diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/cases_transformers.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/cases_transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..8585af46e39e96309f9d749ca9db210b832d1c38
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/cases_transformers.py
@@ -0,0 +1,33 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import warnings
+
+warnings.warn(
+ "pm4py.algo.transformation.to_embeddings.variants.cases_transformers is "
+ "deprecated; use "
+ "pm4py.algo.transformation.trace_encodings.variants.cases_transformers "
+ "instead.",
+ FutureWarning,
+ stacklevel=2,
+)
+
+from pm4py.algo.transformation.trace_encodings.variants.cases_transformers import * # noqa
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/events_transformers.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/events_transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..16badd38ee3ab76d3c756914d861a788a191da61
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/events_transformers.py
@@ -0,0 +1,33 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import warnings
+
+warnings.warn(
+ "pm4py.algo.transformation.to_embeddings.variants.events_transformers is "
+ "deprecated; use "
+ "pm4py.algo.transformation.trace_encodings.variants.events_transformers "
+ "instead.",
+ FutureWarning,
+ stacklevel=2,
+)
+
+from pm4py.algo.transformation.trace_encodings.variants.events_transformers import * # noqa
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..61dc05ca076e3c3446b05d06ecec8a8f5923d693
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.algo.transformation.trace_encodings import algorithm, variants, util
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/algorithm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fb21396f2a2aec84c3f8bf8a9d8e728737f1be6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/algorithm.py
@@ -0,0 +1,122 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Any, Optional, Dict, Union, List, Tuple
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.util import exec_utils
+from pm4py.algo.transformation.trace_encodings.variants import (
+ alignments,
+ bert,
+ cases_transformers,
+ count2vec,
+ doc2vec,
+ event_based,
+ events_transformers,
+ n_grams,
+ one_hot,
+ trace_based,
+ temporal,
+ temporal_lazy,
+ tf_idf,
+ token_replay,
+ word2vec,
+)
+
+
+class Variants(Enum):
+ ALIGNMENTS = alignments
+ BERT = bert
+ COUNT2VEC = count2vec
+ DOC2VEC = doc2vec
+ EVENT_BASED = event_based
+ CASES_TRANSFORMERS = cases_transformers
+ EVENTS_TRANSFORMERS = events_transformers
+ N_GRAMS = n_grams
+ ONE_HOT = one_hot
+ TRACE_BASED = trace_based
+ TEMPORAL = temporal
+ TEMPORAL_LAZY = temporal_lazy
+ TF_IDF = tf_idf
+ TOKEN_REPLAY = token_replay
+ WORD2VEC = word2vec
+
+
+def apply(
+ log: Union[EventLog, pd.DataFrame, EventStream],
+ variant: Any = Variants.TRACE_BASED,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Encodes traces from a log object.
+
+ Parameters
+ ---------------
+ log
+ Event log
+ variant
+ Variant of the feature extraction to use:
+
+ - Variants.ALIGNMENTS => encodes Petri-net alignment diagnostics
+ - Variants.BERT => embeds trace sentences using sentence-transformers
+ - Variants.COUNT2VEC => counts trace token occurrences using scikit-learn
+ - Variants.DOC2VEC => embeds traces as gensim Doc2Vec document vectors
+ - Variants.EVENT_BASED => extracts, for each trace, a list of numerical vectors containing for each event the corresponding features
+ - Variants.CASES_TRANSFORMERS => computes sentence-transformer embeddings at the case level
+ - Variants.EVENTS_TRANSFORMERS => computes sentence-transformer embeddings at the event level
+ - Variants.N_GRAMS => counts contiguous trace token n-grams using scikit-learn
+ - Variants.ONE_HOT => extracts binary trace token occurrence vectors using scikit-learn
+ - Variants.TRACE_BASED => extracts for each trace a single numerical vector containing the features of the trace
+ - Variants.TEMPORAL => extracts temporal features from the traditional event log
+ - Variants.TEMPORAL_LAZY => extracts temporal features from a Polars LazyFrame
+ - Variants.TF_IDF => weights trace tokens/n-grams using scikit-learn TF-IDF
+ - Variants.TOKEN_REPLAY => encodes token-replay diagnostics
+ - Variants.WORD2VEC => aggregates gensim Word2Vec token vectors per trace
+
+ Returns
+ ---------------
+ data
+ Data to provide for decision tree learning
+ feature_names
+ Names of the features, in order
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).apply(log, parameters=parameters)
+
+
+def keep_top_k_per_similarity(
+ log: pd.DataFrame,
+ target_sentence: str,
+ k: int,
+ variant=Variants.CASES_TRANSFORMERS,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> pd.DataFrame:
+ """
+ Keeps the top K events/cases per embedding similarity.
+ """
+ return exec_utils.get_variant(variant).keep_top_k_per_similarity(
+ log, target_sentence, k, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2e0533a906cdd2c15cc134f68f7ea00b0d1c21a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.algo.transformation.trace_encodings.util import petri_net
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/embed_sentence.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/embed_sentence.py
new file mode 100644
index 0000000000000000000000000000000000000000..a364846bd7d6de640b8e0f3e9770ebe67ce420d1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/embed_sentence.py
@@ -0,0 +1,57 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import List, Optional, Dict, Any
+from enum import Enum
+from pm4py.util import exec_utils, constants
+
+
+class Parameters(Enum):
+ EMBEDDING_MODEL = "embedding_model"
+
+
+def apply(sentence: str, parameters: Optional[Dict[Any, Any]] = None) -> List[float]:
+ """
+ Encodes a sentence to embeddings
+
+ Parameters
+ ----------
+ sentence
+ Sentence to be encoded
+ parameters
+ Parameters of the method, including:
+ - Parameters.EMBEDDING_MODEL => embedding model to be used (default: all-MiniLM-L6-v2)
+
+ Returns
+ -------
+ embeddings
+ List of numerical embeddings
+ """
+ if parameters is None:
+ parameters = {}
+
+ embedding_model = exec_utils.get_param_value(Parameters.EMBEDDING_MODEL, parameters,
+ constants.DEFAULT_EMBEDDING_MODEL)
+
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer(embedding_model)
+
+ return model.encode([sentence])[0]
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/locally_linear_embedding.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/locally_linear_embedding.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa7e261f32d710d8941998c0a0320576ffefc8a5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/locally_linear_embedding.py
@@ -0,0 +1,135 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import math
+from datetime import datetime
+from enum import Enum
+from typing import Optional, Dict, Any, Tuple, List
+
+import numpy as np
+from pm4py.util import ml_utils
+
+from pm4py.objects.conversion.log import converter as log_converter
+from pm4py.objects.log.obj import EventLog
+from pm4py.algo.transformation.trace_encodings import (
+ algorithm as trace_encodings,
+)
+from pm4py.objects.log.util import sorting
+from pm4py.util import constants, xes_constants
+from pm4py.util import exec_utils, pandas_utils
+
+
+class Parameters(Enum):
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+
+
+def smooth(y: np.ndarray, box_pts: int) -> np.ndarray:
+ """
+ Smooths the points in y with a weighted average.
+
+ Parameters
+ ----------------
+ y
+ Points
+ box_pts
+ Size of the weighted average
+
+ Returns
+ ----------------
+ y_smooth
+ Smoothened y
+ """
+ box = np.ones(box_pts) / box_pts
+ y_smooth = np.convolve(y, box, mode="same")
+ return y_smooth
+
+
+def apply(
+ log: EventLog, parameters: Optional[Dict[str, Any]] = None
+) -> Tuple[List[datetime], np.ndarray]:
+ """
+ Analyse the evolution of the features over the time using a locally linear embedding.
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Variant-specific parameters, including:
+ - Parameters.ACTIVITY_KEY => the activity key
+ - Parameters.TIMESTAMP_KEY => the timestamp key
+ - Parameters.CASE_ID_KEY => the case ID key
+
+ Returns
+ ----------------
+ x
+ Date attributes (starting points of the cases)
+ y
+ Deviation from the standard behavior (higher absolute values of y signal a higher deviation
+ from the standard behavior)
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+
+ if pandas_utils.check_is_pandas_dataframe(log):
+ # keep only the needed columns
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ log = log[[case_id_key, activity_key, timestamp_key]]
+
+ log = log_converter.apply(
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+ log = sorting.sort_timestamp(log, timestamp_key)
+
+ x = [trace[0][timestamp_key] for trace in log]
+ data, feature_names = trace_encodings.apply(
+ log,
+ parameters={
+ "str_ev_attr": [activity_key],
+ "str_evsucc_attr": [activity_key],
+ },
+ )
+ data = np.array([np.array(x) for x in data])
+
+ tsne = ml_utils.LocallyLinearEmbedding(
+ n_components=1, eigen_solver="dense"
+ )
+ data = tsne.fit_transform(data)
+ data = np.ndarray.flatten(data)
+
+ y = data
+ smooth_amount = 1 + math.floor(math.sqrt(len(y)))
+ y = smooth(y, smooth_amount)
+
+ return x, y
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/petri_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/petri_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..7252c32d44358c8161d37858d3734fa6e648f2d2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/petri_net.py
@@ -0,0 +1,107 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Any, Dict, Optional, Tuple, Union
+
+import pandas as pd
+
+from pm4py.objects.conversion.log import converter as log_converter
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.objects.petri_net.obj import Marking, PetriNet
+from pm4py.util import constants, exec_utils, xes_constants
+
+
+class Parameters(Enum):
+ NET = "net"
+ PETRI_NET = "petri_net"
+ INITIAL_MARKING = "initial_marking"
+ FINAL_MARKING = "final_marking"
+ DISCOVER_MODEL = "discover_model"
+ DISCOVERY_VARIANT = "discovery_variant"
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+
+
+def get_log_and_model(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Tuple[EventLog, PetriNet, Marking, Marking]:
+ """
+ Resolves an EventLog and Petri net for PM-based trace encodings.
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_log = log_converter.apply(
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+
+ net = exec_utils.get_param_value(Parameters.NET, parameters, None)
+ if net is None:
+ net = exec_utils.get_param_value(Parameters.PETRI_NET, parameters, None)
+ initial_marking = exec_utils.get_param_value(
+ Parameters.INITIAL_MARKING, parameters, None
+ )
+ final_marking = exec_utils.get_param_value(
+ Parameters.FINAL_MARKING, parameters, None
+ )
+
+ if net is not None and initial_marking is not None and final_marking is not None:
+ return event_log, net, initial_marking, final_marking
+
+ discover_model = exec_utils.get_param_value(
+ Parameters.DISCOVER_MODEL, parameters, True
+ )
+ if not discover_model:
+ raise ValueError(
+ "PM-based trace encodings require net, initial_marking, and "
+ "final_marking when discover_model is False."
+ )
+
+ from pm4py.algo.discovery.inductive import algorithm as inductive_miner
+ from pm4py.objects.conversion.process_tree import converter as pt_converter
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY
+ )
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ discovery_variant = exec_utils.get_param_value(
+ Parameters.DISCOVERY_VARIANT, parameters, inductive_miner.Variants.IM
+ )
+
+ discovery_parameters = dict(parameters)
+ discovery_parameters[Parameters.ACTIVITY_KEY] = activity_key
+ discovery_parameters[Parameters.TIMESTAMP_KEY] = timestamp_key
+ discovery_parameters[Parameters.CASE_ID_KEY] = case_id_key
+
+ process_tree = inductive_miner.apply(
+ event_log, parameters=discovery_parameters, variant=discovery_variant
+ )
+ net, initial_marking, final_marking = pt_converter.apply(process_tree)
+
+ return event_log, net, initial_marking, final_marking
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/similarity.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/similarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..d91d3381cf52bc178e81fedecb01b360dcbf1b2f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/similarity.py
@@ -0,0 +1,58 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import numpy as np
+from typing import List, Union, Optional, Dict, Any
+from pm4py.algo.transformation.trace_encodings.util import embed_sentence
+
+
+def cosine_similarity(a, b):
+ return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
+
+
+def apply(target_embedding: Union[str, List[float]], embeddings_list: List[List[float]], parameters: Optional[Dict[Any, Any]] = None) -> List[float]:
+ """
+ Computes the cosine similarity between the embeddings of a target sentence and a list of embeddings
+ (at the case or event level)
+
+ Parameters
+ -----------------
+ target_embedding
+ Target sentence (embeddings)
+ embeddings_list
+ List of embeddings (at the case or event level)
+ parameters
+ Parameters of the method
+
+ Returns
+ ------------------
+ similarity_list
+ List containing the cosine similarities between each entry and the target sentence
+ """
+ if parameters is None:
+ parameters = {}
+
+ if isinstance(target_embedding, str):
+ target_embedding = embed_sentence.apply(target_embedding, parameters=parameters)
+
+ similarity_list = [cosine_similarity(target_embedding, emb) for emb in embeddings_list]
+
+ return similarity_list
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/sklearn_vectorization.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/sklearn_vectorization.py
new file mode 100644
index 0000000000000000000000000000000000000000..35dd2164008c248af570aa79ae760f2dc9e5f2c5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/sklearn_vectorization.py
@@ -0,0 +1,169 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.util import exec_utils
+from pm4py.algo.transformation.trace_encodings.util.trace_text import (
+ log_to_trace_tokens,
+)
+
+
+class Parameters(Enum):
+ NGRAM_RANGE = "ngram_range"
+ RETURN_SPARSE = "return_sparse"
+ VECTORIZER = "vectorizer"
+ FIT_VECTORIZER = "fit_vectorizer"
+
+
+def _ngrams(tokens: List[str], ngram_range: Tuple[int, int]) -> List[str]:
+ terms = []
+ min_n, max_n = ngram_range
+ for n in range(min_n, max_n + 1):
+ if n <= 0:
+ continue
+ for i in range(0, len(tokens) - n + 1):
+ terms.append(" >> ".join(tokens[i : i + n]))
+ return terms
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ binary: bool = False,
+ ngram_range: Tuple[int, int] = (1, 1),
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Vectorizes trace token sequences through scikit-learn CountVectorizer.
+ """
+ if parameters is None:
+ parameters = {}
+
+ return_sparse = exec_utils.get_param_value(
+ Parameters.RETURN_SPARSE, parameters, False
+ )
+ vectorizer = exec_utils.get_param_value(
+ Parameters.VECTORIZER, parameters, None
+ )
+ fit_vectorizer = exec_utils.get_param_value(
+ Parameters.FIT_VECTORIZER, parameters, True
+ )
+ ngram_range = exec_utils.get_param_value(
+ Parameters.NGRAM_RANGE, parameters, ngram_range
+ )
+
+ _, traces = log_to_trace_tokens(log, parameters=parameters)
+
+ if vectorizer is None:
+ try:
+ from sklearn.feature_extraction.text import CountVectorizer
+ except ImportError as exc:
+ raise ImportError(
+ "The selected trace encoding uses scikit-learn. Please install "
+ "scikit-learn to use this variant."
+ ) from exc
+
+ vectorizer = CountVectorizer(
+ analyzer=lambda tokens: _ngrams(tokens, ngram_range),
+ binary=binary,
+ lowercase=False,
+ )
+
+ if not traces:
+ return [], []
+
+ try:
+ if fit_vectorizer:
+ matrix = vectorizer.fit_transform(traces)
+ else:
+ matrix = vectorizer.transform(traces)
+ except ValueError as exc:
+ if "empty vocabulary" not in str(exc):
+ raise
+ return [[] for _ in traces], []
+
+ feature_names = list(vectorizer.get_feature_names_out())
+ data = matrix if return_sparse else matrix.toarray().tolist()
+
+ return data, feature_names
+
+
+def apply_tfidf(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ ngram_range: Tuple[int, int] = (1, 1),
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Vectorizes trace token sequences through scikit-learn TfidfVectorizer.
+ """
+ if parameters is None:
+ parameters = {}
+
+ return_sparse = exec_utils.get_param_value(
+ Parameters.RETURN_SPARSE, parameters, False
+ )
+ vectorizer = exec_utils.get_param_value(
+ Parameters.VECTORIZER, parameters, None
+ )
+ fit_vectorizer = exec_utils.get_param_value(
+ Parameters.FIT_VECTORIZER, parameters, True
+ )
+ ngram_range = exec_utils.get_param_value(
+ Parameters.NGRAM_RANGE, parameters, ngram_range
+ )
+
+ _, traces = log_to_trace_tokens(log, parameters=parameters)
+
+ if vectorizer is None:
+ try:
+ from sklearn.feature_extraction.text import TfidfVectorizer
+ except ImportError as exc:
+ raise ImportError(
+ "The selected trace encoding uses scikit-learn. Please install "
+ "scikit-learn to use this variant."
+ ) from exc
+
+ vectorizer = TfidfVectorizer(
+ analyzer=lambda tokens: _ngrams(tokens, ngram_range),
+ lowercase=False,
+ )
+
+ if not traces:
+ return [], []
+
+ try:
+ if fit_vectorizer:
+ matrix = vectorizer.fit_transform(traces)
+ else:
+ matrix = vectorizer.transform(traces)
+ except ValueError as exc:
+ if "empty vocabulary" not in str(exc):
+ raise
+ return [[] for _ in traces], []
+
+ feature_names = list(vectorizer.get_feature_names_out())
+ data = matrix if return_sparse else matrix.toarray().tolist()
+
+ return data, feature_names
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/trace_text.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/trace_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..31dcdbf4c407e92d64ce01bd541f5beafc7d6179
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/trace_text.py
@@ -0,0 +1,201 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import pandas as pd
+
+from pm4py.objects.conversion.log import converter as log_converter
+from pm4py.objects.log.obj import EventLog, EventStream, Trace, Event
+from pm4py.util import constants, exec_utils, xes_constants
+
+
+class Parameters(Enum):
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ INCLUDE_ATTRIBUTE_NAMES = "include_attribute_names"
+ COMBINE_EVENT_ATTRIBUTES = "combine_event_attributes"
+ MISSING_VALUE = "missing_value"
+
+
+def get_event_attributes(
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> List[str]:
+ """
+ Gets the event attributes used to build each event token.
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ attribute_key = exec_utils.get_param_value(
+ Parameters.ATTRIBUTE_KEY, parameters, activity_key
+ )
+ event_attributes = exec_utils.get_param_value(
+ Parameters.EVENT_ATTRIBUTES, parameters, None
+ )
+
+ if event_attributes is None:
+ event_attributes = [attribute_key]
+ elif isinstance(event_attributes, str):
+ event_attributes = [event_attributes]
+ else:
+ event_attributes = list(event_attributes)
+
+ return event_attributes
+
+
+def get_trace_attributes(
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> List[str]:
+ """
+ Gets trace-level attributes to add as case context tokens.
+ """
+ if parameters is None:
+ parameters = {}
+
+ trace_attributes = exec_utils.get_param_value(
+ Parameters.TRACE_ATTRIBUTES, parameters, []
+ )
+ if isinstance(trace_attributes, str):
+ trace_attributes = [trace_attributes]
+
+ return list(trace_attributes)
+
+
+def format_event_tokens(
+ event: Event,
+ event_attributes: List[str],
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> List[str]:
+ """
+ Formats one event as one or more textual tokens.
+ """
+ if parameters is None:
+ parameters = {}
+
+ include_attribute_names = exec_utils.get_param_value(
+ Parameters.INCLUDE_ATTRIBUTE_NAMES, parameters, len(event_attributes) > 1
+ )
+ combine_event_attributes = exec_utils.get_param_value(
+ Parameters.COMBINE_EVENT_ATTRIBUTES, parameters, True
+ )
+ missing_value = exec_utils.get_param_value(
+ Parameters.MISSING_VALUE, parameters, "UNDEFINED"
+ )
+
+ tokens = []
+ for attr in event_attributes:
+ value = event[attr] if attr in event else missing_value
+ if include_attribute_names:
+ tokens.append(str(attr) + "=" + str(value))
+ else:
+ tokens.append(str(value))
+
+ if combine_event_attributes:
+ return ["|".join(tokens)]
+ return tokens
+
+
+def trace_to_tokens(
+ trace: Trace,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> List[str]:
+ """
+ Converts a trace to a sequence of tokens.
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_attributes = get_event_attributes(parameters)
+ trace_attributes = get_trace_attributes(parameters)
+ missing_value = exec_utils.get_param_value(
+ Parameters.MISSING_VALUE, parameters, "UNDEFINED"
+ )
+
+ tokens = []
+ for attr in trace_attributes:
+ if attr in trace.attributes:
+ value = trace.attributes[attr]
+ elif attr.startswith(constants.CASE_ATTRIBUTE_PREFIX) and attr[
+ len(constants.CASE_ATTRIBUTE_PREFIX) :
+ ] in trace.attributes:
+ value = trace.attributes[
+ attr[len(constants.CASE_ATTRIBUTE_PREFIX) :]
+ ]
+ else:
+ value = missing_value
+ tokens.append("trace:" + str(attr) + "=" + str(value))
+
+ for event in trace:
+ tokens.extend(format_event_tokens(event, event_attributes, parameters))
+
+ return tokens
+
+
+def log_to_trace_tokens(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Tuple[List[Any], List[List[str]]]:
+ """
+ Converts a log to case identifiers and trace token sequences.
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, xes_constants.DEFAULT_TRACEID_KEY
+ )
+
+ log = log_converter.apply(
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+
+ case_ids = []
+ trace_tokens = []
+ for index, trace in enumerate(log):
+ case_id = trace.attributes.get(case_id_key, None)
+ if case_id is None and str(case_id_key).startswith(
+ constants.CASE_ATTRIBUTE_PREFIX
+ ):
+ case_id = trace.attributes.get(
+ str(case_id_key)[len(constants.CASE_ATTRIBUTE_PREFIX) :],
+ None,
+ )
+ if case_id is None:
+ case_id = trace.attributes.get(xes_constants.DEFAULT_TRACEID_KEY, index)
+ case_ids.append(case_id)
+ trace_tokens.append(trace_to_tokens(trace, parameters=parameters))
+
+ return case_ids, trace_tokens
+
+
+def tokens_to_sentence(tokens: List[str]) -> str:
+ """
+ Converts trace tokens to a sentence consumed by text embedding models.
+ """
+ return " ".join(tokens)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7150f7dc395e5dd3d362dbd5ae9339a1c6949f44
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/__init__.py
@@ -0,0 +1,38 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.algo.transformation.trace_encodings.variants import (
+ alignments,
+ bert,
+ cases_transformers,
+ count2vec,
+ doc2vec,
+ event_based,
+ events_transformers,
+ n_grams,
+ one_hot,
+ temporal,
+ temporal_lazy,
+ tf_idf,
+ token_replay,
+ trace_based,
+ word2vec,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/alignments.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/alignments.py
new file mode 100644
index 0000000000000000000000000000000000000000..d06050c327484a10427791a2b8d11a833125493d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/alignments.py
@@ -0,0 +1,153 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Alignment-based trace encoding.
+
+From an event-log point of view, each trace is aligned with a Petri net. The
+alignment finds a least-cost explanation of how the trace can be matched to
+the model through synchronous moves, log moves, and model moves. The
+alignment diagnostics become the trace vector: is-fit, fitness, cost,
+best-worst cost, visited states, queued states, and traversed arcs.
+
+Example with a model A -> B -> C:
+ case 1: A, B, C
+ case 2: A, C
+
+case 1 aligns synchronously with the model and receives zero alignment cost.
+case 2 needs a model move for B or a related deviation, so its cost is
+greater than zero and its fitness is lower.
+
+The Petri net can be passed with net, initial_marking, and final_marking. If
+no model is passed, the variant discovers one from the log using PM4Py's
+Inductive Miner.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+The survey lists alignments as a PM-based encoding and points to PM4Py as the
+maintained implementation. This variant delegates alignment computation to
+PM4Py's Petri-net alignments and exposes per-trace diagnostics as vectors.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import petri_net
+
+
+class Parameters(Enum):
+ NET = "net"
+ PETRI_NET = "petri_net"
+ INITIAL_MARKING = "initial_marking"
+ FINAL_MARKING = "final_marking"
+ DISCOVER_MODEL = "discover_model"
+ ALIGNMENT_VARIANT = "alignment_variant"
+
+
+FEATURE_NAMES = [
+ "@@alignment_is_fit",
+ "@@alignment_fitness",
+ "@@alignment_cost",
+ "@@alignment_bwc",
+ "@@alignment_visited_states",
+ "@@alignment_queued_states",
+ "@@alignment_traversed_arcs",
+]
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace with alignment conformance diagnostics.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - NET/PETRI_NET, INITIAL_MARKING, FINAL_MARKING: existing Petri net
+ model to align against.
+ - DISCOVER_MODEL: if True, discover a Petri net when no model is
+ supplied.
+ - ALIGNMENT_VARIANT: PM4Py Petri-net alignment variant.
+
+ Returns
+ -------
+ data
+ One row per trace with alignment diagnostics.
+ feature_names
+ Diagnostic names corresponding to the columns of data.
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.algo.conformance.alignments.petri_net import (
+ algorithm as alignments,
+ )
+ from pm4py.util import exec_utils
+
+ event_log, net, initial_marking, final_marking = petri_net.get_log_and_model(
+ log, parameters=parameters
+ )
+ variant = exec_utils.get_param_value(
+ Parameters.ALIGNMENT_VARIANT,
+ parameters,
+ alignments.DEFAULT_VARIANT,
+ )
+
+ alignment_results = alignments.apply(
+ event_log,
+ net,
+ initial_marking,
+ final_marking,
+ parameters=parameters,
+ variant=variant,
+ )
+
+ data = []
+ for alignment in alignment_results:
+ if alignment is None:
+ data.append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
+ else:
+ fitness = float(alignment.get("fitness", 0.0))
+ data.append(
+ [
+ 1.0 if fitness == 1.0 else 0.0,
+ fitness,
+ float(alignment.get("cost", 0.0)),
+ float(alignment.get("bwc", 0.0)),
+ float(alignment.get("visited_states", 0.0)),
+ float(alignment.get("queued_states", 0.0)),
+ float(alignment.get("traversed_arcs", 0.0)),
+ ]
+ )
+
+ return data, FEATURE_NAMES
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/bert.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..30b384fa823a014f40e1aecb470c12032cb4804d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/bert.py
@@ -0,0 +1,117 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Trace-level BERT-style sentence embedding.
+
+From an event-log point of view, each case is converted to a sentence and
+then embedded by a transformer model. By default, the sentence is the
+activity sequence, but additional event and trace attributes can be included
+to embed a richer perspective.
+
+Example with activity-only encoding:
+ case 1: A, B, C -> "A B C"
+ case 2: A, C -> "A C"
+
+A BERT/sentence-transformer model maps each sentence to a dense vector. The
+output has one row per trace and one column per embedding dimension.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+This variant delegates embedding computation to sentence-transformers. The
+default model name is intentionally configurable because model availability is
+environment-specific.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import trace_text
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ BERT_MODEL = "bert_model"
+ EMBEDDING_MODEL = "embedding_model"
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace as a dense transformer/BERT-style sentence vector.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
+ the activity attribute.
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
+ - BERT_MODEL/EMBEDDING_MODEL: sentence-transformers model name or path.
+
+ Returns
+ -------
+ data
+ One row per trace, containing transformer embedding dimensions.
+ feature_names
+ Dimension names corresponding to the columns of data.
+ """
+ if parameters is None:
+ parameters = {}
+
+ try:
+ from sentence_transformers import SentenceTransformer
+ except ImportError as exc:
+ raise ImportError(
+ "The BERT trace encoding uses sentence-transformers. Please "
+ "install sentence-transformers to use this variant."
+ ) from exc
+
+ model_name = exec_utils.get_param_value(
+ Parameters.BERT_MODEL,
+ parameters,
+ exec_utils.get_param_value(
+ Parameters.EMBEDDING_MODEL, parameters, "bert-base-nli-mean-tokens"
+ ),
+ )
+
+ _, traces = trace_text.log_to_trace_tokens(log, parameters=parameters)
+ sentences = [trace_text.tokens_to_sentence(trace) for trace in traces]
+ model = SentenceTransformer(model_name)
+ embeddings = model.encode(sentences)
+ data = [embedding.tolist() for embedding in embeddings]
+
+ vector_size = len(data[0]) if data else 0
+ feature_names = ["@@bert_dim_" + str(i) for i in range(vector_size)]
+ return data, feature_names
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/cases_transformers.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/cases_transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..77e1d7a3409b8b835c93d761653ceb6e1bd5922d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/cases_transformers.py
@@ -0,0 +1,161 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import exec_utils, constants, xes_constants
+from typing import Optional, Dict, Any, List, Tuple
+from pm4py.objects.conversion.log import converter as log_converter
+import pandas as pd
+from enum import Enum
+from pm4py.algo.transformation.trace_encodings.util import similarity
+from pm4py.algo.transformation.trace_encodings.util import trace_text
+
+
+class Parameters(Enum):
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ EMBEDDING_MODEL = "embedding_model"
+ ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+
+
+def apply(log: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None) -> Tuple[List[str], List[List[float]]]:
+ """
+ Computes one text embedding per case.
+
+ From an event-log point of view, each trace is converted to a sentence and
+ then embedded by a sentence-transformers model. By default, the sentence is
+ the sequence of activity names. Additional event attributes and trace
+ attributes can be included to represent a richer perspective.
+
+ Example with activity-only encoding:
+ case 1: A, B, C -> "A B C"
+ case 2: A, C -> "A C"
+
+ Example with event_attributes=["concept:name", "org:resource"]:
+ event A by R1 becomes "concept:name=A|org:resource=R1"
+
+ The output is a list of case identifiers and a list of dense embedding
+ vectors, one vector per case.
+
+ Parameters
+ -----------------
+ log
+ Pandas dataframe
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.CASE_ID_KEY => the case identifier column
+ - Parameters.EMBEDDING_MODEL => the embedding to be used (default: all-MiniLM-L6-v2)
+ - Parameters.ATTRIBUTE_KEY => the attribute to be used for the concatenation
+ - Parameters.EVENT_ATTRIBUTES => event attributes to include in the case sentence. If omitted, ATTRIBUTE_KEY is used.
+ - Parameters.TRACE_ATTRIBUTES => trace attributes to include as case context tokens.
+
+ Returns
+ ----------------
+ cases_identifiers
+ The list of all the case identifiers
+ embeddings_list
+ The list of embeddings for the considered cases
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME)
+ attribute_key = exec_utils.get_param_value(Parameters.ATTRIBUTE_KEY, parameters, xes_constants.DEFAULT_NAME_KEY)
+ embedding_model = exec_utils.get_param_value(Parameters.EMBEDDING_MODEL, parameters,
+ constants.DEFAULT_EMBEDDING_MODEL)
+
+ cases_identifiers = []
+ sentences = []
+
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer(embedding_model)
+
+ event_attributes = exec_utils.get_param_value(
+ Parameters.EVENT_ATTRIBUTES, parameters, None
+ )
+ trace_attributes = exec_utils.get_param_value(
+ Parameters.TRACE_ATTRIBUTES, parameters, []
+ )
+
+ if event_attributes is not None or trace_attributes:
+ cases_identifiers, traces = trace_text.log_to_trace_tokens(
+ log, parameters=parameters
+ )
+ sentences = [trace_text.tokens_to_sentence(x) for x in traces]
+ else:
+ log = log_converter.apply(log, variant=log_converter.Variants.TO_DATA_FRAME)
+ cases = log.groupby(case_id_key)[attribute_key].agg(list)
+ cases = cases.to_dict()
+
+ for k, v in cases.items():
+ cases_identifiers.append(k)
+ sentences.append(" ".join(str(x) for x in v))
+
+ embeddings_list = list(model.encode(sentences))
+
+ return cases_identifiers, embeddings_list
+
+
+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:
+ """
+ Keeps the top K cases by embedding similarity with the given sentence.
+
+ For example, after encoding cases as activity sentences, the query
+ "rejected cases" is embedded with the same model and compared with each
+ case embedding using cosine similarity.
+
+ Parameters
+ ----------------
+ log
+ Pandas dataframe
+ target_sentence
+ Target sentence
+ k
+ Number of similar cases to retain
+ cases_identifiers
+ (Optional) the list of cases identifiers in the log, as returned by the 'apply' method
+ embeddings_list
+ (Optional) the list of embeddings for such cases, as returned by the 'apply' method
+ parameters
+ Other parameters of the method
+
+ Returns
+ -----------------
+ filtered_log
+ Event log filtered on the top K cases according to the similarity metric.
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME)
+
+ if cases_identifiers is None or embeddings_list is None:
+ cases_identifiers, embeddings_list = apply(log, parameters=parameters)
+
+ sim = similarity.apply(target_sentence, embeddings_list)
+ cases = [(cases_identifiers[i], sim[i]) for i in range(len(cases_identifiers))]
+ cases.sort(key=lambda x: (x[1], x[0]), reverse=True)
+ cases = cases[:k]
+ cases = [x[0] for x in cases]
+
+ log = log[log[case_id_key].isin(cases)]
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/count2vec.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/count2vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..232efb87ff2329de82175ae85427b8243f973a98
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/count2vec.py
@@ -0,0 +1,96 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Trace-level count2vec encoding.
+
+From an event-log point of view, each case is read as a sequence of tokens.
+By default, the token of an event is its activity name. The output has one
+row per trace and one column per token; the cell is the number of times the
+token appears in that trace.
+
+Example with the activity attribute:
+ case 1: A, B, A
+ case 2: A, C
+
+The vocabulary is [A, B, C], and the encoded matrix is:
+ case 1 -> [2, 1, 0]
+ case 2 -> [1, 0, 1]
+
+If event_attributes includes additional columns, each event token can include
+context such as activity, resource, and amount before counts are computed.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+The survey lists count2vec as a baseline encoding and uses sklearn as the
+open-source implementation source. This variant uses scikit-learn's
+CountVectorizer over trace tokens.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
+
+
+class Parameters(Enum):
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ RETURN_SPARSE = "return_sparse"
+ VECTORIZER = "vectorizer"
+ FIT_VECTORIZER = "fit_vectorizer"
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace as token frequency counts.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
+ the activity attribute.
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
+
+ Returns
+ -------
+ data
+ One row per trace, one count per discovered token.
+ feature_names
+ Token names corresponding to the columns of data.
+ """
+ return sklearn_vectorization.apply(
+ log, binary=False, ngram_range=(1, 1), parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/doc2vec.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/doc2vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..34f207fdbf93c048208a6a105a7d3aa52291fc60
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/doc2vec.py
@@ -0,0 +1,138 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Trace-level Doc2Vec encoding.
+
+From an event-log point of view, each case is treated as one document and
+each event token is treated as one word in that document. A Doc2Vec model
+learns a dense vector directly for each trace/document.
+
+Example with activity tokens:
+ case 1: A, B, C
+ case 2: A, B, D
+
+Doc2Vec learns one vector for "A B C" and one vector for "A B D". Unlike
+Word2Vec, no explicit mean over event-token vectors is needed because the
+document vector is trained directly.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+This variant delegates model training/inference to gensim's maintained
+Doc2Vec implementation.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import trace_text
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ MODEL = "model"
+ VECTOR_SIZE = "vector_size"
+ WINDOW = "window"
+ MIN_COUNT = "min_count"
+ WORKERS = "workers"
+ EPOCHS = "epochs"
+ DM = "dm"
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace as a gensim Doc2Vec document vector.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
+ the activity attribute.
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
+ - MODEL: pre-trained gensim Doc2Vec model. If omitted, a model is
+ trained on the provided log.
+ - VECTOR_SIZE, WINDOW, MIN_COUNT, WORKERS, EPOCHS, DM: gensim Doc2Vec
+ training parameters.
+
+ Returns
+ -------
+ data
+ One row per trace, containing Doc2Vec dimensions.
+ feature_names
+ Dimension names corresponding to the columns of data.
+ """
+ if parameters is None:
+ parameters = {}
+
+ try:
+ from gensim.models.doc2vec import Doc2Vec, TaggedDocument
+ except ImportError as exc:
+ raise ImportError(
+ "The DOC2VEC trace encoding uses gensim. Please install gensim "
+ "to use this variant."
+ ) from exc
+
+ _, traces = trace_text.log_to_trace_tokens(log, parameters=parameters)
+ vector_size = exec_utils.get_param_value(
+ Parameters.VECTOR_SIZE, parameters, 100
+ )
+ epochs = exec_utils.get_param_value(Parameters.EPOCHS, parameters, 20)
+ model = exec_utils.get_param_value(Parameters.MODEL, parameters, None)
+
+ if model is None:
+ documents = [
+ TaggedDocument(words=trace, tags=[str(index)])
+ for index, trace in enumerate(traces)
+ ]
+ model = Doc2Vec(
+ documents=documents,
+ vector_size=vector_size,
+ window=exec_utils.get_param_value(Parameters.WINDOW, parameters, 5),
+ min_count=exec_utils.get_param_value(Parameters.MIN_COUNT, parameters, 1),
+ workers=exec_utils.get_param_value(Parameters.WORKERS, parameters, 1),
+ dm=exec_utils.get_param_value(Parameters.DM, parameters, 1),
+ epochs=epochs,
+ )
+ data = [model.dv[str(index)].tolist() for index in range(len(traces))]
+ else:
+ vector_size = int(model.vector_size)
+ data = [
+ model.infer_vector(trace, epochs=epochs).tolist()
+ for trace in traces
+ ]
+
+ feature_names = ["@@doc2vec_dim_" + str(i) for i in range(vector_size)]
+ return data, feature_names
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/event_based.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/event_based.py
new file mode 100644
index 0000000000000000000000000000000000000000..462e9651e71e7e96adfe8e2604da88c922cd203b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/event_based.py
@@ -0,0 +1,227 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections import Counter
+from enum import Enum
+from typing import Optional, List, Dict, Any, Tuple, Union
+
+import numpy as np
+
+from pm4py.objects.log.obj import EventLog
+from pm4py.util import exec_utils
+from pm4py.objects.conversion.log import converter
+
+
+class Parameters(Enum):
+ STR_EVENT_ATTRIBUTES = "str_ev_attr"
+ NUM_EVENT_ATTRIBUTES = "num_ev_attr"
+ FEATURE_NAMES = "feature_names"
+ MIN_NUM_DIFF_STR_VALUES = "min_num_diff_str_values"
+ MAX_NUM_DIFF_STR_VALUES = "max_num_diff_str_values"
+
+
+def extract_all_ev_features_names_from_log(
+ log: EventLog,
+ str_ev_attr: List[str],
+ num_ev_attr: List[str],
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> List[str]:
+ """
+ Extracts the feature names from an event log.
+
+ Parameters
+ ---------------
+ log
+ Event log
+ str_ev_attr
+ (if provided) list of string event attributes to consider in extracting the feature names
+ num_ev_attr
+ (if provided) list of integer event attributes to consider in extracting the feature names
+ parameters
+ Parameters, including:
+ - MIN_NUM_DIFF_STR_VALUES => minimum number of distinct values to include an attribute as feature(s)
+ - MAX_NUM_DIFF_STR_VALUES => maximum number of distinct values to include an attribute as feature(s)
+
+ Returns
+ ----------------
+ feature_names
+ List of feature names
+ """
+ if parameters is None:
+ parameters = {}
+
+ min_num_diff_str_values = exec_utils.get_param_value(
+ Parameters.MIN_NUM_DIFF_STR_VALUES, parameters, 2
+ )
+ max_num_diff_str_values = exec_utils.get_param_value(
+ Parameters.MAX_NUM_DIFF_STR_VALUES, parameters, 500
+ )
+
+ str_features = {}
+ num_features = Counter()
+ count_events = 0
+ for trace in log:
+ for event in trace:
+ count_events += 1
+ for attr_name in event:
+ attr_value = event[attr_name]
+ if isinstance(attr_value, str) and (
+ str_ev_attr is None or attr_name in str_ev_attr
+ ):
+ if attr_name not in str_features:
+ str_features[attr_name] = set()
+ str_features[attr_name].add(
+ "event:" + attr_name + "@" + attr_value
+ )
+ elif isinstance(attr_value, int) or isinstance(
+ attr_value, float
+ ):
+ if num_ev_attr is None or attr_name in num_ev_attr:
+ num_features["event:" + attr_name] += 1
+ num_features = list(
+ {x for x, y in num_features.items() if y == count_events}
+ )
+ str_features = list(
+ {
+ z
+ for x, y in str_features.items()
+ for z in y
+ if min_num_diff_str_values <= len(y) <= max_num_diff_str_values
+ }
+ )
+
+ feature_names = str_features + num_features
+ feature_names = sorted(feature_names)
+
+ return feature_names
+
+
+def extract_features(
+ log: EventLog,
+ feature_names: List[str],
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Extracts the matrix of the features from an event log
+
+ Parameters
+ ---------------
+ log
+ Event log
+ feature_names
+ Features to consider (in the given order)
+
+ Returns
+ -------------
+ data
+ Data to provide for decision tree learning
+ feature_names
+ Names of the features, in order
+ """
+ v1 = max(len(trace) for trace in log)
+ v2 = len(feature_names)
+ data = np.zeros((len(log), v1, v2), dtype=np.float32)
+
+ for i1, trace in enumerate(log):
+ for i2, event in enumerate(trace):
+ str_features = set()
+ num_features = {}
+ for attr_name in event:
+ attr_value = event[attr_name]
+ if isinstance(attr_value, str):
+ str_features.add("event:" + attr_name + "@" + attr_value)
+ elif isinstance(attr_value, int) or isinstance(
+ attr_value, float
+ ):
+ num_features["event:" + attr_name] = float(attr_value)
+ for attr in str_features:
+ if attr in feature_names:
+ data[i1, i2, feature_names.index(attr)] = 1.0
+ for attr in num_features:
+ if attr in feature_names:
+ data[i1, i2, feature_names.index(attr)] = float(
+ num_features[attr]
+ )
+
+ return data, feature_names
+
+
+def apply(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Encodes each event in each trace as a feature vector.
+
+ From an event-log point of view, the result keeps the trace/event grid:
+ each trace becomes a sequence of event vectors, padded to the maximum trace
+ length in the log. String event attributes are one-hot encoded; numeric
+ event attributes are copied as numeric values.
+
+ Example with event attribute "concept:name":
+ case 1: A, B
+ case 2: A
+
+ The vocabulary is [event:concept:name@A, event:concept:name@B]. If the
+ maximum trace length is 2, the encoded tensor is:
+ case 1 -> [[1, 0], [0, 1]]
+ case 2 -> [[1, 0], [0, 0]]
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm, including:
+ - STR_EVENT_ATTRIBUTES => string event attributes to consider in the features extraction
+ - NUM_EVENT_ATTRIBUTES => numeric event attributes to consider in the features extraction
+ - FEATURE_NAMES => features to consider (in the given order)
+
+ Returns
+ -------------
+ data
+ Data to provide for decision tree learning
+ feature_names
+ Names of the features, in order
+ """
+ if parameters is None:
+ parameters = {}
+
+ str_ev_attr = exec_utils.get_param_value(
+ Parameters.STR_EVENT_ATTRIBUTES, parameters, None
+ )
+ num_ev_attr = exec_utils.get_param_value(
+ Parameters.NUM_EVENT_ATTRIBUTES, parameters, None
+ )
+ feature_names = exec_utils.get_param_value(
+ Parameters.FEATURE_NAMES, parameters, None
+ )
+
+ log = converter.apply(
+ log, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+
+ if feature_names is None:
+ feature_names = extract_all_ev_features_names_from_log(
+ log, str_ev_attr, num_ev_attr, parameters=parameters
+ )
+
+ return extract_features(log, feature_names, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/events_transformers.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/events_transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cbfa0a8308f1374afb214d10f3837be0b7f007f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/events_transformers.py
@@ -0,0 +1,173 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import exec_utils, constants, xes_constants
+from typing import Optional, Dict, Any, List, Tuple
+from pm4py.objects.conversion.log import converter as log_converter
+import pandas as pd
+from enum import Enum
+from pm4py.algo.transformation.trace_encodings.util import similarity
+from pm4py.algo.transformation.trace_encodings.util import trace_text
+
+
+class Parameters(Enum):
+ EVENT_ID_KEY = "event_id_key"
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ EMBEDDING_MODEL = "embedding_model"
+ ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY
+ EVENT_ATTRIBUTES = "event_attributes"
+ KEEP_CASES = "keep_cases"
+
+
+def apply(log: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None) -> Tuple[List[str], List[List[float]]]:
+ """
+ Computes one text embedding per event.
+
+ From an event-log point of view, each event is converted to a short
+ sentence and then embedded by a sentence-transformers model. By default,
+ the sentence is the activity name. Additional event attributes can be
+ included to represent a richer event perspective.
+
+ Example with activity-only encoding:
+ event {concept:name: "A"} -> "A"
+
+ Example with event_attributes=["concept:name", "org:resource"]:
+ event {concept:name: "A", org:resource: "R1"}
+ -> "concept:name=A|org:resource=R1"
+
+ The output is a list of event identifiers and a list of dense embedding
+ vectors, one vector per event.
+
+ Parameters
+ -----------------
+ log
+ Pandas dataframe
+ Parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID_KEY => an attribute unique per event
+ - Parameters.EMBEDDING_MODEL => the embedding to be used (default: all-MiniLM-L6-v2)
+ - Parameters.ATTRIBUTE_KEY => the attribute to be used
+ - Parameters.EVENT_ATTRIBUTES => event attributes to include in the event sentence. If omitted, ATTRIBUTE_KEY is used.
+
+ Returns
+ ----------------
+ event_identifiers
+ The list of all the event identifiers
+ embeddings_list
+ The list of embeddings for the considered events
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id_key = exec_utils.get_param_value(Parameters.EVENT_ID_KEY, parameters, constants.DEFAULT_INDEX_KEY)
+ attribute_key = exec_utils.get_param_value(Parameters.ATTRIBUTE_KEY, parameters, xes_constants.DEFAULT_NAME_KEY)
+ embedding_model = exec_utils.get_param_value(Parameters.EMBEDDING_MODEL, parameters,
+ constants.DEFAULT_EMBEDDING_MODEL)
+ event_attributes = exec_utils.get_param_value(
+ Parameters.EVENT_ATTRIBUTES, parameters, None
+ )
+ if event_attributes is None:
+ event_attributes = [attribute_key]
+ elif isinstance(event_attributes, str):
+ event_attributes = [event_attributes]
+ else:
+ event_attributes = list(event_attributes)
+
+ log = log_converter.apply(log, variant=log_converter.Variants.TO_DATA_FRAME)
+
+ event_identifiers = []
+ sentences = []
+
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer(embedding_model)
+
+ log = log[[event_id_key] + event_attributes].to_dict(orient="records")
+
+ for entry in log:
+ event_identifiers.append(entry[event_id_key])
+ if event_attributes == [attribute_key]:
+ sentences.append(str(entry[attribute_key]))
+ else:
+ tokens = trace_text.format_event_tokens(
+ entry, event_attributes, parameters=parameters
+ )
+ sentences.append(trace_text.tokens_to_sentence(tokens))
+
+ embeddings_list = list(model.encode(sentences))
+
+ return event_identifiers, embeddings_list
+
+
+def keep_top_k_per_similarity(log: pd.DataFrame, target_sentence: str, k: int,
+ event_identifiers: Optional[List[str]] = None,
+ embeddings_list: Optional[List[List[float]]] = None,
+ parameters: Optional[Dict[Any, Any]] = None) -> pd.DataFrame:
+ """
+ Keeps the top K events by embedding similarity with the given sentence.
+
+ For example, after encoding events as activity/resource sentences, the
+ query "pay compensation" is embedded with the same model and compared with
+ each event embedding using cosine similarity.
+
+ Parameters
+ ----------------
+ log
+ Pandas dataframe
+ target_sentence
+ Target sentence
+ k
+ Number of similar events to retain
+ event_identifiers
+ (Optional) the list of event identifiers in the log, as returned by the 'apply' method
+ embeddings_list
+ (Optional) the list of embeddings for such events, as returned by the 'apply' method
+ parameters
+ Other parameters of the method:
+ - Parameters.KEEP_CASES => If True, keep the cases containing such events, instead of the events themselves (default: False)
+
+ Returns
+ -----------------
+ filtered_log
+ Event log filtered on the top K events (or cases) according to the similarity metric.
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id_key = exec_utils.get_param_value(Parameters.EVENT_ID_KEY, parameters, constants.DEFAULT_INDEX_KEY)
+ keep_cases = exec_utils.get_param_value(Parameters.KEEP_CASES, parameters, False)
+
+ if event_identifiers is None or embeddings_list is None:
+ event_identifiers, embeddings_list = apply(log, parameters=parameters)
+
+ sim = similarity.apply(target_sentence, embeddings_list)
+ events = [(event_identifiers[i], sim[i]) for i in range(len(event_identifiers))]
+ events.sort(key=lambda x: (x[1], x[0]), reverse=True)
+ events = events[:k]
+ events = [x[0] for x in events]
+
+ filt_log = log[log[event_id_key].isin(events)]
+
+ if keep_cases:
+ case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME)
+ filt_log2 = log[log[case_id_key].isin(filt_log[case_id_key])]
+ return filt_log2
+
+ return filt_log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/n_grams.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/n_grams.py
new file mode 100644
index 0000000000000000000000000000000000000000..73503d052414f7dd48f07d66cbf4fde72fc01eb1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/n_grams.py
@@ -0,0 +1,98 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Trace-level n-gram encoding.
+
+From an event-log point of view, each case is read as an ordered sequence of
+tokens. By default, the token of an event is its activity name. The output
+has one row per trace and one column per contiguous token pattern of length n.
+The cell is the number of times that pattern appears in the trace.
+
+Example with ngram_range=(2, 2):
+ case 1: A, B, A
+ case 2: A, C
+
+The 2-gram vocabulary is [A >> B, A >> C, B >> A], and the encoded matrix is:
+ case 1 -> [1, 0, 1]
+ case 2 -> [0, 1, 0]
+
+With ngram_range=(1, 2), the vocabulary includes both single activities and
+directly-follows pairs.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+The survey lists n-grams as a baseline encoding and points to maintained text
+tooling for implementation. This variant delegates vector construction to
+scikit-learn's CountVectorizer with a trace-token n-gram analyzer.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
+
+
+class Parameters(Enum):
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ NGRAM_RANGE = "ngram_range"
+ RETURN_SPARSE = "return_sparse"
+ VECTORIZER = "vectorizer"
+ FIT_VECTORIZER = "fit_vectorizer"
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace as frequency counts of contiguous token n-grams.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
+ the activity attribute.
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
+ - NGRAM_RANGE: tuple such as (2, 2) or (1, 3).
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
+
+ Returns
+ -------
+ data
+ One row per trace, one count per discovered n-gram.
+ feature_names
+ N-gram names corresponding to the columns of data.
+ """
+ return sklearn_vectorization.apply(
+ log, binary=False, ngram_range=(2, 2), parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/one_hot.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/one_hot.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd5eee5593dced697550e922faecb353c4962831
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/one_hot.py
@@ -0,0 +1,96 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Trace-level one-hot occurrence encoding.
+
+From an event-log point of view, each case is read as a sequence of tokens.
+By default, the token of an event is its activity name. The output has one
+row per trace and one column per token; the cell is 1.0 when the trace
+contains the token at least once and 0.0 otherwise.
+
+Example with the activity attribute:
+ case 1: A, B, A
+ case 2: A, C
+
+The vocabulary is [A, B, C], and the encoded matrix is:
+ case 1 -> [1, 1, 0]
+ case 2 -> [1, 0, 1]
+
+If event_attributes=["concept:name", "org:resource"], the event token can
+include both the activity and resource, e.g. "concept:name=A|org:resource=R1".
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+The survey lists one-hot as a baseline encoding and uses sklearn as the
+open-source implementation source. This variant uses scikit-learn's
+CountVectorizer with binary counts over trace tokens.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
+
+
+class Parameters(Enum):
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ RETURN_SPARSE = "return_sparse"
+ VECTORIZER = "vectorizer"
+ FIT_VECTORIZER = "fit_vectorizer"
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace as a binary vector of present trace tokens.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
+ the activity attribute.
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
+
+ Returns
+ -------
+ data
+ One row per trace, one binary value per discovered token.
+ feature_names
+ Token names corresponding to the columns of data.
+ """
+ return sklearn_vectorization.apply(
+ log, binary=True, ngram_range=(1, 1), parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dbf49db6ac96d446dee2122b7211164254123f2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal.py
@@ -0,0 +1,245 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog, EventStream
+import pandas as pd
+from typing import Union, Optional, Dict, Any
+from pm4py.objects.conversion.log import converter as log_converter
+from enum import Enum
+from pm4py.util import exec_utils, constants, xes_constants, pandas_utils
+
+
+class Parameters(Enum):
+ ARRIVAL_RATE = "arrival_rate"
+ FINISH_RATE = "finish_rate"
+ CASE_ID_COLUMN = constants.PARAMETER_CONSTANT_CASEID_KEY
+ START_TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
+ TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ RESOURCE_COLUMN = constants.PARAMETER_CONSTANT_RESOURCE_KEY
+ ACTIVITY_COLUMN = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ GROUPER_FREQ = "grouper_freq"
+ SERVICE_TIME = "service_time"
+ WAITING_TIME = "waiting_time"
+ SOJOURN_TIME = "sojourn_time"
+ DIFF_START_END = "diff_start_end"
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> pd.DataFrame:
+ """
+ Aggregates an event log into temporal windows and computes window-level
+ process features.
+
+ From an event-log point of view, events are grouped by a timestamp
+ frequency such as weekly ("W") or daily ("D"). Each output row describes
+ one time window, not one trace. The columns include counts and averages
+ such as unique resources, unique activities, number of events, average
+ arrival rate, average finish rate, waiting time, service time, rework
+ count, cases per resource, events per case, number of cases, and resources
+ per case.
+
+ Example with GROUPER_FREQ="D":
+ day 2024-01-01 has 2 cases and 5 events
+ day 2024-01-02 has 1 case and 2 events
+
+ The result has two rows, one for each day, with columns such as
+ number_of_cases=[2, 1] and num_events=[5, 2].
+
+ Implements the approach described in the paper:
+ Pourbafrani, Mahsa, Sebastiaan J. van Zelst, and Wil MP van der Aalst.
+ "Supporting automatic system dynamics model generation for simulation
+ in the context of process mining." International Conference on Business
+ Information Systems. Springer, Cham, 2020.
+
+ Parameters
+ ---------------
+ log
+ Event log / Event stream / Pandas dataframe
+ parameters
+ Parameters of the algorithm, including:
+
+ - Parameters.GROUPER_FREQ => the time interval to be used for the grouping (default: "W")
+ - Parameters.ARRIVAL_RATE => column of the dataframe which is going to host the arrival rate
+ - Parameters.FINISH_RATE => column of the dataframe which is going to host the finishing rate
+ - Parameters.SERVICE_TIME => column of the dataframe which is going to host the service time
+ - Parameters.WAITING_TIME => column of the dataframe which is going to host the waiting time
+ - Parameters.SOJOURN_TIME => column of the dataframe which is going to host the sojourn time
+ - Parameters.CASE_ID_COLUMN => case ID column in the dataframe (default: case:concept:name)
+ - Parameters.ACTIVITY_COLUMN => activity column in the dataframe (default: concept:name)
+ - Parameters.TIMESTAMP_COLUMN => timestamp column in the dataframe (default: time:timestamp)
+ - Parameters.RESOURCE_COLUMN => resource column in the dataframe (default: org:resource)
+ - Parameters.START_TIMESTAMP_COLUMN => start timestamp column in the dataframe (if not provided, the timestamp column is used)
+
+ Returns
+ ----------------
+ features_df
+ Dataframe with temporal features, aggregated per time window
+ """
+ if parameters is None:
+ parameters = {}
+
+ grouper_freq = exec_utils.get_param_value(
+ Parameters.GROUPER_FREQ, parameters, "W"
+ )
+ timestamp_column = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_COLUMN,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ start_timestamp_column = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_COLUMN, parameters, None
+ )
+ if start_timestamp_column is None:
+ start_timestamp_column = timestamp_column
+
+ case_id_column = exec_utils.get_param_value(
+ Parameters.CASE_ID_COLUMN, parameters, constants.CASE_CONCEPT_NAME
+ )
+ diff_start_end = exec_utils.get_param_value(
+ Parameters.DIFF_START_END, parameters, "@@diff_start_end"
+ )
+ arrival_rate = exec_utils.get_param_value(
+ Parameters.ARRIVAL_RATE, parameters, "@@arrival_rate"
+ )
+ finish_rate = exec_utils.get_param_value(
+ Parameters.FINISH_RATE, parameters, "@@finish_rate"
+ )
+ service_time = exec_utils.get_param_value(
+ Parameters.SERVICE_TIME, parameters, "@@service_time"
+ )
+ waiting_time = exec_utils.get_param_value(
+ Parameters.WAITING_TIME, parameters, "@@waiting_time"
+ )
+ sojourn_time = exec_utils.get_param_value(
+ Parameters.SOJOURN_TIME, parameters, "@@sojourn_time"
+ )
+ resource_column = exec_utils.get_param_value(
+ Parameters.RESOURCE_COLUMN,
+ parameters,
+ xes_constants.DEFAULT_RESOURCE_KEY,
+ )
+ activity_column = exec_utils.get_param_value(
+ Parameters.ACTIVITY_COLUMN, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+
+ # Convert input event log to a DataFrame if necessary
+ log_df = log_converter.apply(
+ log,
+ variant=log_converter.Variants.TO_DATA_FRAME,
+ parameters=parameters,
+ )
+
+ # Insert arrival and finish rate columns
+ log_df = pandas_utils.insert_case_arrival_finish_rate(
+ log_df,
+ case_id_column=case_id_column,
+ timestamp_column=timestamp_column,
+ arrival_rate_column=arrival_rate,
+ finish_rate_column=finish_rate,
+ )
+
+ # Insert service, waiting, sojourn times
+ log_df = pandas_utils.insert_case_service_waiting_time(
+ log_df,
+ case_id_column=case_id_column,
+ timestamp_column=timestamp_column,
+ diff_start_end_column=diff_start_end,
+ service_time_column=service_time,
+ sojourn_time_column=sojourn_time,
+ waiting_time_column=waiting_time,
+ )
+
+ # Group the log by time windows
+ grouped_log = log_df.groupby(
+ pandas_utils.get_grouper(key=start_timestamp_column, freq=grouper_freq)
+ )
+
+ final_values = []
+
+ for gkey, gval in grouped_log:
+ dct = {}
+ dct["timestamp"] = gkey
+
+ # Group by case to get one row per case (first arrival_rate, etc.)
+ gval_first = gval.groupby(case_id_column).first()
+
+ # Keep existing features (if desired)
+ dct["unique_resources"] = gval[resource_column].nunique()
+ dct["unique_activities"] = gval[activity_column].nunique()
+ dct["num_events"] = len(gval)
+
+ dct["average_arrival_rate"] = gval_first[arrival_rate].mean()
+ dct["average_finish_rate"] = gval_first[finish_rate].mean()
+ dct["average_waiting_time"] = gval_first[waiting_time].mean()
+ dct["average_sojourn_time"] = gval_first[sojourn_time].mean()
+ dct["average_service_time"] = gval_first[service_time].mean()
+
+ # -----------------------------------------------------------------
+ # NEW FEATURES
+ # -----------------------------------------------------------------
+ # (1) Total number of reworked activities
+ # For each case: (number_of_events) - (unique_activities)
+ # Then sum across all cases in the window.
+ if len(gval) > 0:
+ reworks_series = gval.groupby(case_id_column)[activity_column].apply(
+ lambda series: series.size - series.nunique()
+ )
+ dct["total_number_of_reworked_activities"] = reworks_series.sum()
+
+ # (2) Average number of cases per resource
+ # For each resource, count distinct cases, then average over resources
+ cases_per_resource = gval.groupby(resource_column)[case_id_column].nunique()
+ dct["avg_cases_per_resource"] = (
+ cases_per_resource.mean() if not pd.isna(cases_per_resource.mean()) else 0
+ )
+
+ # (3) Average number of events per case
+ # For each case, count events, then average
+ events_per_case = gval.groupby(case_id_column).size()
+ dct["avg_events_per_case"] = (
+ events_per_case.mean() if not pd.isna(events_per_case.mean()) else 0
+ )
+
+ # (4) Number of cases
+ dct["number_of_cases"] = gval[case_id_column].nunique()
+
+ # (5) Average number of resources per case
+ # For each case, count distinct resources, then average
+ resources_per_case = gval.groupby(case_id_column)[resource_column].nunique()
+ dct["avg_resources_per_case"] = (
+ resources_per_case.mean() if not pd.isna(resources_per_case.mean()) else 0
+ )
+ # -----------------------------------------------------------------
+ else:
+ dct["total_number_of_reworked_activities"] = 0
+ dct["avg_cases_per_resource"] = 0
+ dct["avg_events_per_case"] = 0
+ dct["avg_resources_per_case"] = 0
+
+ final_values.append(dct)
+
+ dataframe = pandas_utils.instantiate_dataframe(final_values)
+ # Fill any remaining NaNs with 0
+ dataframe = dataframe.fillna(0)
+
+ return dataframe
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal_lazy.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal_lazy.py
new file mode 100644
index 0000000000000000000000000000000000000000..687d353c190cc7434076e28388109aef9bcf8ff6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal_lazy.py
@@ -0,0 +1,325 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.util import exec_utils, constants, xes_constants, pandas_utils
+
+
+class Parameters(Enum):
+ ARRIVAL_RATE = "arrival_rate"
+ FINISH_RATE = "finish_rate"
+ CASE_ID_COLUMN = constants.PARAMETER_CONSTANT_CASEID_KEY
+ START_TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
+ TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ RESOURCE_COLUMN = constants.PARAMETER_CONSTANT_RESOURCE_KEY
+ ACTIVITY_COLUMN = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ GROUPER_FREQ = "grouper_freq"
+ SERVICE_TIME = "service_time"
+ WAITING_TIME = "waiting_time"
+ SOJOURN_TIME = "sojourn_time"
+ DIFF_START_END = "diff_start_end"
+
+
+_WINDOW_START_COL = "__window_start"
+
+
+def _freq_to_polars_duration(freq: str) -> str:
+ """
+ Convert a pandas-style frequency string to a Polars duration string.
+ """
+ if not freq:
+ raise ValueError("grouper frequency must be a non-empty string")
+
+ freq = freq.strip()
+ freq_upper = freq.upper()
+ # Remove timezone/day designators (e.g., W-MON -> W)
+ if "-" in freq_upper:
+ freq_upper = freq_upper.split("-", 1)[0]
+
+ numbers = "".join(ch for ch in freq_upper if ch.isdigit())
+ letters = "".join(ch for ch in freq_upper if ch.isalpha())
+
+ if not letters:
+ raise ValueError(f"cannot infer unit from grouper frequency '{freq}'")
+
+ if not numbers:
+ numbers = "1"
+
+ normalized_unit = letters
+ if normalized_unit in {"MIN"}:
+ normalized_unit = "MIN"
+ else:
+ # Drop suffixes such as S, E (month/quarter/year start/end)
+ normalized_unit = normalized_unit.rstrip("S").rstrip("E")
+ if not normalized_unit:
+ normalized_unit = letters
+
+ unit_mapping = {
+ "S": "s",
+ "SEC": "s",
+ "SECOND": "s",
+ "MIN": "m",
+ "T": "m",
+ "H": "h",
+ "D": "d",
+ "W": "w",
+ "M": "mo",
+ "Q": "q",
+ "Y": "y",
+ "A": "y",
+ }
+
+ if normalized_unit not in unit_mapping:
+ raise ValueError(
+ f"grouper frequency '{freq}' is not supported when using the temporal_lazy variant."
+ )
+
+ return f"{numbers}{unit_mapping[normalized_unit]}"
+
+
+def apply(
+ log,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Aggregates a Polars LazyFrame event log into temporal windows.
+
+ This is the lazy Polars equivalent of the temporal variant. From an
+ event-log point of view, events are grouped by timestamp windows and each
+ output row describes one window. The returned LazyFrame contains the same
+ feature semantics as the pandas temporal variant, such as unique
+ resources, unique activities, number of events, average waiting/service
+ times, rework counts, and cases/resources per window.
+
+ Example with GROUPER_FREQ="D":
+ day 2024-01-01 has 2 cases and 5 events
+ day 2024-01-02 has 1 case and 2 events
+
+ The result is a lazy query that, when collected, yields two rows with
+ window-level feature values.
+
+ Parameters
+ ----------------
+ log
+ Polars LazyFrame containing the event log
+ parameters
+ Parameters of the algorithm (same semantics as the pandas-based temporal variant)
+
+ Returns
+ ----------------
+ pl.DataFrame
+ Dataframe with temporal features, aggregated per time window
+ """
+ if parameters is None:
+ parameters = {}
+
+ import polars as pl
+
+ if not pandas_utils.is_polars_lazyframe(log):
+ raise TypeError(
+ "temporal_lazy.apply expects a Polars LazyFrame as input."
+ )
+
+ grouper_freq = exec_utils.get_param_value(
+ Parameters.GROUPER_FREQ, parameters, "W"
+ )
+ timestamp_column = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_COLUMN,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ start_timestamp_column = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_COLUMN, parameters, None
+ )
+ if start_timestamp_column is None:
+ start_timestamp_column = timestamp_column
+
+ case_id_column = exec_utils.get_param_value(
+ Parameters.CASE_ID_COLUMN, parameters, constants.CASE_CONCEPT_NAME
+ )
+ diff_start_end = exec_utils.get_param_value(
+ Parameters.DIFF_START_END, parameters, "@@diff_start_end"
+ )
+ arrival_rate = exec_utils.get_param_value(
+ Parameters.ARRIVAL_RATE, parameters, "@@arrival_rate"
+ )
+ finish_rate = exec_utils.get_param_value(
+ Parameters.FINISH_RATE, parameters, "@@finish_rate"
+ )
+ service_time = exec_utils.get_param_value(
+ Parameters.SERVICE_TIME, parameters, "@@service_time"
+ )
+ waiting_time = exec_utils.get_param_value(
+ Parameters.WAITING_TIME, parameters, "@@waiting_time"
+ )
+ sojourn_time = exec_utils.get_param_value(
+ Parameters.SOJOURN_TIME, parameters, "@@sojourn_time"
+ )
+ resource_column = exec_utils.get_param_value(
+ Parameters.RESOURCE_COLUMN,
+ parameters,
+ xes_constants.DEFAULT_RESOURCE_KEY,
+ )
+ activity_column = exec_utils.get_param_value(
+ Parameters.ACTIVITY_COLUMN, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+
+ lazy_log = pandas_utils.insert_case_arrival_finish_rate(
+ log,
+ case_id_column=case_id_column,
+ timestamp_column=timestamp_column,
+ start_timestamp_column=start_timestamp_column,
+ arrival_rate_column=arrival_rate,
+ finish_rate_column=finish_rate,
+ )
+
+ lazy_log = pandas_utils.insert_case_service_waiting_time(
+ lazy_log,
+ case_id_column=case_id_column,
+ timestamp_column=timestamp_column,
+ start_timestamp_column=start_timestamp_column,
+ diff_start_end_column=diff_start_end,
+ service_time_column=service_time,
+ sojourn_time_column=sojourn_time,
+ waiting_time_column=waiting_time,
+ )
+
+ duration = _freq_to_polars_duration(grouper_freq)
+
+ lazy_log = lazy_log.with_columns(
+ pl.col(start_timestamp_column)
+ .dt.truncate(duration)
+ .alias(_WINDOW_START_COL)
+ )
+
+ case_agg = (
+ lazy_log.group_by([_WINDOW_START_COL, case_id_column])
+ .agg(
+ pl.len().alias("__events_per_case"),
+ pl.col(activity_column)
+ .drop_nulls()
+ .n_unique()
+ .alias("__unique_acts_per_case"),
+ pl.col(resource_column)
+ .drop_nulls()
+ .n_unique()
+ .alias("__unique_res_per_case"),
+ pl.col(arrival_rate).first().alias("__arrival_rate"),
+ pl.col(finish_rate).first().alias("__finish_rate"),
+ pl.col(waiting_time).first().alias("__waiting_time"),
+ pl.col(sojourn_time).first().alias("__sojourn_time"),
+ pl.col(service_time).first().alias("__service_time"),
+ )
+ .with_columns(
+ (
+ pl.col("__events_per_case")
+ - pl.col("__unique_acts_per_case")
+ ).alias("__reworks_per_case")
+ )
+ )
+
+ case_window = case_agg.group_by(_WINDOW_START_COL).agg(
+ pl.col("__reworks_per_case")
+ .sum()
+ .alias("total_number_of_reworked_activities"),
+ pl.col("__events_per_case").mean().alias("avg_events_per_case"),
+ pl.col("__unique_res_per_case").mean().alias("avg_resources_per_case"),
+ pl.col(case_id_column).n_unique().alias("number_of_cases"),
+ pl.col("__arrival_rate").mean().alias("average_arrival_rate"),
+ pl.col("__finish_rate").mean().alias("average_finish_rate"),
+ pl.col("__waiting_time").mean().alias("average_waiting_time"),
+ pl.col("__sojourn_time").mean().alias("average_sojourn_time"),
+ pl.col("__service_time").mean().alias("average_service_time"),
+ )
+
+ resource_agg = (
+ lazy_log.filter(pl.col(resource_column).is_not_null())
+ .group_by([_WINDOW_START_COL, resource_column])
+ .agg(
+ pl.col(case_id_column)
+ .n_unique()
+ .alias("__cases_per_resource")
+ )
+ )
+
+ resource_window = resource_agg.group_by(_WINDOW_START_COL).agg(
+ pl.col("__cases_per_resource")
+ .mean()
+ .alias("avg_cases_per_resource")
+ )
+
+ basic_window = lazy_log.group_by(_WINDOW_START_COL).agg(
+ pl.col(resource_column)
+ .drop_nulls()
+ .n_unique()
+ .alias("unique_resources"),
+ pl.col(activity_column)
+ .drop_nulls()
+ .n_unique()
+ .alias("unique_activities"),
+ pl.len().alias("num_events"),
+ )
+
+ result_lazy = (
+ basic_window.join(case_window, on=_WINDOW_START_COL, how="left", maintain_order="left")
+ .join(resource_window, on=_WINDOW_START_COL, how="left", maintain_order="left")
+ .sort(_WINDOW_START_COL)
+ .rename({_WINDOW_START_COL: "timestamp"})
+ .with_columns(
+ [
+ pl.col("total_number_of_reworked_activities").fill_null(0),
+ pl.col("avg_events_per_case").fill_null(0),
+ pl.col("avg_resources_per_case").fill_null(0),
+ pl.col("average_arrival_rate").fill_null(0),
+ pl.col("average_finish_rate").fill_null(0),
+ pl.col("average_waiting_time").fill_null(0),
+ pl.col("average_sojourn_time").fill_null(0),
+ pl.col("average_service_time").fill_null(0),
+ pl.col("avg_cases_per_resource").fill_null(0),
+ pl.col("number_of_cases").fill_null(0),
+ pl.col("unique_resources").fill_null(0),
+ pl.col("unique_activities").fill_null(0),
+ pl.col("num_events").fill_null(0),
+ ]
+ )
+ .select(
+ [
+ "timestamp",
+ "unique_resources",
+ "unique_activities",
+ "num_events",
+ "average_arrival_rate",
+ "average_finish_rate",
+ "average_waiting_time",
+ "average_sojourn_time",
+ "average_service_time",
+ "total_number_of_reworked_activities",
+ "avg_cases_per_resource",
+ "avg_events_per_case",
+ "number_of_cases",
+ "avg_resources_per_case",
+ ]
+ )
+ )
+
+ return result_lazy
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/tf_idf.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/tf_idf.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b02fec3d07dfdbc89bfb2b896f1c38c18eec5bf
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/tf_idf.py
@@ -0,0 +1,94 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Trace-level TF-IDF encoding.
+
+From an event-log point of view, each case is read as a sequence of tokens.
+By default, the token of an event is its activity name. The output has one
+row per trace and one column per token or n-gram. The cell is the TF-IDF
+weight of that token in that trace: tokens that are frequent in one trace
+but rare across the log receive higher weights.
+
+Example with activity tokens:
+ case 1: A, B, A
+ case 2: A, C
+
+The vocabulary is [A, B, C]. A appears in both traces, so it receives a lower
+inverse-document-frequency weight than B or C, which are more trace-specific.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+This variant delegates vector construction to scikit-learn's maintained
+TfidfVectorizer using PM4Py trace tokens.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
+
+
+class Parameters(Enum):
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ NGRAM_RANGE = "ngram_range"
+ RETURN_SPARSE = "return_sparse"
+ VECTORIZER = "vectorizer"
+ FIT_VECTORIZER = "fit_vectorizer"
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace as TF-IDF weights over trace tokens or n-grams.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
+ the activity attribute.
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
+ - NGRAM_RANGE: tuple such as (1, 1) or (1, 2).
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
+
+ Returns
+ -------
+ data
+ One row per trace, one TF-IDF weight per discovered token/n-gram.
+ feature_names
+ Token or n-gram names corresponding to the columns of data.
+ """
+ return sklearn_vectorization.apply_tfidf(
+ log, ngram_range=(1, 1), parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/token_replay.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/token_replay.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbb7e3bc1b07ed5e56eb57ceaa355064a060bff0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/token_replay.py
@@ -0,0 +1,145 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Token-replay trace encoding.
+
+From an event-log point of view, each trace is replayed on a Petri net and
+the replay diagnostics become the trace vector. The vector contains:
+is-fit, fitness, missing tokens, consumed tokens, remaining tokens, and
+produced tokens.
+
+Example with a model A -> B -> C:
+ case 1: A, B, C
+ case 2: A, C
+
+case 1 can be replayed without adding or leaving tokens, so it receives a
+fit vector such as [1, 1.0, 0, consumed, 0, produced]. case 2 skips B, so
+token replay has to add or compensate for tokens and the missing-token
+count and fitness reflect that deviation.
+
+The Petri net can be passed with net, initial_marking, and final_marking. If
+no model is passed, the variant discovers one from the log using PM4Py's
+Inductive Miner.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+The survey lists token-replay as a PM-based encoding and points to PM4Py as
+the maintained implementation. This variant delegates replay computation to
+PM4Py's token replay and exposes per-trace replay diagnostics as vectors.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import petri_net
+
+
+class Parameters(Enum):
+ NET = "net"
+ PETRI_NET = "petri_net"
+ INITIAL_MARKING = "initial_marking"
+ FINAL_MARKING = "final_marking"
+ DISCOVER_MODEL = "discover_model"
+ TOKEN_REPLAY_VARIANT = "token_replay_variant"
+
+
+FEATURE_NAMES = [
+ "@@token_replay_is_fit",
+ "@@token_replay_fitness",
+ "@@token_replay_missing_tokens",
+ "@@token_replay_consumed_tokens",
+ "@@token_replay_remaining_tokens",
+ "@@token_replay_produced_tokens",
+]
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace with token-replay conformance diagnostics.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - NET/PETRI_NET, INITIAL_MARKING, FINAL_MARKING: existing Petri net
+ model to replay on.
+ - DISCOVER_MODEL: if True, discover a Petri net when no model is
+ supplied.
+ - TOKEN_REPLAY_VARIANT: PM4Py token replay variant.
+
+ Returns
+ -------
+ data
+ One row per trace with token-replay diagnostics.
+ feature_names
+ Diagnostic names corresponding to the columns of data.
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.algo.conformance.tokenreplay import algorithm as token_replay
+ from pm4py.util import exec_utils
+
+ event_log, net, initial_marking, final_marking = petri_net.get_log_and_model(
+ log, parameters=parameters
+ )
+ variant = exec_utils.get_param_value(
+ Parameters.TOKEN_REPLAY_VARIANT,
+ parameters,
+ token_replay.DEFAULT_VARIANT,
+ )
+
+ replayed_traces = token_replay.apply(
+ event_log,
+ net,
+ initial_marking,
+ final_marking,
+ parameters=parameters,
+ variant=variant,
+ )
+
+ data = []
+ for replayed_trace in replayed_traces:
+ data.append(
+ [
+ 1.0 if replayed_trace.get("trace_is_fit", False) else 0.0,
+ float(replayed_trace.get("trace_fitness", 0.0)),
+ float(replayed_trace.get("missing_tokens", 0.0)),
+ float(replayed_trace.get("consumed_tokens", 0.0)),
+ float(replayed_trace.get("remaining_tokens", 0.0)),
+ float(replayed_trace.get("produced_tokens", 0.0)),
+ ]
+ )
+
+ return data, FEATURE_NAMES
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/trace_based.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/trace_based.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f49332083b58b482a22fe520670fafa195a2450
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/trace_based.py
@@ -0,0 +1,1669 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any, Union, Tuple, List, Set
+
+from pm4py.objects.conversion.log import converter
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.objects.log.util import dataframe_utils
+from pm4py.util import constants, pandas_utils
+from pm4py.util import exec_utils
+from pm4py.util import xes_constants as xes
+from pm4py.util import xes_constants
+from pm4py.utils import is_polars_lazyframe
+
+
+class Parameters(Enum):
+ ENABLE_ACTIVITY_DEF_REPRESENTATION = "enable_activity_def_representation"
+ ENABLE_SUCC_DEF_REPRESENTATION = "enable_succ_def_representation"
+ STR_TRACE_ATTRIBUTES = "str_tr_attr"
+ STR_EVENT_ATTRIBUTES = "str_ev_attr"
+ NUM_TRACE_ATTRIBUTES = "num_tr_attr"
+ NUM_EVENT_ATTRIBUTES = "num_ev_attr"
+ STR_EVSUCC_ATTRIBUTES = "str_evsucc_attr"
+ FEATURE_NAMES = "feature_names"
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ RESOURCE_KEY = constants.PARAMETER_CONSTANT_RESOURCE_KEY
+ EPSILON = "epsilon"
+ DEFAULT_NOT_PRESENT = "default_not_present"
+ ENABLE_ALL_EXTRA_FEATURES = "enable_all_extra_features"
+ ENABLE_CASE_DURATION = "enable_case_duration"
+ ADD_CASE_IDENTIFIER_COLUMN = "add_case_identifier_column"
+ ENABLE_TIMES_FROM_FIRST_OCCURRENCE = "enable_times_from_first_occurrence"
+ ENABLE_TIMES_FROM_LAST_OCCURRENCE = "enable_times_from_last_occurrence"
+ ENABLE_DIRECT_PATHS_TIMES_LAST_OCC = "enable_direct_paths_times_last_occ"
+ ENABLE_INDIRECT_PATHS_TIMES_LAST_OCC = (
+ "enable_indirect_paths_times_last_occ"
+ )
+ ENABLE_WORK_IN_PROGRESS = "enable_work_in_progress"
+ ENABLE_RESOURCE_WORKLOAD = "enable_resource_workload"
+ ENABLE_FIRST_LAST_ACTIVITY_INDEX = "enable_first_last_activity_index"
+ ENABLE_MAX_CONCURRENT_EVENTS = "enable_max_concurrent_events"
+ ENABLE_MAX_CONCURRENT_EVENTS_PER_ACTIVITY = (
+ "enable_max_concurrent_events_per_activity"
+ )
+ ENABLE_NUMERIC_ATTRIBUTE_STATISTICS = "enable_numeric_attribute_statistics"
+ NUMERIC_ATTRIBUTE_AGGREGATIONS = "numeric_attribute_aggregations"
+ CASE_ATTRIBUTE_PREFIX = constants.CASE_ATTRIBUTE_PREFIX
+
+
+def max_concurrent_events(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Counts for every trace the maximum number of events (of any activity) that happen concurrently
+ (e.g., their time intervals [st1, ct1] and [st2, ct2] have non-empty intersection).
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+
+ data = []
+ feature_names = ["@@max_concurrent_activities_general"]
+
+ for trace in log:
+ max_conc = 0
+ i = 0
+ while i < len(trace) - 1:
+ conc = 0
+ ct = trace[i][timestamp_key].timestamp()
+ j = i + 1
+ while j < len(trace):
+ st = trace[j][start_timestamp_key].timestamp()
+ if st > ct:
+ break
+ conc = conc + 1
+ j = j + 1
+ if conc > max_conc:
+ max_conc = conc
+ i = i + 1
+ data.append([float(max_conc)])
+
+ return data, feature_names
+
+
+def max_concurrent_events_per_activity(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Counts for every trace and every activity the maximum number of events of the given activity that happen concurrently
+ (e.g., their time intervals [st1, ct1] and [st2, ct2] have non-empty intersection).
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+
+ activities = list(set(y[activity_key] for x in log for y in x))
+
+ data = []
+ feature_names = [
+ "@@max_concurrent_activities_like_" + x for x in activities
+ ]
+
+ for trace in log:
+ max_conc_act = {act: 0 for act in activities}
+ i = 0
+ while i < len(trace) - 1:
+ conc = 0
+ act = trace[i][activity_key]
+ ct = trace[i][timestamp_key].timestamp()
+ j = i + 1
+ while j < len(trace):
+ st = trace[j][start_timestamp_key].timestamp()
+ actj = trace[j][activity_key]
+ if st > ct:
+ break
+ if act == actj:
+ conc = conc + 1
+ j = j + 1
+ i = i + 1
+ max_conc_act[act] = max(max_conc_act[act], conc)
+ arr = []
+ for act in activities:
+ arr.append(float(max_conc_act[act]))
+ data.append(arr)
+
+ return data, feature_names
+
+
+def resource_workload(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Calculates for each case, and for each resource of the log, the workload of the resource during
+ the lead time of a case. Defaults if a resource is not contained in a case.
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.util.intervaltree import IntervalTree, Interval
+
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ resource_key = exec_utils.get_param_value(
+ Parameters.RESOURCE_KEY, parameters, xes_constants.DEFAULT_RESOURCE_KEY
+ )
+ epsilon = exec_utils.get_param_value(
+ Parameters.EPSILON, parameters, 0.000001
+ )
+ default_not_present = exec_utils.get_param_value(
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
+ )
+
+ tree_dict = {}
+ for case in log:
+ if case:
+ resources = set(x[resource_key] for x in case if resource_key in x)
+ st = case[0][start_timestamp_key].timestamp() - epsilon
+ ct = case[-1][timestamp_key].timestamp() + epsilon
+ for res in resources:
+ if res not in tree_dict:
+ tree_dict[res] = IntervalTree()
+ tree_dict[res].add(Interval(st, ct))
+
+ resources_list = sorted(list(tree_dict))
+
+ data = []
+ feature_names = ["resource_workload@@" + r for r in resources_list]
+
+ for case in log:
+ data.append([])
+ resources = set(x[resource_key] for x in case if resource_key in x)
+ st = case[0][start_timestamp_key].timestamp() - epsilon
+ ct = case[-1][timestamp_key].timestamp() + epsilon
+ for res in resources_list:
+ if res in resources:
+ data[-1].append(float(len(tree_dict[res][st:ct])))
+ else:
+ data[-1].append(float(default_not_present))
+
+ return data, feature_names
+
+
+def work_in_progress(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Calculates for each case, and for each resource of the log, the number of cases which are open during
+ the lead time of the case.
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.util.intervaltree import IntervalTree, Interval
+
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ epsilon = exec_utils.get_param_value(
+ Parameters.EPSILON, parameters, 0.000001
+ )
+ default_not_present = exec_utils.get_param_value(
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
+ )
+
+ tree = IntervalTree()
+ for case in log:
+ if case:
+ st = case[0][start_timestamp_key].timestamp() - epsilon
+ ct = case[-1][timestamp_key].timestamp() + epsilon
+ tree.add(Interval(st, ct))
+
+ data = []
+ feature_names = ["@@work_in_progress"]
+
+ for case in log:
+ if case:
+ st = case[0][start_timestamp_key].timestamp() - epsilon
+ ct = case[-1][timestamp_key].timestamp() + epsilon
+ data.append([float(len(tree[st:ct]))])
+ else:
+ data.append([float(default_not_present)])
+
+ return data, feature_names
+
+
+def indirect_paths_times_last_occ(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Calculates for each case, and for each indirect path of the case, the difference between the start timestamp
+ of the later event and the completion timestamp of the first event. Defaults if a path is not present in a case.
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ default_not_present = exec_utils.get_param_value(
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
+ )
+
+ all_paths = set()
+ for trace in log:
+ for i in range(len(trace) - 1):
+ for j in range(i + 2, len(trace)):
+ all_paths.add((trace[i][activity_key], trace[j][activity_key]))
+ all_paths = sorted(list(all_paths))
+
+ data = []
+ feature_names = []
+ for p in all_paths:
+ feature_names.append(
+ "indirectPathPerformanceLastOcc@@" + p[0] + "##" + p[1]
+ )
+
+ for trace in log:
+ data.append([])
+ trace_paths_perf = {}
+ for i in range(len(trace) - 1):
+ for j in range(i + 2, len(trace)):
+ p = (trace[i][activity_key], trace[j][activity_key])
+ tc = trace[i][timestamp_key].timestamp()
+ ts = trace[j][start_timestamp_key].timestamp()
+ if ts > tc:
+ trace_paths_perf[p] = ts - tc
+ for p in all_paths:
+ if p in trace_paths_perf:
+ data[-1].append(float(trace_paths_perf[p]))
+ else:
+ data[-1].append(float(default_not_present))
+
+ return data, feature_names
+
+
+def direct_paths_times_last_occ(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Calculates for each case, and for each direct path of the case, the difference between the start timestamp
+ of the later event and the completion timestamp of the first event. Defaults if a path is not present in a case.
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ default_not_present = exec_utils.get_param_value(
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
+ )
+
+ all_paths = set()
+ for trace in log:
+ for i in range(len(trace) - 1):
+ all_paths.add((trace[i][activity_key], trace[i + 1][activity_key]))
+ all_paths = sorted(list(all_paths))
+
+ data = []
+ feature_names = []
+ for p in all_paths:
+ feature_names.append(
+ "directPathPerformanceLastOcc@@" + p[0] + "##" + p[1]
+ )
+
+ for trace in log:
+ data.append([])
+ trace_paths_perf = {}
+ for i in range(len(trace) - 1):
+ p = (trace[i][activity_key], trace[i + 1][activity_key])
+ tc = trace[i][timestamp_key].timestamp()
+ ts = trace[i + 1][start_timestamp_key].timestamp()
+ if ts > tc:
+ trace_paths_perf[p] = ts - tc
+ for p in all_paths:
+ if p in trace_paths_perf:
+ data[-1].append(float(trace_paths_perf[p]))
+ else:
+ data[-1].append(float(default_not_present))
+
+ return data, feature_names
+
+
+def times_from_first_occurrence_activity_case(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Calculates for each case, and for each activity, the times from the start to the case, and to the end of the case,
+ from the first occurrence of the activity in the case.
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ default_not_present = exec_utils.get_param_value(
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
+ )
+
+ activities_log = set()
+ for trace in log:
+ for event in trace:
+ activities_log.add(event[activity_key])
+ activities_log = sorted(list(activities_log))
+
+ data = []
+ feature_names = []
+ for act in activities_log:
+ feature_names.append("startToFirstOcc@@" + act)
+ feature_names.append("firstOccToEnd@@" + act)
+
+ for trace in log:
+ data.append([])
+ activities_occ = {}
+ for i in range(len(trace)):
+ if trace[i][activity_key] not in activities_occ:
+ activities_occ[trace[i][activity_key]] = i
+ for act in activities_log:
+ if act in activities_occ:
+ ev = trace[activities_occ[act]]
+ this_ev_st = ev[start_timestamp_key].timestamp()
+ this_ev_ct = ev[timestamp_key].timestamp()
+ start_ev_ct = trace[0][timestamp_key].timestamp()
+ end_ev_st = trace[-1][start_timestamp_key].timestamp()
+ data[-1].append(float(this_ev_st - start_ev_ct))
+ data[-1].append(float(end_ev_st - this_ev_ct))
+ else:
+ data[-1].append(float(default_not_present))
+ data[-1].append(float(default_not_present))
+
+ return data, feature_names
+
+
+def times_from_last_occurrence_activity_case(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Calculates for each case, and for each activity, the times from the start to the case, and to the end of the case,
+ from the last occurrence of the activity in the case.
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ default_not_present = exec_utils.get_param_value(
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
+ )
+
+ activities_log = set()
+ for trace in log:
+ for event in trace:
+ activities_log.add(event[activity_key])
+ activities_log = sorted(list(activities_log))
+
+ data = []
+ feature_names = []
+ for act in activities_log:
+ feature_names.append("startToLastOcc@@" + act)
+ feature_names.append("lastOccToEnd@@" + act)
+
+ for trace in log:
+ data.append([])
+ activities_occ = {}
+ for i in range(len(trace)):
+ activities_occ[trace[i][activity_key]] = i
+ for act in activities_log:
+ if act in activities_occ:
+ ev = trace[activities_occ[act]]
+ this_ev_st = ev[start_timestamp_key].timestamp()
+ this_ev_ct = ev[timestamp_key].timestamp()
+ start_ev_ct = trace[0][timestamp_key].timestamp()
+ end_ev_st = trace[-1][start_timestamp_key].timestamp()
+ data[-1].append(float(this_ev_st - start_ev_ct))
+ data[-1].append(float(end_ev_st - this_ev_ct))
+ else:
+ data[-1].append(float(default_not_present))
+ data[-1].append(float(default_not_present))
+
+ return data, feature_names
+
+
+def first_last_activity_index_trace(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Consider as features the first and the last index of an activity inside a case
+
+ Parameters
+ ------------------
+ log
+ Event log
+ parameters
+ Parameters, including:
+ - Parameters.ACTIVITY_KEY => the attribute to use as activity
+ - Parameters.DEFAULT_NOT_PRESENT => the replacement value for activities that are not present for the specific case
+
+ Returns
+ -----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ default_not_present = exec_utils.get_param_value(
+ Parameters.DEFAULT_NOT_PRESENT, parameters, -1
+ )
+
+ activities_log = set()
+ for trace in log:
+ for event in trace:
+ activities_log.add(event[activity_key])
+ activities_log = sorted(list(activities_log))
+
+ data = []
+ feature_names = []
+ for act in activities_log:
+ feature_names.append("firstIndexAct@@" + act)
+ feature_names.append("lastIndexAct@@" + act)
+ for trace in log:
+ data.append([])
+
+ first_occ = {}
+ last_occ = {}
+ for index, event in enumerate(trace):
+ act = event[activity_key]
+ last_occ[act] = index
+ if act not in first_occ:
+ first_occ[act] = index
+ for act in activities_log:
+ if act not in first_occ:
+ data[-1].append(float(default_not_present))
+ data[-1].append(float(default_not_present))
+ else:
+ data[-1].append(float(first_occ[act]))
+ data[-1].append(float(last_occ[act]))
+
+ return data, feature_names
+
+
+def case_duration(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Calculates for each case, the case duration (and adds it as a feature)
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ data
+ Numeric value of the features
+ feature_names
+ Names of the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+
+ feature_names = ["@@caseDuration"]
+ data = []
+ for trace in log:
+ if trace:
+ data.append(
+ [
+ float(
+ trace[-1][timestamp_key].timestamp()
+ - trace[0][start_timestamp_key].timestamp()
+ )
+ ]
+ )
+ else:
+ data.append([0.0])
+
+ return data, feature_names
+
+
+def get_string_trace_attribute_rep(trace: Trace, trace_attribute: str) -> str:
+ """
+ Get a representation of the feature name associated to a string trace attribute value
+
+ Parameters
+ ------------
+ trace
+ Trace of the log
+ trace_attribute
+ Attribute of the trace to consider
+
+ Returns
+ ------------
+ rep
+ Representation of the feature name associated to a string trace attribute value
+ """
+ if trace_attribute in trace.attributes:
+ return (
+ "trace:"
+ + str(trace_attribute)
+ + "@"
+ + str(trace.attributes[trace_attribute])
+ )
+ return "trace:" + str(trace_attribute) + "@UNDEFINED"
+
+
+def get_all_string_trace_attribute_values(
+ log: EventLog, trace_attribute: str
+) -> List[str]:
+ """
+ Get all string trace attribute values representations for a log
+
+ Parameters
+ ------------
+ log
+ Trace log
+ trace_attribute
+ Attribute of the trace to consider
+
+ Returns
+ ------------
+ list
+ List containing for each trace a representation of the feature name associated to the attribute
+ """
+ values = set()
+ for trace in log:
+ values.add(get_string_trace_attribute_rep(trace, trace_attribute))
+ return list(sorted(values))
+
+
+def get_string_event_attribute_rep(event: Event, event_attribute: str) -> str:
+ """
+ Get a representation of the feature name associated to a string event attribute value
+
+ Parameters
+ ------------
+ event
+ Single event of a trace
+ event_attribute
+ Event attribute to consider
+
+ Returns
+ ------------
+ rep
+ Representation of the feature name associated to a string event attribute value
+ """
+ return "event:" + str(event_attribute) + "@" + str(event[event_attribute])
+
+
+def get_values_event_attribute_for_trace(
+ trace: Trace, event_attribute: str
+) -> Set[str]:
+ """
+ Get all the representations for the events of a trace associated to a string event attribute values
+
+ Parameters
+ -------------
+ trace
+ Trace of the log
+ event_attribute
+ Event attribute to consider
+
+ Returns
+ -------------
+ values
+ All feature names present for the given attribute in the given trace
+ """
+ values_trace = set()
+ for event in trace:
+ if event_attribute in event:
+ values_trace.add(
+ get_string_event_attribute_rep(event, event_attribute)
+ )
+ if not values_trace:
+ values_trace.add("event:" + str(event_attribute) + "@UNDEFINED")
+ return values_trace
+
+
+def get_all_string_event_attribute_values(
+ log: EventLog, event_attribute: str
+) -> List[str]:
+ """
+ Get all the representations for all the traces of the log associated to a string event attribute values
+
+ Parameters
+ ------------
+ log
+ Trace of the log
+ event_attribute
+ Event attribute to consider
+
+ Returns
+ ------------
+ values
+ All feature names present for the given attribute in the given log
+ """
+ values = set()
+ for trace in log:
+ values = values.union(
+ get_values_event_attribute_for_trace(trace, event_attribute)
+ )
+ return list(sorted(values))
+
+
+def get_string_event_attribute_succession_rep(
+ event1: Event, event2: Event, event_attribute: str
+) -> str:
+ """
+ Get a representation of the feature name associated to a string event attribute value
+
+ Parameters
+ ------------
+ event1
+ First event of the succession
+ event2
+ Second event of the succession
+ event_attribute
+ Event attribute to consider
+
+ Returns
+ ------------
+ rep
+ Representation of the feature name associated to a string event attribute value
+ """
+ return (
+ "succession:"
+ + str(event_attribute)
+ + "@"
+ + str(event1[event_attribute])
+ + "#"
+ + str(event2[event_attribute])
+ )
+
+
+def get_values_event_attribute_succession_for_trace(
+ trace: Trace, event_attribute: str
+) -> Set[str]:
+ """
+ Get all the representations for the events of a trace associated to a string event attribute succession values
+
+ Parameters
+ -------------
+ trace
+ Trace of the log
+ event_attribute
+ Event attribute to consider
+
+ Returns
+ -------------
+ values
+ All feature names present for the given attribute succession in the given trace
+ """
+ values_trace = set()
+ for i in range(len(trace) - 1):
+ event1 = trace[i]
+ event2 = trace[i + 1]
+ if event_attribute in event1 and event_attribute in event2:
+ values_trace.add(
+ get_string_event_attribute_succession_rep(
+ event1, event2, event_attribute
+ )
+ )
+ if not values_trace:
+ values_trace.add("succession:" + str(event_attribute) + "@UNDEFINED")
+ return values_trace
+
+
+def get_all_string_event_succession_attribute_values(
+ log: EventLog, event_attribute: str
+) -> List[str]:
+ """
+ Get all the representations for all the traces of the log associated to a string event attribute succession values
+
+ Parameters
+ ------------
+ log
+ Trace of the log
+ event_attribute
+ Event attribute to consider
+
+ Returns
+ ------------
+ values
+ All feature names present for the given attribute succession in the given log
+ """
+ values = set()
+ for trace in log:
+ values = values.union(
+ get_values_event_attribute_succession_for_trace(
+ trace, event_attribute
+ )
+ )
+ return list(sorted(values))
+
+
+def get_numeric_trace_attribute_rep(trace_attribute: str) -> str:
+ """
+ Get the feature name associated to a numeric trace attribute
+
+ Parameters
+ ------------
+ trace_attribute
+ Name of the trace attribute
+
+ Returns
+ ------------
+ feature_name
+ Name of the feature
+ """
+ return "trace:" + trace_attribute
+
+
+def get_numeric_trace_attribute_value(
+ trace: Trace, trace_attribute: str
+) -> Union[int, float]:
+ """
+ Get the value of a numeric trace attribute from a given trace
+
+ Parameters
+ ------------
+ trace
+ Trace of the log
+
+ Returns
+ ------------
+ value
+ Value of the numeric trace attribute for the given trace
+ """
+ if trace_attribute in trace.attributes:
+ return float(trace.attributes[trace_attribute])
+ raise Exception(
+ "at least a trace without trace attribute: " + trace_attribute
+ )
+
+
+def get_numeric_event_attribute_rep(event_attribute: str) -> str:
+ """
+ Get the feature name associated to a numeric event attribute
+
+ Parameters
+ ------------
+ event_attribute
+ Name of the event attribute
+
+ Returns
+ -------------
+ feature_name
+ Name of the feature
+ """
+ return "event:" + event_attribute
+
+
+def get_numeric_event_attribute_value(
+ event: Event, event_attribute: str
+) -> Union[int, float]:
+ """
+ Get the value of a numeric event attribute from a given event
+
+ Parameters
+ -------------
+ event
+ Event
+
+ Returns
+ -------------
+ value
+ Value of the numeric event attribute for the given event
+ """
+ if event_attribute in event:
+ return float(event[event_attribute])
+ return None
+
+
+def get_numeric_event_attribute_value_trace(
+ trace: Trace, event_attribute: str
+) -> Union[int, float]:
+ """
+ Get the value of the last occurrence of a numeric event attribute given a trace
+
+ Parameters
+ -------------
+ trace
+ Trace of the log
+
+ Returns
+ -------------
+ value
+ Value of the last occurrence of a numeric trace attribute for the given trace
+ """
+ non_zero_values = []
+ for event in trace:
+ value = get_numeric_event_attribute_value(event, event_attribute)
+ if value is not None:
+ non_zero_values.append(value)
+ if len(non_zero_values) > 0:
+ return non_zero_values[-1]
+ raise Exception(
+ "at least a trace without any event with event attribute: "
+ + event_attribute
+ )
+
+
+def get_default_representation_with_attribute_names(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+ feature_names: Optional[List[str]] = None,
+) -> Tuple[Any, List[str], List[str], List[str], List[str], List[str]]:
+ """
+ Gets the default data representation of an event log (for process tree building)
+ returning also the attribute names
+
+ Parameters
+ -------------
+ log
+ Trace log
+ parameters
+ Possible parameters of the algorithm
+ feature_names
+ (If provided) Feature to use in the representation of the log
+
+ Returns
+ -------------
+ data
+ Data to provide for decision tree learning
+ feature_names
+ Names of the features, in order
+ """
+ from pm4py.statistics.attributes.log.select import (
+ select_attributes_from_log_for_tree,
+ )
+
+ if parameters is None:
+ parameters = {}
+
+ enable_activity_def_representation = exec_utils.get_param_value(
+ Parameters.ENABLE_ACTIVITY_DEF_REPRESENTATION, parameters, False
+ )
+ enable_succ_def_representation = exec_utils.get_param_value(
+ Parameters.ENABLE_SUCC_DEF_REPRESENTATION, parameters, False
+ )
+
+ activity_key = (
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+ blacklist = parameters["blacklist"] if "blacklist" in parameters else []
+
+ str_tr_attr, str_ev_attr, num_tr_attr, num_ev_attr = (
+ select_attributes_from_log_for_tree(log)
+ )
+ str_evsucc_attr = None
+
+ if enable_succ_def_representation:
+ str_evsucc_attr = [activity_key]
+ if enable_activity_def_representation and activity_key not in str_ev_attr:
+ str_ev_attr.append(activity_key)
+
+ str_tr_attr = [x for x in str_tr_attr if x not in blacklist]
+ str_ev_attr = [x for x in str_ev_attr if x not in blacklist]
+ num_tr_attr = [x for x in num_tr_attr if x not in blacklist]
+ num_ev_attr = [x for x in num_ev_attr if x not in blacklist]
+ if str_evsucc_attr is not None:
+ str_evsucc_attr = [x for x in str_evsucc_attr if x not in blacklist]
+
+ data, feature_names = get_representation(
+ log,
+ str_tr_attr,
+ str_ev_attr,
+ num_tr_attr,
+ num_ev_attr,
+ str_evsucc_attr=str_evsucc_attr,
+ feature_names=feature_names,
+ )
+
+ return (
+ data,
+ feature_names,
+ str_tr_attr,
+ str_ev_attr,
+ num_tr_attr,
+ num_ev_attr,
+ )
+
+
+def get_default_representation(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+ feature_names: Optional[List[str]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Gets the default data representation of an event log (for process tree building)
+
+ Parameters
+ -------------
+ log
+ Trace log
+ parameters
+ Possible parameters of the algorithm
+ feature_names
+ (If provided) Feature to use in the representation of the log
+
+ Returns
+ -------------
+ data
+ Data to provide for decision tree learning
+ feature_names
+ Names of the features, in order
+ """
+ from pm4py.statistics.attributes.log.select import (
+ select_attributes_from_log_for_tree,
+ )
+
+ if parameters is None:
+ parameters = {}
+
+ enable_activity_def_representation = exec_utils.get_param_value(
+ Parameters.ENABLE_ACTIVITY_DEF_REPRESENTATION, parameters, True
+ )
+ enable_succ_def_representation = exec_utils.get_param_value(
+ Parameters.ENABLE_SUCC_DEF_REPRESENTATION, parameters, True
+ )
+
+ activity_key = (
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+ blacklist = parameters["blacklist"] if "blacklist" in parameters else []
+
+ str_tr_attr, str_ev_attr, num_tr_attr, num_ev_attr = (
+ select_attributes_from_log_for_tree(log)
+ )
+ str_evsucc_attr = None
+
+ if enable_succ_def_representation:
+ str_evsucc_attr = [activity_key]
+ if enable_activity_def_representation and activity_key not in str_ev_attr:
+ str_ev_attr.append(activity_key)
+
+ str_tr_attr = [x for x in str_tr_attr if x not in blacklist]
+ str_ev_attr = [x for x in str_ev_attr if x not in blacklist]
+ num_tr_attr = [x for x in num_tr_attr if x not in blacklist]
+ num_ev_attr = [x for x in num_ev_attr if x not in blacklist]
+ if str_evsucc_attr is not None:
+ str_evsucc_attr = [x for x in str_evsucc_attr if x not in blacklist]
+
+ return get_representation(
+ log,
+ str_tr_attr,
+ str_ev_attr,
+ num_tr_attr,
+ num_ev_attr,
+ str_evsucc_attr=str_evsucc_attr,
+ feature_names=feature_names,
+ )
+
+
+def get_representation(
+ log: EventLog,
+ str_tr_attr: List[str],
+ str_ev_attr: List[str],
+ num_tr_attr: List[str],
+ num_ev_attr: List[str],
+ str_evsucc_attr: Optional[List[str]] = None,
+ feature_names: Optional[List[str]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Get a representation of the event log that is suited for the data part of the decision tree learning
+
+ NOTE: this function only encodes the last value seen for each attribute
+
+ Parameters
+ -------------
+ log
+ Trace log
+ str_tr_attr
+ List of string trace attributes to consider in data vector creation
+ str_ev_attr
+ List of string event attributes to consider in data vector creation
+ num_tr_attr
+ List of numeric trace attributes to consider in data vector creation
+ num_ev_attr
+ List of numeric event attributes to consider in data vector creation
+ str_evsucc_attr
+ List of attributes succession of values to consider in data vector creation
+ feature_names
+ (If provided) Feature to use in the representation of the log
+
+ Returns
+ -------------
+ data
+ Data to provide for decision tree learning
+ feature_names
+ Names of the features, in order
+ """
+ data = []
+ dictionary = {}
+ count = 0
+ if feature_names is None:
+ feature_names = []
+ for trace_attribute in str_tr_attr:
+ values = get_all_string_trace_attribute_values(
+ log, trace_attribute
+ )
+ for value in values:
+ dictionary[value] = count
+ feature_names.append(value)
+ count = count + 1
+ for event_attribute in str_ev_attr:
+ values = get_all_string_event_attribute_values(
+ log, event_attribute
+ )
+ for value in values:
+ dictionary[value] = count
+ feature_names.append(value)
+ count = count + 1
+ for trace_attribute in num_tr_attr:
+ dictionary[get_numeric_trace_attribute_rep(trace_attribute)] = (
+ count
+ )
+ feature_names.append(
+ get_numeric_trace_attribute_rep(trace_attribute)
+ )
+ count = count + 1
+ for event_attribute in num_ev_attr:
+ dictionary[get_numeric_event_attribute_rep(event_attribute)] = (
+ count
+ )
+ feature_names.append(
+ get_numeric_event_attribute_rep(event_attribute)
+ )
+ count = count + 1
+ if str_evsucc_attr:
+ for event_attribute in str_evsucc_attr:
+ values = get_all_string_event_succession_attribute_values(
+ log, event_attribute
+ )
+ for value in values:
+ dictionary[value] = count
+ feature_names.append(value)
+ count = count + 1
+ else:
+ count = len(feature_names)
+ for index, value in enumerate(feature_names):
+ dictionary[value] = index
+
+ for trace in log:
+ trace_rep = [0.0] * count
+ for trace_attribute in str_tr_attr:
+ trace_attr_rep = get_string_trace_attribute_rep(
+ trace, trace_attribute
+ )
+ if trace_attr_rep in dictionary:
+ trace_rep[dictionary[trace_attr_rep]] = 1.0
+ for event_attribute in str_ev_attr:
+ values = get_values_event_attribute_for_trace(
+ trace, event_attribute
+ )
+ for value in values:
+ if value in dictionary:
+ trace_rep[dictionary[value]] = 1.0
+ for trace_attribute in num_tr_attr:
+ this_value = get_numeric_trace_attribute_rep(trace_attribute)
+ if this_value in dictionary:
+ trace_rep[dictionary[this_value]] = (
+ get_numeric_trace_attribute_value(trace, trace_attribute)
+ )
+ for event_attribute in num_ev_attr:
+ this_value = get_numeric_event_attribute_rep(event_attribute)
+ if this_value in dictionary:
+ trace_rep[dictionary[this_value]] = (
+ get_numeric_event_attribute_value_trace(
+ trace, event_attribute
+ )
+ )
+ if str_evsucc_attr:
+ for event_attribute in str_evsucc_attr:
+ values = get_values_event_attribute_succession_for_trace(
+ trace, event_attribute
+ )
+ for value in values:
+ if value in dictionary:
+ trace_rep[dictionary[value]] = 1.0
+ data.append(trace_rep)
+ # data = np.asarray(data)
+ return data, feature_names
+
+
+def apply(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> Tuple[Any, List[str]]:
+ """
+ Encodes each trace as one feature vector.
+
+ From an event-log point of view, each case is summarized into a single row.
+ String trace attributes and selected string event attributes become one-hot
+ columns; selected numeric trace attributes and the last seen selected
+ numeric event attributes become numeric columns. Optional extra features
+ can add durations, activity positions, path times, concurrency, and
+ workload measures.
+
+ Example with event attribute "concept:name":
+ case 1: A, B, A
+ case 2: A, C
+
+ The activity columns are [event:concept:name@A, event:concept:name@B,
+ event:concept:name@C]. The encoded rows are:
+ case 1 -> [1, 1, 0]
+ case 2 -> [1, 0, 1]
+
+ This differs from count2vec because this legacy trace-based representation
+ stores whether a selected string attribute value appears in the trace,
+ not how many times it appears.
+
+ Parameters
+ -----------------
+ log
+ Log
+ parameters
+ Parameters of the algorithm, including:
+ - STR_TRACE_ATTRIBUTES => string trace attributes to consider in the features extraction
+ - STR_EVENT_ATTRIBUTES => string event attributes to consider in the features extraction
+ - NUM_TRACE_ATTRIBUTES => numeric trace attributes to consider in the features extraction
+ - NUM_EVENT_ATTRIBUTES => numeric event attributes to consider in the features extraction
+ - STR_EVSUCC_ATTRIBUTES => succession of event attributes to consider in the features extraction
+ - FEATURE_NAMES => features to consider (in the given order)
+ - ENABLE_ALL_EXTRA_FEATURES => enables all the extra features
+ - ENABLE_CASE_DURATION => enables the case duration as additional feature
+ - ENABLE_TIMES_FROM_FIRST_OCCURRENCE => enables the addition of the times from start of the case, to the end
+ of the case, from the first occurrence of an activity of a case
+ - ADD_CASE_IDENTIFIER_COLUMN => adds the case identifier (string) as column of the feature table (default: False)
+ - ENABLE_NUMERIC_ATTRIBUTE_STATISTICS => for dataframe inputs, expands numeric attributes to aggregation columns
+ - NUMERIC_ATTRIBUTE_AGGREGATIONS => collection of numeric aggregations to compute for attributes whose names
+ do not start with @@: last, first, min, max, mean, median, stdev, and sum
+ - ENABLE_TIMES_FROM_LAST_OCCURRENCE => enables the addition of the times from start of the case, to the end
+ of the case, from the last occurrence of an activity of a case
+ - ENABLE_DIRECT_PATHS_TIMES_LAST_OCC => add the duration of the last occurrence of a directed (i, i+1) path
+ in the case as feature
+ - ENABLE_INDIRECT_PATHS_TIMES_LAST_OCC => add the duration of the last occurrence of an indirect (i, j) path
+ in the case as feature
+ - ENABLE_WORK_IN_PROGRESS => enables the work in progress (number of concurrent cases) as a feature
+ - ENABLE_RESOURCE_WORKLOAD => enables the resource workload as a feature
+ - ENABLE_FIRST_LAST_ACTIVITY_INDEX => enables the insertion of the indexes of the activities as features
+ - ENABLE_MAX_CONCURRENT_EVENTS => enables the count of the number of concurrent events inside a case
+ - ENABLE_MAX_CONCURRENT_EVENTS_PER_ACTIVITY => enables the count of the number of concurrent events per activity
+
+ Returns
+ -------------
+ data
+ Data to provide for decision tree learning
+ feature_names
+ Names of the features, in order
+ """
+ if parameters is None:
+ parameters = {}
+
+ str_tr_attr = exec_utils.get_param_value(
+ Parameters.STR_TRACE_ATTRIBUTES, parameters, None
+ )
+ num_tr_attr = exec_utils.get_param_value(
+ Parameters.NUM_TRACE_ATTRIBUTES, parameters, None
+ )
+ str_ev_attr = exec_utils.get_param_value(
+ Parameters.STR_EVENT_ATTRIBUTES, parameters, None
+ )
+ num_ev_attr = exec_utils.get_param_value(
+ Parameters.NUM_EVENT_ATTRIBUTES, parameters, None
+ )
+ str_evsucc_attr = exec_utils.get_param_value(
+ Parameters.STR_EVSUCC_ATTRIBUTES, parameters, None
+ )
+ feature_names = exec_utils.get_param_value(
+ Parameters.FEATURE_NAMES, parameters, None
+ )
+
+ at_least_one_provided = (
+ (str_tr_attr is not None)
+ or (num_tr_attr is not None)
+ or (str_ev_attr is not None)
+ or (num_ev_attr is not None)
+ )
+
+ if str_tr_attr is None:
+ str_tr_attr = []
+
+ if num_tr_attr is None:
+ num_tr_attr = []
+
+ if str_ev_attr is None:
+ str_ev_attr = []
+
+ if num_ev_attr is None:
+ num_ev_attr = []
+
+ if pandas_utils.check_is_pandas_dataframe(log):
+ case_attribute_prefix = exec_utils.get_param_value(
+ Parameters.CASE_ATTRIBUTE_PREFIX, parameters, "case:"
+ )
+
+ if str_tr_attr or num_tr_attr or str_ev_attr or num_ev_attr:
+ columns = list(
+ set([case_attribute_prefix + x for x in str_tr_attr])
+ .union(set([case_attribute_prefix + x for x in num_tr_attr]))
+ .union(set(str_ev_attr))
+ .union(set(num_ev_attr))
+ )
+ if is_polars_lazyframe(log):
+ from pm4py.objects.log.util import pl_lazy_fea_utils
+ fea_df = pl_lazy_fea_utils.get_features_df(log, columns, parameters=parameters)
+ else:
+ fea_df = dataframe_utils.get_features_df(
+ log, columns, parameters=parameters
+ )
+ if is_polars_lazyframe(fea_df):
+ feature_names = list(fea_df.collect_schema().names())
+ else:
+ feature_names = list(fea_df.columns)
+ else:
+ if is_polars_lazyframe(log):
+ from pm4py.objects.log.util import pl_lazy_fea_utils
+ fea_df = pl_lazy_fea_utils.automatic_feature_extraction_df(log, parameters=parameters)
+ else:
+ fea_df = dataframe_utils.automatic_feature_extraction_df(
+ log, parameters=parameters
+ )
+ if is_polars_lazyframe(fea_df):
+ feature_names = list(fea_df.collect_schema().names())
+ else:
+ feature_names = list(fea_df.columns)
+ return fea_df, feature_names
+ else:
+ enable_all = exec_utils.get_param_value(
+ Parameters.ENABLE_ALL_EXTRA_FEATURES, parameters, False
+ )
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY,
+ parameters,
+ xes_constants.DEFAULT_TRACEID_KEY,
+ )
+ add_case_identifier_column = exec_utils.get_param_value(
+ Parameters.ADD_CASE_IDENTIFIER_COLUMN, parameters, False
+ )
+ enable_case_duration = exec_utils.get_param_value(
+ Parameters.ENABLE_CASE_DURATION, parameters, enable_all
+ )
+ enable_times_from_first_occ = exec_utils.get_param_value(
+ Parameters.ENABLE_TIMES_FROM_FIRST_OCCURRENCE,
+ parameters,
+ enable_all,
+ )
+ enable_times_from_last_occ = exec_utils.get_param_value(
+ Parameters.ENABLE_TIMES_FROM_LAST_OCCURRENCE,
+ parameters,
+ enable_all,
+ )
+ enable_direct_paths_times_last_occ = exec_utils.get_param_value(
+ Parameters.ENABLE_DIRECT_PATHS_TIMES_LAST_OCC,
+ parameters,
+ enable_all,
+ )
+ enable_indirect_paths_times_last_occ = exec_utils.get_param_value(
+ Parameters.ENABLE_INDIRECT_PATHS_TIMES_LAST_OCC,
+ parameters,
+ enable_all,
+ )
+ enable_work_in_progress = exec_utils.get_param_value(
+ Parameters.ENABLE_WORK_IN_PROGRESS, parameters, enable_all
+ )
+ enable_resource_workload = exec_utils.get_param_value(
+ Parameters.ENABLE_RESOURCE_WORKLOAD, parameters, enable_all
+ )
+ enable_first_last_activity_index = exec_utils.get_param_value(
+ Parameters.ENABLE_FIRST_LAST_ACTIVITY_INDEX, parameters, enable_all
+ )
+ enable_max_concurrent_events = exec_utils.get_param_value(
+ Parameters.ENABLE_MAX_CONCURRENT_EVENTS, parameters, enable_all
+ )
+ enable_max_concurrent_events_per_activity = exec_utils.get_param_value(
+ Parameters.ENABLE_MAX_CONCURRENT_EVENTS_PER_ACTIVITY,
+ parameters,
+ enable_all,
+ )
+
+ log = converter.apply(
+ log, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+ if at_least_one_provided:
+ datas, features_namess = get_representation(
+ log,
+ str_tr_attr,
+ str_ev_attr,
+ num_tr_attr,
+ num_ev_attr,
+ str_evsucc_attr=str_evsucc_attr,
+ feature_names=feature_names,
+ )
+ else:
+ datas, features_namess = get_default_representation(
+ log, parameters=parameters
+ )
+
+ if add_case_identifier_column:
+ for i in range(len(datas)):
+ datas[i] = [log[i].attributes[case_id_key]] + datas[i]
+ features_namess = ["@@case_id_column"] + features_namess
+
+ # add additional features
+
+ if enable_case_duration:
+ data, features_names = case_duration(log, parameters=parameters)
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_times_from_first_occ:
+ data, features_names = times_from_first_occurrence_activity_case(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_times_from_last_occ:
+ data, features_names = times_from_last_occurrence_activity_case(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_direct_paths_times_last_occ:
+ data, features_names = direct_paths_times_last_occ(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_indirect_paths_times_last_occ:
+ data, features_names = indirect_paths_times_last_occ(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_work_in_progress:
+ data, features_names = work_in_progress(log, parameters=parameters)
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_resource_workload:
+ data, features_names = resource_workload(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_first_last_activity_index:
+ data, features_names = first_last_activity_index_trace(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_max_concurrent_events:
+ data, features_names = max_concurrent_events(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ if enable_max_concurrent_events_per_activity:
+ data, features_names = max_concurrent_events_per_activity(
+ log, parameters=parameters
+ )
+ for i in range(len(datas)):
+ datas[i] = datas[i] + data[i]
+ features_namess = features_namess + features_names
+
+ return datas, features_namess
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/word2vec.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/word2vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9a89551984470b7d1ca6de906199ae196cfe77a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/word2vec.py
@@ -0,0 +1,149 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+"""
+Trace-level Word2Vec encoding.
+
+From an event-log point of view, each case is treated as a short sentence and
+each event token is treated as a word. A Word2Vec model learns a vector for
+each token from the neighboring tokens observed in the traces. A trace vector
+is then obtained by aggregating the token vectors in that trace.
+
+Example with activity tokens:
+ case 1: A, B, C
+ case 2: A, B, D
+
+Word2Vec learns vectors for A, B, C, and D from their contexts. The trace
+vector for case 1 is, by default, the mean of vectors A, B, and C.
+
+Reference:
+Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
+"Trace encoding in process mining: A survey and benchmarking."
+Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
+https://doi.org/10.1016/j.engappai.2023.107028
+
+This variant delegates model training/inference to gensim's maintained
+Word2Vec implementation.
+"""
+
+from enum import Enum
+from typing import Any, Dict, Optional, Union
+
+import numpy as np
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.algo.transformation.trace_encodings.util import trace_text
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ EVENT_ATTRIBUTES = "event_attributes"
+ TRACE_ATTRIBUTES = "trace_attributes"
+ MODEL = "model"
+ VECTOR_SIZE = "vector_size"
+ WINDOW = "window"
+ MIN_COUNT = "min_count"
+ WORKERS = "workers"
+ EPOCHS = "epochs"
+ SG = "sg"
+ AGGREGATION = "aggregation"
+
+
+def _aggregate(vectors, vector_size, aggregation):
+ if not vectors:
+ return [0.0] * vector_size
+
+ matrix = np.asarray(vectors, dtype=float)
+ if aggregation == "sum":
+ return matrix.sum(axis=0).tolist()
+ return matrix.mean(axis=0).tolist()
+
+
+def apply(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Encodes each trace by aggregating gensim Word2Vec token vectors.
+
+ Parameters
+ ----------
+ log
+ Event log, event stream, or dataframe containing traces.
+ parameters
+ Parameters of the encoding. Common options:
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
+ the activity attribute.
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
+ - MODEL: pre-trained gensim Word2Vec model. If omitted, a model is
+ trained on the provided log.
+ - VECTOR_SIZE, WINDOW, MIN_COUNT, WORKERS, EPOCHS, SG: gensim Word2Vec
+ training parameters.
+ - AGGREGATION: "mean" or "sum" token-vector aggregation.
+
+ Returns
+ -------
+ data
+ One row per trace, containing the aggregated Word2Vec dimensions.
+ feature_names
+ Dimension names corresponding to the columns of data.
+ """
+ if parameters is None:
+ parameters = {}
+
+ try:
+ from gensim.models import Word2Vec
+ except ImportError as exc:
+ raise ImportError(
+ "The WORD2VEC trace encoding uses gensim. Please install gensim "
+ "to use this variant."
+ ) from exc
+
+ _, traces = trace_text.log_to_trace_tokens(log, parameters=parameters)
+ vector_size = exec_utils.get_param_value(
+ Parameters.VECTOR_SIZE, parameters, 100
+ )
+ model = exec_utils.get_param_value(Parameters.MODEL, parameters, None)
+ aggregation = exec_utils.get_param_value(
+ Parameters.AGGREGATION, parameters, "mean"
+ )
+
+ if model is None:
+ model = Word2Vec(
+ sentences=traces,
+ vector_size=vector_size,
+ window=exec_utils.get_param_value(Parameters.WINDOW, parameters, 5),
+ min_count=exec_utils.get_param_value(Parameters.MIN_COUNT, parameters, 1),
+ workers=exec_utils.get_param_value(Parameters.WORKERS, parameters, 1),
+ sg=exec_utils.get_param_value(Parameters.SG, parameters, 1),
+ epochs=exec_utils.get_param_value(Parameters.EPOCHS, parameters, 10),
+ )
+ else:
+ vector_size = int(model.vector_size)
+
+ data = []
+ for trace in traces:
+ vectors = [model.wv[token] for token in trace if token in model.wv]
+ data.append(_aggregate(vectors, vector_size, aggregation))
+
+ feature_names = ["@@word2vec_dim_" + str(i) for i in range(vector_size)]
+ return data, feature_names
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/analysis.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..60340f48bed4eff53ef3e03153f89261677f0693
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/analysis.py
@@ -0,0 +1,980 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+"""
+
+from typing import List, Optional, Tuple, Dict, Union, Generator, Set, Any
+
+from pm4py.objects.log.obj import Trace, EventLog, EventStream
+from pm4py.utils import __event_log_deprecation_warning
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.utils import get_properties, pandas_utils, constants
+from pm4py.util.pandas_utils import check_is_pandas_dataframe, check_pandas_dataframe_columns
+from pm4py.util import labels_similarity as ls_util
+from pm4py.util import deprecation
+
+import pandas as pd
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="this method will be removed in a future release.",
+)
+def construct_synchronous_product_net(
+ trace: Trace,
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Constructs the synchronous product net between a trace and a Petri net process model.
+
+ :param trace: A trace from an event log.
+ :param petri_net: The Petri net process model.
+ :param initial_marking: The initial marking of the Petri net.
+ :param final_marking: The final marking of the Petri net.
+ :return: A tuple containing the synchronous Petri net, the initial marking, and the final marking.
+ :rtype: Tuple[PetriNet, ~pm4py.objects.petri_net.obj.Marking, ~pm4py.objects.petri_net.obj.Marking]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ log = pm4py.read_xes('log.xes')
+ sync_net, sync_im, sync_fm = pm4py.construct_synchronous_product_net(log[0], net, im, fm)
+ """
+ from pm4py.objects.petri_net.utils.petri_utils import construct_trace_net
+ from pm4py.objects.petri_net.utils.synchronous_product import construct
+ from pm4py.objects.petri_net.utils.align_utils import SKIP
+
+ trace_net, trace_im, trace_fm = construct_trace_net(trace)
+ sync_net, sync_im, sync_fm = construct(
+ trace_net,
+ trace_im,
+ trace_fm,
+ petri_net,
+ initial_marking,
+ final_marking,
+ SKIP,
+ )
+ return sync_net, sync_im, sync_fm
+
+
+def compute_emd(
+ language1: Dict[List[str], float], language2: Dict[List[str], float]
+) -> float:
+ """
+ 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.
+
+ :param language1: The first stochastic language.
+ :param language2: The second stochastic language.
+ :return: The computed Earth Mover Distance.
+ :rtype: float
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes('tests/input_data/running-example.xes')
+ language_log = pm4py.get_stochastic_language(log)
+ print(language_log)
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
+ language_model = pm4py.get_stochastic_language(net, im, fm)
+ print(language_model)
+ emd_distance = pm4py.compute_emd(language_log, language_model)
+ print(emd_distance)
+ """
+ from pm4py.algo.evaluation.earth_mover_distance import (
+ algorithm as earth_mover_distance,
+ )
+
+ return earth_mover_distance.apply(language1, language2)
+
+
+def solve_marking_equation(
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ cost_function: Dict[PetriNet.Transition, float] = None,
+) -> float:
+ """
+ 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.
+
+ :param petri_net: The Petri net.
+ :param initial_marking: The initial marking of the Petri net.
+ :param final_marking: The final marking of the Petri net.
+ :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.
+ :return: The heuristic value obtained by solving the marking equation.
+ :rtype: float
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ heuristic = pm4py.solve_marking_equation(net, im, fm)
+ """
+ from pm4py.algo.analysis.marking_equation import (
+ algorithm as marking_equation,
+ )
+
+ if cost_function is None:
+ cost_function = {t: 1 for t in petri_net.transitions}
+
+ me = marking_equation.build(
+ petri_net,
+ initial_marking,
+ final_marking,
+ parameters={"costs": cost_function},
+ )
+ return marking_equation.get_h_value(me)
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="this method will be removed in a future release.",
+)
+def solve_extended_marking_equation(
+ trace: Trace,
+ sync_net: PetriNet,
+ sync_im: Marking,
+ sync_fm: Marking,
+ split_points: Optional[List[int]] = None,
+) -> float:
+ """
+ Computes a heuristic value (an underestimation of the cost of an alignment) between a trace
+ and a synchronous product net using the extended marking equation with the standard cost function.
+ For example, synchronization moves have a cost of 0, invisible moves have a cost of 1,
+ and other moves on the model or log have a cost of 10,000. This method provides optimal provisioning of the split points.
+
+ :param trace: The trace to evaluate.
+ :param sync_net: The synchronous product net.
+ :param sync_im: The initial marking of the synchronous net.
+ :param sync_fm: The final marking of the synchronous net.
+ :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.
+ :return: The heuristic value representing the cost underestimation.
+ :rtype: float
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ log = pm4py.read_xes('log.xes')
+ ext_mark_eq_heu = pm4py.solve_extended_marking_equation(log[0], net, im, fm)
+ """
+ from pm4py.algo.analysis.extended_marking_equation import (
+ algorithm as extended_marking_equation,
+ )
+
+ parameters = {}
+ if split_points is not None:
+ parameters[
+ extended_marking_equation.Variants.CLASSIC.value.Parameters.SPLIT_IDX
+ ] = split_points
+ me = extended_marking_equation.build(
+ trace, sync_net, sync_im, sync_fm, parameters=parameters
+ )
+ return extended_marking_equation.get_h_value(me)
+
+
+def check_is_sound(petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking) -> bool:
+ """
+ Checks if a given Petri net is a sound Workflow net (WF-net).
+ Returns a boolean value.
+
+ A Petri net is a WF-net if and only if:
+
+ - It has a unique source place.
+ - It has a unique end place.
+ - Every element in the WF-net is on a path from the source to the sink place.
+
+ A WF-net is sound if and only if:
+
+ - It contains no live-locks.
+ - It contains no deadlocks.
+ - It is always possible to reach the final marking from any reachable marking.
+
+ :param petri_net: The Petri net to check.
+ :param initial_marking: The initial marking of the Petri net.
+ :param final_marking: The final marking of the Petri net.
+ :returns: boolean (True if the Petri net is sound)
+ """
+ try:
+ from pm4py.convert import convert_to_powl
+ powl_model = convert_to_powl(petri_net, initial_marking, final_marking)
+ return True
+ except:
+ pass
+
+ from pm4py.algo.analysis.woflan import algorithm as woflan
+ soundness = woflan.apply(
+ petri_net,
+ initial_marking,
+ final_marking,
+ parameters={
+ "return_asap_when_not_sound": True,
+ "return_diagnostics": True,
+ "print_diagnostics": False,
+ },
+ )
+
+ return soundness[0]
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="this method will be removed in a future release.",
+)
+def check_soundness(
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ print_diagnostics: bool = False,
+) -> Tuple[bool, Dict[str, Any]]:
+ """
+ Checks if a given Petri net is a sound Workflow net (WF-net).
+
+ A Petri net is a WF-net if and only if:
+
+ - It has a unique source place.
+ - It has a unique end place.
+ - Every element in the WF-net is on a path from the source to the sink place.
+
+ A WF-net is sound if and only if:
+
+ - It contains no live-locks.
+ - It contains no deadlocks.
+ - It is always possible to reach the final marking from any reachable marking.
+
+ For a formal definition of a sound WF-net, refer to: http://www.padsweb.rwth-aachen.de/wvdaalst/publications/p628.pdf
+
+ The returned tuple consists of:
+
+ - A boolean indicating whether the Petri net is a sound WF-net.
+ - A dictionary containing diagnostics collected while running WOFLAN, associating diagnostic names with their corresponding details.
+
+ :param petri_net: The Petri net to check.
+ :param initial_marking: The initial marking of the Petri net.
+ :param final_marking: The final marking of the Petri net.
+ :param print_diagnostics: If True, additional diagnostics will be printed during the execution of WOFLAN.
+ :return: A tuple containing a boolean indicating soundness and a dictionary of diagnostics.
+ :rtype: Tuple[bool, Dict[str, Any]]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ is_sound = pm4py.check_soundness(net, im, fm)
+ """
+ from pm4py.algo.analysis.woflan import algorithm as woflan
+
+ return woflan.apply(
+ petri_net,
+ initial_marking,
+ final_marking,
+ parameters={
+ "return_asap_when_not_sound": True,
+ "return_diagnostics": True,
+ "print_diagnostics": print_diagnostics,
+ },
+ )
+
+
+def cluster_log(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ sklearn_clusterer=None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Generator[EventLog, None, None]:
+ """
+ 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).
+
+ :param log: The event log to cluster.
+ :param sklearn_clusterer: (Optional) The Scikit-Learn clusterer to use. Default is KMeans with `n_clusters=2`, `random_state=0`, and `n_init="auto"`.
+ :param activity_key: The key used to identify activities in the log.
+ :param timestamp_key: The key used to identify timestamps in the log.
+ :param case_id_key: The key used to identify case IDs in the log.
+ :return: A generator that yields clustered event logs as pandas DataFrames.
+ :rtype: Generator[pd.DataFrame, None, None]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ for clust_log in pm4py.cluster_log(df):
+ print(clust_log)
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+ if sklearn_clusterer is not None:
+ properties["sklearn_clusterer"] = sklearn_clusterer
+
+ from pm4py.algo.clustering.profiles import algorithm as clusterer
+
+ return clusterer.apply(log, parameters=properties)
+
+
+def insert_artificial_start_end(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ artificial_start=constants.DEFAULT_ARTIFICIAL_START_ACTIVITY,
+ artificial_end=constants.DEFAULT_ARTIFICIAL_END_ACTIVITY,
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Inserts artificial start and end activities into an event log or a Pandas DataFrame.
+
+ :param log: The event log or Pandas DataFrame to modify.
+ :param activity_key: The attribute key used for activities.
+ :param timestamp_key: The attribute key used for timestamps.
+ :param case_id_key: The attribute key used to identify cases.
+ :param artificial_start: The symbol to use for the artificial start activity.
+ :param artificial_end: The symbol to use for the artificial end activity.
+ :return: The event log or Pandas DataFrame with artificial start and end activities inserted.
+ :rtype: Union[EventLog, pd.DataFrame]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.insert_artificial_start_end(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+ properties[constants.PARAM_ARTIFICIAL_START_ACTIVITY] = artificial_start
+ properties[constants.PARAM_ARTIFICIAL_END_ACTIVITY] = artificial_end
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+ from pm4py.objects.log.util import dataframe_utils
+
+ return dataframe_utils.insert_artificial_start_end(
+ log, parameters=properties
+ )
+ else:
+ from pm4py.objects.log.util import artificial
+
+ return artificial.insert_artificial_start_end(
+ log, parameters=properties
+ )
+
+
+def insert_case_service_waiting_time(
+ log: Union[EventLog, pd.DataFrame],
+ service_time_column: str = "@@service_time",
+ sojourn_time_column: str = "@@sojourn_time",
+ waiting_time_column: str = "@@waiting_time",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ start_timestamp_key: str = "time:timestamp",
+) -> pd.DataFrame:
+ """
+ Inserts service time, waiting time, and sojourn time information for each case into a Pandas DataFrame.
+
+ :param log: The event log or Pandas DataFrame to modify.
+ :param service_time_column: The name of the column to store service times.
+ :param sojourn_time_column: The name of the column to store sojourn times.
+ :param waiting_time_column: The name of the column to store waiting times.
+ :param activity_key: The attribute key used for activities.
+ :param timestamp_key: The attribute key used for timestamps.
+ :param case_id_key: The attribute key used to identify cases.
+ :param start_timestamp_key: The attribute key used for the start timestamp of cases.
+ :return: A Pandas DataFrame with the inserted service, waiting, and sojourn time columns.
+ :rtype: pd.DataFrame
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.insert_case_service_waiting_time(
+ dataframe,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name',
+ start_timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+
+ from pm4py.objects.conversion.log import converter as log_converter
+
+ log_df = log_converter.apply(
+ log,
+ variant=log_converter.Variants.TO_DATA_FRAME,
+ parameters=properties,
+ )
+
+ return pandas_utils.insert_case_service_waiting_time(
+ log_df,
+ case_id_column=case_id_key,
+ timestamp_column=timestamp_key,
+ start_timestamp_column=start_timestamp_key,
+ service_time_column=service_time_column,
+ waiting_time_column=waiting_time_column,
+ sojourn_time_column=sojourn_time_column,
+ )
+
+
+def insert_case_arrival_finish_rate(
+ log: Union[EventLog, pd.DataFrame],
+ arrival_rate_column: str = "@@arrival_rate",
+ finish_rate_column: str = "@@finish_rate",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ start_timestamp_key: str = "time:timestamp",
+) -> pd.DataFrame:
+ """
+ Inserts arrival and finish rate information for each case into a Pandas DataFrame.
+
+ 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.
+ 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.
+
+ :param log: The event log or Pandas DataFrame to modify.
+ :param arrival_rate_column: The name of the column to store arrival rates.
+ :param finish_rate_column: The name of the column to store finish rates.
+ :param activity_key: The attribute key used for activities.
+ :param timestamp_key: The attribute key used for timestamps.
+ :param case_id_key: The attribute key used to identify cases.
+ :param start_timestamp_key: The attribute key used for the start timestamp of cases.
+ :return: A Pandas DataFrame with the inserted arrival and finish rate columns.
+ :rtype: pd.DataFrame
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.insert_case_arrival_finish_rate(
+ dataframe,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name',
+ start_timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+
+ from pm4py.objects.conversion.log import converter as log_converter
+
+ log_df = log_converter.apply(
+ log,
+ variant=log_converter.Variants.TO_DATA_FRAME,
+ parameters=properties,
+ )
+
+ return pandas_utils.insert_case_arrival_finish_rate(
+ log_df,
+ case_id_column=case_id_key,
+ timestamp_column=timestamp_key,
+ start_timestamp_column=start_timestamp_key,
+ arrival_rate_column=arrival_rate_column,
+ finish_rate_column=finish_rate_column,
+ )
+
+
+def check_is_workflow_net(net: PetriNet) -> bool:
+ """
+ Checks if the input Petri net satisfies the WF-net (Workflow net) conditions:
+ 1. It has a unique source place.
+ 2. It has a unique sink place.
+ 3. Every node is on a path from the source to the sink.
+
+ :param net: The Petri net to check.
+ :return: True if the Petri net is a WF-net, False otherwise.
+ :rtype: bool
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net = pm4py.read_pnml('model.pnml')
+ is_wfnet = pm4py.check_is_workflow_net(net)
+ """
+ from pm4py.algo.analysis.workflow_net import algorithm
+
+ return algorithm.apply(net)
+
+
+def maximal_decomposition(
+ net: PetriNet, im: Marking, fm: Marking
+) -> List[Tuple[PetriNet, Marking, Marking]]:
+ """
+ Calculates the maximal decomposition of an accepting Petri net into its maximal components.
+
+ :param net: The Petri net to decompose.
+ :param im: The initial marking of the Petri net.
+ :param fm: The final marking of the Petri net.
+ :return: A list of tuples, each containing a subnet Petri net, its initial marking, and its final marking.
+ :rtype: List[Tuple[PetriNet, ~pm4py.objects.petri_net.obj.Marking, ~pm4py.objects.petri_net.obj.Marking]]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ list_nets = pm4py.maximal_decomposition(net, im, fm)
+ for subnet, subim, subfm in list_nets:
+ pm4py.view_petri_net(subnet, subim, subfm, format='svg')
+ """
+ from pm4py.objects.petri_net.utils.decomposition import decompose
+
+ return decompose(net, im, fm)
+
+
+def simplicity_petri_net(
+ net: PetriNet,
+ im: Marking,
+ fm: Marking,
+ variant: Optional[str] = "arc_degree",
+) -> float:
+ """
+ Computes the simplicity metric for a given Petri net model.
+
+ Three available approaches are supported:
+
+ - **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.
+ - **Extended Cardoso Metric**: Described in the paper "Complexity Metrics for Workflow Nets" by Lassen, Kristian Bisgaard, and Wil MP van der Aalst.
+ - **Extended Cyclomatic Metric**: Also described in the paper "Complexity Metrics for Workflow Nets" by Lassen, Kristian Bisgaard, and Wil MP van der Aalst.
+
+ :param net: The Petri net for which to compute simplicity.
+ :param im: The initial marking of the Petri net.
+ :param fm: The final marking of the Petri net.
+ :param variant: The simplicity metric variant to use ('arc_degree', 'extended_cardoso', 'extended_cyclomatic').
+ :return: The computed simplicity value.
+ :rtype: float
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ simplicity = pm4py.simplicity_petri_net(net, im, fm, variant='arc_degree')
+ """
+ if variant == "arc_degree":
+ from pm4py.algo.evaluation.simplicity.variants import arc_degree
+
+ return arc_degree.apply(net)
+ elif variant == "extended_cardoso":
+ from pm4py.algo.evaluation.simplicity.variants import extended_cardoso
+
+ return extended_cardoso.apply(net)
+ elif variant == "extended_cyclomatic":
+ from pm4py.algo.evaluation.simplicity.variants import (
+ extended_cyclomatic,
+ )
+
+ return extended_cyclomatic.apply(net, im)
+
+
+def generate_marking(
+ net: PetriNet,
+ place_or_dct_places: Union[
+ str, PetriNet.Place, Dict[str, int], Dict[PetriNet.Place, int]
+ ],
+) -> Marking:
+ """
+ Generates a marking for a given Petri net based on specified places and token counts.
+
+ :param net: The Petri net for which to generate the marking.
+ :param place_or_dct_places: Specifies the places and their token counts for the marking. It can be:
+
+ - A single `PetriNet.Place` object, which will have one token.
+ - A string representing the name of a place, which will have one token.
+ - A dictionary mapping `PetriNet.Place` objects to their respective number of tokens.
+ - 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
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ marking = pm4py.generate_marking(net, {'source': 2})
+ """
+ dct_places = {x.name: x for x in net.places}
+ if isinstance(place_or_dct_places, PetriNet.Place):
+ # A single Place object is specified for the marking
+ return Marking({place_or_dct_places: 1})
+ elif isinstance(place_or_dct_places, str):
+ # The name of a place is specified for the marking
+ return Marking({dct_places[place_or_dct_places]: 1})
+ elif isinstance(place_or_dct_places, dict):
+ dct_keys = list(place_or_dct_places)
+ if dct_keys:
+ if isinstance(dct_keys[0], PetriNet.Place):
+ # A dictionary mapping Place objects to token counts is
+ # specified
+ return Marking(place_or_dct_places)
+ elif isinstance(dct_keys[0], str):
+ # A dictionary mapping place names to token counts is specified
+ return Marking(
+ {dct_places[x]: y for x, y in place_or_dct_places.items()}
+ )
+
+
+def reduce_petri_net_invisibles(net: PetriNet) -> PetriNet:
+ """
+ Reduces the number of invisible transitions in the provided Petri net.
+
+ :param net: The Petri net to be reduced.
+ :return: The reduced Petri net with fewer invisible transitions.
+ :rtype: PetriNet
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ net = pm4py.reduce_petri_net_invisibles(net)
+ """
+ from pm4py.objects.petri_net.utils import reduction
+
+ return reduction.apply_simple_reduction(net)
+
+
+def reduce_petri_net_implicit_places(
+ net: PetriNet, im: Marking, fm: Marking
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Reduces the number of implicit places in the provided Petri net.
+
+ :param net: The Petri net to be reduced.
+ :param im: The initial marking of the Petri net.
+ :param fm: The final marking of the Petri net.
+ :return: A tuple containing the reduced Petri net, its initial marking, and its final marking.
+ :rtype: Tuple[PetriNet, ~pm4py.objects.petri_net.obj.Marking, ~pm4py.objects.petri_net.obj.Marking]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('model.pnml')
+ net, im, fm = pm4py.reduce_petri_net_implicit_places(net, im, fm)
+ """
+ from pm4py.objects.petri_net.utils import murata
+
+ return murata.apply_reduction(net, im, fm)
+
+
+def get_enabled_transitions(
+ net: PetriNet, marking: Marking
+) -> Set[PetriNet.Transition]:
+ """
+ Retrieves the set of transitions that are enabled in a given marking of a Petri net.
+
+ :param net: The Petri net.
+ :param marking: The current marking of the Petri net.
+ :return: A set of transitions that are enabled in the provided marking.
+ :rtype: Set[PetriNet.Transition]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
+ # Gets the transitions enabled in the initial marking
+ enabled_transitions = pm4py.get_enabled_transitions(net, im)
+ """
+ from pm4py.objects.petri_net import semantics
+
+ return semantics.enabled_transitions(net, marking)
+
+
+def get_activity_labels(*args) -> List[str]:
+ """Gets the activity labels from the specified event log / process model.
+
+ Returns
+ ---------------
+ activities : list
+ Activity labels
+
+ """
+ import pm4py
+
+ if isinstance(args[0], EventLog):
+ labels = set(y["concept:name"] for x in args[0] for y in x)
+ elif isinstance(args[0], pd.DataFrame):
+ labels = set(args[0]["concept:name"].unique())
+ else:
+ net, im, fm = pm4py.convert_to_petri_net(*args)
+ labels = {x.label for x in net.transitions if x.label is not None}
+ return sorted(list(labels))
+
+
+def replace_activity_labels(string_dictio, *args):
+ """
+ Replace the activity labels in the specified process model.
+
+ The first argument is the dictionary, i.e., {"pay": "pay
+ compensation", "reject": "reject request"} The rest is the
+ specification of the process model
+ """
+ from pm4py.objects.powl.obj import POWL
+ from pm4py.objects.bpmn.obj import BPMN
+
+ if isinstance(args[0], POWL):
+ from pm4py.objects.powl.utils import label_replacing
+ return label_replacing.apply(args[0], string_dictio)
+ elif isinstance(args[0], ProcessTree):
+ from pm4py.objects.process_tree.utils import label_replacing
+ return label_replacing.apply(args[0], string_dictio)
+ elif isinstance(args[0], PetriNet):
+ from pm4py.objects.petri_net.utils import label_replacing
+ return label_replacing.apply(args[0], args[1], args[2], string_dictio)
+ elif isinstance(args[0], BPMN):
+ from pm4py.objects.bpmn.util import label_replacing
+ return label_replacing.apply(args[0], string_dictio)
+ else:
+ raise Exception("unsupported.")
+
+
+def __extract_models(*args) -> List[Any]:
+ if len(args) < 2:
+ raise Exception("Insufficient arguments provided.")
+
+ counter = 0
+ lst_models = []
+
+ import pm4py
+ for i in range(2):
+ if type(args[counter]) is PetriNet:
+ net, im, fm = args[counter:counter + 3]
+ lst_models.append([net, im, fm])
+ counter += 3
+ elif isinstance(args[counter], dict):
+ dfg, sa, ea = args[counter:counter + 3]
+ net, im, fm = pm4py.convert_to_petri_net(dfg, sa, ea)
+ lst_models.append([net, im, fm])
+ counter += 3
+ else:
+ obj = args[counter]
+ lst_models.append([obj])
+ counter += 1
+
+ return lst_models
+
+
+def behavioral_similarity(*args) -> float:
+ """
+ Computes the behavioral similarity (footprints-based) between two process models.
+
+ Examples:
+
+ * pm4py.behavioral_similarity(petri_net, im, fm, process_tree)
+ * pm4py.behavioral_similarity(bpmn1, bpmn2)
+ * pm4py.behavioral_similarity(process_tree, powl)
+
+ Returns
+ --------------
+ similarity
+ Footprints-based behavioral similarity
+
+ """
+ lst_models = __extract_models(*args)
+
+ import pm4py
+ footprints = []
+ for i in range(len(lst_models)):
+ x = lst_models[i]
+ if not (isinstance(x[0], PetriNet) or isinstance(x[0], ProcessTree)):
+ x = [pm4py.convert_to_powl(*x)]
+
+ footprints.append(pm4py.discover_footprints(*x))
+
+ footprints1, footprints2 = footprints
+
+ sequence_union = footprints1["sequence"].union(footprints2["sequence"])
+ sequence_intersection = footprints1["sequence"].intersection(footprints2["sequence"])
+
+ parallel_union = footprints1["parallel"].union(footprints2["parallel"])
+ parallel_intersection = footprints1["parallel"].intersection(footprints2["parallel"])
+
+ denominator = len(sequence_union) + len(parallel_union)
+
+ if denominator == 0:
+ return 0
+ else:
+ return (len(sequence_intersection) + len(parallel_intersection)) / denominator
+
+
+def structural_similarity(*args) -> float:
+ """
+ Computes the structural similarity between two semi-block-structured process models,
+ following an approach similar to:
+
+ Yan, Z., Dijkman, R., & Grefen, P. (2012). Fast business process similarity search.
+ Distributed and Parallel Databases, 30(2), 105–144.
+ (https://doi.org/10.1007/s10619-012-7089-z)
+
+ Examples:
+
+ * pm4py.structural_similarity(petri_net, im, fm, process_tree)
+ * pm4py.structural_similarity(bpmn1, bpmn2)
+ * pm4py.structural_similarity(process_tree, powl)
+
+ Returns
+ --------------
+ similarity
+ Structural similarity
+
+ """
+ lst_models = __extract_models(*args)
+
+ import pm4py
+ i = 0
+ while i < len(lst_models):
+ lst_models[i] = pm4py.convert_to_process_tree(pm4py.convert_to_powl(*lst_models[i]))
+ i = i + 1
+
+ from pm4py.objects.process_tree.utils import struct_similarity
+ return struct_similarity.structural_similarity(lst_models[0], lst_models[1])
+
+
+def embeddings_similarity(*args) -> float:
+ """
+ Computes the embeddings similarity between two process models,
+ following the approach described in:
+
+ Colonna, Juan G., et al. "Process mining embeddings: Learning vector representations for Petri nets."
+ Intelligent Systems with Applications 23 (2024): 200423.
+
+ Examples:
+
+ * pm4py.embeddings_similarity(petri_net, im, fm, process_tree)
+ * pm4py.embeddings_similarity(bpmn1, bpmn2)
+ * pm4py.embeddings_similarity(process_tree, powl)
+
+ Returns
+ --------------
+ similarity
+ Structural similarity
+
+ """
+ lst_models = __extract_models(*args)
+
+ import pm4py
+ i = 0
+ while i < len(lst_models):
+ lst_models[i] = pm4py.convert_to_petri_net(*lst_models[i])
+ i = i + 1
+
+ from pm4py.objects.petri_net.utils import embeddings_similarity
+ return embeddings_similarity.apply(lst_models[0][0], lst_models[1][0])
+
+
+def label_sets_similarity(*args, threshold=0.75) -> float:
+ """
+ Computes the label sets similarity between two process models.
+
+ Examples:
+
+ * pm4py.labels_similarity(petri_net, im, fm, process_tree)
+ * pm4py.labels_similarity(bpmn1, bpmn2)
+ * pm4py.labels_similarity(process_tree, powl)
+
+ Returns
+ --------------
+ similarity
+ Label sets similarity
+
+ """
+ lst_models = __extract_models(*args)
+ labels = []
+ i = 0
+ while i < len(lst_models):
+ labels.append(get_activity_labels(*lst_models[i]))
+ i = i + 1
+
+ return ls_util.label_sets_similarity(labels[0], labels[1], threshold=threshold)
+
+
+def map_labels_from_second_model(*args, threshold=0.75):
+ """
+ Maps the labels from the second process model into the first.
+
+ Example usages:
+
+ * pm4py.map_labels_from_second_model(net, im, fm, process_tree)
+ * pm4py.map_labels_from_second_model(process_tree, net, im, fm)
+ * pm4py.map_labels_from_second_model(powl1, powl2)
+ """
+ lst_models = __extract_models(*args)
+ labels = []
+ i = 0
+ while i < len(lst_models):
+ labels.append(get_activity_labels(*lst_models[i]))
+ i = i + 1
+
+ label_mapping = ls_util.map_labels(labels[0], labels[1], threshold=threshold)
+ return replace_activity_labels(label_mapping, *lst_models[0])
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/cli.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b0aac9887274aa2d7b1d287deb5f653f6f2da99
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/cli.py
@@ -0,0 +1,450 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import pm4py
+import sys
+import os
+import itertools
+from pathlib import Path
+import traceback
+import pandas as pd
+from pm4py.util import constants, pandas_utils
+
+
+methods = {
+ "ConvertToXES": {
+ "inputs": [".csv"],
+ "output_extension": ".xes",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.convert_to_event_log(
+ pm4py.format_dataframe(pandas_utils.read_csv(x[0]))
+ ),
+ x[1],
+ ),
+ },
+ "ConvertToCSV": {
+ "inputs": [".xes"],
+ "output_extension": ".csv",
+ "method": lambda x: pm4py.convert_to_dataframe(
+ pm4py.read_xes(x[0])
+ ).to_csv(x[1], index=False),
+ },
+ "ConvertPNMLtoBPMN": {
+ "inputs": [".pnml"],
+ "output_extension": ".bpmn",
+ "method": lambda x: pm4py.write_bpmn(
+ pm4py.convert_to_bpmn(*pm4py.read_pnml(x[0])), x[1]
+ ),
+ },
+ "ConvertPNMLtoPTML": {
+ "inputs": [".pnml"],
+ "output_extension": ".ptml",
+ "method": lambda x: pm4py.write_ptml(
+ pm4py.convert_to_process_tree(*pm4py.read_pnml(x[0])), x[1]
+ ),
+ },
+ "ConvertPTMLtoPNML": {
+ "inputs": [".ptml"],
+ "output_extension": ".pnml",
+ "method": lambda x: pm4py.write_pnml(
+ *pm4py.convert_to_petri_net(pm4py.read_ptml(x[0])), x[1]
+ ),
+ },
+ "ConvertPTMLtoBPMN": {
+ "inputs": [".ptml"],
+ "output_extension": ".bpmn",
+ "method": lambda x: pm4py.write_bpmn(
+ pm4py.convert_to_bpmn(pm4py.read_ptml(x[0])), x[1]
+ ),
+ },
+ "ConvertBPMNtoPNML": {
+ "inputs": [".bpmn"],
+ "output_extension": ".pnml",
+ "method": lambda x: pm4py.write_pnml(
+ *pm4py.convert_to_petri_net(pm4py.read_bpmn(x[0])), x[1]
+ ),
+ },
+ "ConvertDFGtoPNML": {
+ "inputs": [".dfg"],
+ "output_extension": ".pnml",
+ "method": lambda x: pm4py.write_pnml(
+ *pm4py.convert_to_petri_net(*pm4py.read_dfg(x[0])), x[1]
+ ),
+ },
+ "DiscoverPetriNetAlpha": {
+ "inputs": [".xes"],
+ "output_extension": ".pnml",
+ "method": lambda x: pm4py.write_pnml(
+ *pm4py.discover_petri_net_alpha(__read_log(x[0])), x[1]
+ ),
+ },
+ "DiscoverPetriNetInductive": {
+ "inputs": [".xes"],
+ "output_extension": ".pnml",
+ "method": lambda x: pm4py.write_pnml(
+ *pm4py.discover_petri_net_inductive(__read_log(x[0])), x[1]
+ ),
+ },
+ "DiscoverPetriNetHeuristics": {
+ "inputs": [".xes"],
+ "output_extension": ".pnml",
+ "method": lambda x: pm4py.write_pnml(
+ *pm4py.discover_petri_net_heuristics(__read_log(x[0])), x[1]
+ ),
+ },
+ "DiscoverPetriNetGenetic": {
+ "inputs": [".xes"],
+ "output_extension": ".pnml",
+ "method": lambda x: pm4py.write_pnml(
+ *pm4py.discover_petri_net_genetic(__read_log(x[0])), x[1]
+ ),
+ },
+ "DiscoverBPMNInductive": {
+ "inputs": [".xes"],
+ "output_extension": ".bpmn",
+ "method": lambda x: pm4py.write_bpmn(
+ pm4py.discover_bpmn_inductive(__read_log(x[0])), x[1]
+ ),
+ },
+ "DiscoverProcessTreeInductive": {
+ "inputs": [".xes"],
+ "output_extension": ".ptml",
+ "method": lambda x: pm4py.write_ptml(
+ pm4py.discover_process_tree_inductive(__read_log(x[0])), x[1]
+ ),
+ },
+ "DiscoverDFG": {
+ "inputs": [".xes"],
+ "output_extension": ".dfg",
+ "method": lambda x: pm4py.write_dfg(
+ *pm4py.discover_dfg(__read_log(x[0])), x[1]
+ ),
+ },
+ "ConformanceDiagnosticsTBR": {
+ "inputs": [".xes", ".pnml"],
+ "output_extension": ".txt",
+ "method": lambda x: open(x[2], "w").write(
+ str(
+ pm4py.conformance_diagnostics_token_based_replay(
+ __read_log(x[0]),
+ *pm4py.read_pnml(x[1]),
+ return_diagnostics_dataframe=False
+ )
+ )
+ ),
+ },
+ "ConformanceDiagnosticsAlignments": {
+ "inputs": [".xes", ".pnml"],
+ "output_extension": ".txt",
+ "method": lambda x: open(x[2], "w").write(
+ str(
+ pm4py.conformance_diagnostics_alignments(
+ __read_log(x[0]),
+ *pm4py.read_pnml(x[1]),
+ return_diagnostics_dataframe=False
+ )
+ )
+ ),
+ },
+ "FitnessTBR": {
+ "inputs": [".xes", ".pnml"],
+ "output_extension": ".txt",
+ "method": lambda x: open(x[2], "w").write(
+ str(
+ pm4py.fitness_token_based_replay(
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
+ )
+ )
+ ),
+ },
+ "FitnessAlignments": {
+ "inputs": [".xes", ".pnml"],
+ "output_extension": ".txt",
+ "method": lambda x: open(x[2], "w").write(
+ str(
+ pm4py.fitness_alignments(
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
+ )
+ )
+ ),
+ },
+ "PrecisionTBR": {
+ "inputs": [".xes", ".pnml"],
+ "output_extension": ".txt",
+ "method": lambda x: open(x[2], "w").write(
+ str(
+ pm4py.precision_token_based_replay(
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
+ )
+ )
+ ),
+ },
+ "PrecisionAlignments": {
+ "inputs": [".xes", ".pnml"],
+ "output_extension": ".txt",
+ "method": lambda x: open(x[2], "w").write(
+ str(
+ pm4py.precision_alignments(
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
+ )
+ )
+ ),
+ },
+ "SaveVisDFG": {
+ "inputs": [".dfg"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_dfg(*pm4py.read_dfg(x[0]), x[1]),
+ },
+ "SaveVisPNML": {
+ "inputs": [".pnml"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_petri_net(
+ *pm4py.read_pnml(x[0]), x[1]
+ ),
+ },
+ "SaveVisBPMN": {
+ "inputs": [".bpmn"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_bpmn(pm4py.read_bpmn(x[0]), x[1]),
+ },
+ "SaveVisPTML": {
+ "inputs": [".ptml"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_process_tree(
+ pm4py.read_ptml(x[0]), x[1]
+ ),
+ },
+ "SaveVisDottedChart": {
+ "inputs": [".xes", None, None, None],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_dotted_chart(
+ __read_log(x[0]), x[4], attributes=[x[1], x[2], x[3]]
+ ),
+ },
+ "SaveVisTransitionSystem": {
+ "inputs": [".xes"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_transition_system(
+ pm4py.discover_transition_system(__read_log(x[0])), x[1]
+ ),
+ },
+ "SaveVisTrie": {
+ "inputs": [".xes"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_prefix_tree(
+ pm4py.discover_prefix_tree(__read_log(x[0])), x[1]
+ ),
+ },
+ "SaveVisEventsDistribution": {
+ "inputs": [".xes", None],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_events_distribution_graph(
+ __read_log(x[0]), x[2], distr_type=x[1]
+ ),
+ },
+ "SaveVisEventsPerTime": {
+ "inputs": [".xes"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_events_per_time_graph(
+ __read_log(x[0]), x[1]
+ ),
+ },
+ "GenerateProcessTree": {
+ "inputs": [None],
+ "output_extension": ".ptml",
+ "method": lambda x: pm4py.write_ptml(
+ pm4py.generate_process_tree(
+ parameters={
+ "min": int(x[0]),
+ "max": int(x[0]),
+ "mode": int(x[0]),
+ }
+ ),
+ x[1],
+ ),
+ },
+ "PNMLplayout": {
+ "inputs": [".pnml"],
+ "output_extension": ".xes",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.play_out(*pm4py.read_pnml(x[0])), x[1]
+ ),
+ },
+ "PTMLplayout": {
+ "inputs": [".ptml"],
+ "output_extension": ".xes",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.play_out(pm4py.read_ptml(x[0])), x[1]
+ ),
+ },
+ "DFGplayout": {
+ "inputs": [".dfg"],
+ "output_extension": ".dfg",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.play_out(*pm4py.read_dfg(x[0])), x[1]
+ ),
+ },
+ "SaveVisSNA": {
+ "inputs": [".xes", None],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_sna(
+ __apply_sna(__read_log(x[0]), x[1]), x[2]
+ ),
+ },
+ "SaveVisCaseDuration": {
+ "inputs": [".xes"],
+ "output_extension": ".png",
+ "method": lambda x: pm4py.save_vis_case_duration_graph(
+ __read_log(x[0]), x[1]
+ ),
+ },
+ "FilterVariantsTopK": {
+ "inputs": [".xes", None],
+ "output_extension": ".xes",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.filter_variants_top_k(__read_log(x[0]), int(x[1])), x[2]
+ ),
+ },
+ "FilterVariantsCoverage": {
+ "inputs": [".xes", None],
+ "output_extension": ".xes",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.filter_variants_by_coverage_percentage(
+ __read_log(x[0]), float(x[1])
+ ),
+ x[2],
+ ),
+ },
+ "FilterCasePerformance": {
+ "inputs": [".xes", None, None],
+ "output_extension": ".xes",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.filter_case_performance(
+ __read_log(x[0]),
+ min_performance=float(x[1]),
+ max_performance=float(x[2]),
+ ),
+ x[3],
+ ),
+ },
+ "FilterTimeRange": {
+ "inputs": [".xes", None, None],
+ "output_extension": ".xes",
+ "method": lambda x: pm4py.write_xes(
+ pm4py.filter_time_range(
+ __read_log(x[0]), x[1] + " 00:00:00", x[2] + " 23:59:59"
+ ),
+ x[3],
+ ),
+ },
+}
+
+
+def __read_log(log_path):
+ if "xes" in log_path.lower():
+ return pm4py.read_xes(log_path)
+ elif "csv" in log_path.lower():
+ dataframe = pandas_utils.read_csv(log_path)
+ dataframe = pm4py.format_dataframe(dataframe)
+ return dataframe
+
+
+def __apply_sna(log, method, **kwargs):
+ if method == "handover":
+ return pm4py.discover_handover_of_work_network(log, **kwargs)
+ elif method == "working_together":
+ return pm4py.discover_working_together_network(log, **kwargs)
+ elif method == "similar_activities":
+ return pm4py.discover_activity_based_resource_similarity(log, **kwargs)
+ elif method == "subcontracting":
+ return pm4py.discover_subcontracting_network(log, **kwargs)
+
+
+def __get_output_name(inp_list, idx, method_name, extension):
+ ret = []
+ for inp in inp_list:
+ ret.append(str(Path(inp).stem))
+ return "_".join(ret) + "_" + method_name + extension
+
+
+def cli_interface():
+ method_name = sys.argv[1]
+ if method_name in methods:
+ method = methods[method_name]
+ inputs = []
+ for i in range(len(method["inputs"])):
+ ci = sys.argv[2 + i]
+ if os.path.isdir(ci):
+ if not os.path.exists(ci):
+ raise Exception(
+ "the provided path (" + ci + ") does not exist."
+ )
+ files = os.listdir(ci)
+ inputs.append(
+ [
+ os.path.join(ci, f)
+ for f in files
+ if os.path.isfile(os.path.join(ci, f))
+ and f.endswith(method["inputs"][i])
+ ]
+ )
+ else:
+ inputs.append([ci])
+ j = 2 + len(method["inputs"])
+ inputs = list(itertools.product(*inputs))
+ if len(inputs) == 1:
+ outputs = [[sys.argv[j]]]
+ else:
+ if not os.path.exists(sys.argv[j]):
+ os.mkdir(sys.argv[j])
+ outputs = [
+ [
+ os.path.join(
+ sys.argv[j],
+ __get_output_name(
+ inputs[z],
+ z,
+ method_name,
+ method["output_extension"],
+ ),
+ )
+ ]
+ for z in range(len(inputs))
+ ]
+ method_tuples = [(*inputs[i], *outputs[i]) for i in range(len(inputs))]
+ for i in range(len(method_tuples)):
+ try:
+ if not os.path.exists(method_tuples[i][-1]):
+ print(method_name, method_tuples[i])
+ method["method"](method_tuples[i])
+ except BaseException:
+ traceback.print_exc()
+ else:
+ raise Exception(
+ "the provided method ("
+ + method_name
+ + ") does not exist in the CLI."
+ )
+
+
+if __name__ == "__main__":
+ cli_interface()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/conformance.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/conformance.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dece80a357a19ee54141aff5a07ad1d73c9c3f7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/conformance.py
@@ -0,0 +1,1578 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+The ``pm4py.conformance`` module contains the conformance checking algorithms implemented in ``pm4py``.
+
+"""
+
+from typing import List, Dict, Any, Union, Optional, Tuple, Set
+
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import xes_constants, constants
+from pm4py.utils import get_properties, __event_log_deprecation_warning
+from pm4py.util.pandas_utils import (
+ check_is_pandas_dataframe,
+ check_pandas_dataframe_columns,
+)
+import pandas as pd
+from pm4py.util import deprecation
+
+
+def conformance_diagnostics_token_based_replay(
+ log: Union[EventLog, pd.DataFrame],
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
+ opt_parameters: Optional[Dict[Any, Any]] = None,
+) -> List[Dict[str, Any]]:
+ """
+ Apply token-based replay for conformance checking analysis.
+ This method returns the full token-based replay diagnostics.
+
+ 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.
+
+ 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.
+
+ The approach is described in:
+ Berti, Alessandro, and Wil MP van der Aalst. "Reviving Token-based Replay: Increasing Speed While Improving Diagnostics." ATAED@ Petri Nets/ACSD. 2019.
+
+ The output of the token-based replay, stored in the variable `replayed_traces`, contains for each trace in the log:
+
+ - **trace_is_fit**: Boolean value indicating whether the trace conforms to the model.
+ - **activated_transitions**: List of transitions activated in the model by the token-based replay.
+ - **reached_marking**: Marking reached at the end of the replay.
+ - **missing_tokens**: Number of missing tokens.
+ - **consumed_tokens**: Number of consumed tokens.
+ - **remaining_tokens**: Number of remaining tokens.
+ - **produced_tokens**: Number of produced tokens.
+
+ :param log: Event log.
+ :param petri_net: Petri net.
+ :param initial_marking: Initial marking.
+ :param final_marking: Final marking.
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
+ :param opt_parameters: Optional parameters for the token-based replay, including:
+
+ * **reach_mark_through_hidden**: Boolean to decide if the final marking should be reached through hidden transitions.
+ * **stop_immediately_unfit**: Boolean to decide if the replay should stop immediately when non-conformance is detected.
+ * **walk_through_hidden_trans**: Boolean to decide if the replay should walk through hidden transitions to enable visible transitions.
+ * **places_shortest_path_by_hidden**: Shortest paths between places using hidden transitions.
+ * **is_reduction**: Indicates if the token-based replay is called in a reduction attempt.
+ * **thread_maximum_ex_time**: Maximum allowed execution time for alignment threads.
+ * **cleaning_token_flood**: Decides if token flood cleaning should be performed.
+ * **disable_variants**: Disable variants grouping.
+ * **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]]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ tbr_diagnostics = pm4py.conformance_diagnostics_token_based_replay(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if return_diagnostics_dataframe:
+ from pm4py.convert import convert_to_event_log
+
+ log = convert_to_event_log(log, case_id_key=case_id_key)
+ case_id_key = None
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if opt_parameters is None:
+ opt_parameters = {}
+
+ for k, v in opt_parameters.items():
+ properties[k] = v
+
+ from pm4py.algo.conformance.tokenreplay import algorithm as token_replay
+
+ result = token_replay.apply(
+ log, petri_net, initial_marking, final_marking, parameters=properties
+ )
+
+ if return_diagnostics_dataframe:
+ return token_replay.get_diagnostics_dataframe(
+ log, result, parameters=properties
+ )
+
+ return result
+
+
+def conformance_diagnostics_alignments(
+ log: Union[EventLog, pd.DataFrame],
+ *args,
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ variant_str: Optional[str] = None,
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
+ **kwargs,
+) -> List[Dict[str, Any]]:
+ """
+ Apply the alignments algorithm between a log and a process model.
+ This method returns the full alignment diagnostics.
+
+ 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:
+
+ - **Sync move**: The event and transition labels correspond, advancing both the trace and the model simultaneously.
+ - **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.
+ - **Move on model**: The event is ``»``, indicating a replay move in the model not mirrored in the trace. These can be further classified as:
+ * **Moves on model involving hidden transitions**: Even if it's not a sync move, the move is fit.
+ * **Moves on model not involving hidden transitions**: The move is unfit and signals a deviation.
+
+ For each trace, a dictionary is associated containing, among other details:
+
+ - **alignment**: The alignment pairs (sync moves, moves on log, moves on model).
+ - **cost**: The cost of the alignment based on the provided cost function.
+ - **fitness**: Equals 1 if the trace fits perfectly.
+
+ :param log: Event log.
+ :param args: Specifications of the process model.
+ :param multi_processing: Boolean to enable multiprocessing (default is `constants.ENABLE_MULTIPROCESSING_DEFAULT`).
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :param variant_str: Variant specification (for Petri net alignments).
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
+ :return: A list of dictionaries containing diagnostics for each trace.
+ :rtype: ``List[Dict[str, Any]]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ alignments_diagnostics = pm4py.conformance_diagnostics_alignments(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if return_diagnostics_dataframe:
+ from pm4py.convert import convert_to_event_log
+
+ log = convert_to_event_log(log, case_id_key=case_id_key)
+ case_id_key = None
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if kwargs:
+ for k, v in kwargs.items():
+ properties[k] = v
+
+ if len(args) == 3:
+ if isinstance(args[0], PetriNet):
+ # Petri net alignments
+ from pm4py.algo.conformance.alignments.petri_net import (
+ algorithm as alignments,
+ )
+
+ variant = alignments.DEFAULT_VARIANT
+ if variant_str is not None:
+ variant = variant_str
+ if multi_processing:
+ result = alignments.apply_multiprocessing(
+ log,
+ args[0],
+ args[1],
+ args[2],
+ parameters=properties,
+ variant=variant,
+ )
+ else:
+ result = alignments.apply(
+ log,
+ args[0],
+ args[1],
+ args[2],
+ parameters=properties,
+ variant=variant,
+ )
+
+ if return_diagnostics_dataframe:
+ return alignments.get_diagnostics_dataframe(
+ log, result, parameters=properties
+ )
+
+ return result
+ elif isinstance(args[0], dict):
+ # DFG alignments
+ from pm4py.algo.conformance.alignments.dfg import (
+ algorithm as dfg_alignment,
+ )
+
+ result = dfg_alignment.apply(
+ log, args[0], args[1], args[2], parameters=properties
+ )
+
+ return result
+ elif len(args) == 1:
+ if isinstance(args[0], ProcessTree):
+ # Process tree alignments
+ from pm4py.algo.conformance.alignments.process_tree.variants import (
+ search_graph_pt, )
+
+ if multi_processing:
+ result = search_graph_pt.apply_multiprocessing(
+ log, args[0], parameters=properties
+ )
+ else:
+ result = search_graph_pt.apply(
+ log, args[0], parameters=properties
+ )
+
+ return result
+ elif isinstance(args[0], (EventLog, pd.DataFrame)):
+ # Edit distance alignments (log to log)
+ from pm4py.algo.conformance.alignments.edit_distance import (
+ algorithm as edit_distance_alignments,
+ )
+
+ result = edit_distance_alignments.apply(
+ log, args[0], parameters=properties
+ )
+
+ return result
+ # Try to convert to Petri net
+ import pm4py
+ from pm4py.algo.conformance.alignments.petri_net import (
+ algorithm as alignments,
+ )
+
+ net, im, fm = pm4py.convert_to_petri_net(*args)
+ if multi_processing:
+ result = alignments.apply_multiprocessing(
+ log, net, im, fm, parameters=properties
+ )
+ else:
+ result = alignments.apply(log, net, im, fm, parameters=properties)
+
+ if return_diagnostics_dataframe:
+ return alignments.get_diagnostics_dataframe(
+ log, result, parameters=properties
+ )
+
+ return result
+
+
+def fitness_token_based_replay(
+ log: Union[EventLog, pd.DataFrame],
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Dict[str, float]:
+ """
+ Calculate the fitness using token-based replay.
+ The fitness is calculated on a log-based level.
+ The output dictionary contains the following keys:
+
+ - **perc_fit_traces**: Percentage of fit traces (from 0.0 to 100.0).
+ - **average_trace_fitness**: Average of the trace fitnesses (between 0.0 and 1.0).
+ - **log_fitness**: Overall fitness of the log (between 0.0 and 1.0).
+ - **percentage_of_fitting_traces**: Percentage of fit traces (from 0.0 to 100.0).
+
+ 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.
+
+ 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.
+
+ The approach is described in:
+ Berti, Alessandro, and Wil MP van der Aalst. "Reviving Token-based Replay: Increasing Speed While Improving Diagnostics." ATAED@ Petri Nets/ACSD. 2019.
+
+ 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.
+
+ 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.
+
+ :param log: Event log.
+ :param petri_net: Petri net.
+ :param initial_marking: Initial marking.
+ :param final_marking: Final marking.
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :return: A dictionary containing fitness metrics.
+ :rtype: ``Dict[str, float]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ fitness_tbr = pm4py.fitness_token_based_replay(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.evaluation.replay_fitness import (
+ algorithm as replay_fitness,
+ )
+
+ result = replay_fitness.apply(
+ log,
+ petri_net,
+ initial_marking,
+ final_marking,
+ variant=replay_fitness.Variants.TOKEN_BASED,
+ parameters=properties,
+ )
+
+ return result
+
+
+def fitness_alignments(
+ log: Union[EventLog, pd.DataFrame],
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ variant_str: Optional[str] = None,
+) -> Dict[str, float]:
+ """
+ Calculate the fitness using alignments.
+ The output dictionary contains the following keys:
+
+ - **average_trace_fitness**: Average of the trace fitnesses (between 0.0 and 1.0).
+ - **log_fitness**: Overall fitness of the log (between 0.0 and 1.0).
+ - **percentage_of_fitting_traces**: Percentage of fit traces (from 0.0 to 100.0).
+
+ 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:
+
+ - **Sync move**: The event and transition labels correspond, advancing both the trace and the model simultaneously.
+ - **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.
+ - **Move on model**: The event is ``»``, indicating a replay move in the model not mirrored in the trace. These can be further classified as:
+ * **Moves on model involving hidden transitions**: Even if it's not a sync move, the move is fit.
+ * **Moves on model not involving hidden transitions**: The move is unfit and signals a deviation.
+
+ 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.
+
+ 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.
+
+ :param log: Event log.
+ :param petri_net: Petri net.
+ :param initial_marking: Initial marking.
+ :param final_marking: Final marking.
+ :param multi_processing: Boolean to enable multiprocessing (default is `constants.ENABLE_MULTIPROCESSING_DEFAULT`).
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :param variant_str: Variant specification.
+ :return: A dictionary containing fitness metrics.
+ :rtype: ``Dict[str, float]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ fitness_alignments = pm4py.fitness_alignments(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.evaluation.replay_fitness import (
+ algorithm as replay_fitness,
+ )
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["multiprocessing"] = multi_processing
+ result = replay_fitness.apply(
+ log,
+ petri_net,
+ initial_marking,
+ final_marking,
+ variant=replay_fitness.Variants.ALIGNMENT_BASED,
+ align_variant=variant_str,
+ parameters=parameters,
+ )
+
+ return result
+
+
+def precision_token_based_replay(
+ log: Union[EventLog, pd.DataFrame],
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> float:
+ """
+ Calculate precision using token-based replay.
+
+ 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.
+
+ 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.
+
+ The approach is described in:
+ Berti, Alessandro, and Wil MP van der Aalst. "Reviving Token-based Replay: Increasing Speed While Improving Diagnostics." ATAED@ Petri Nets/ACSD. 2019.
+
+ The reference paper for the TBR-based precision (ETConformance) is:
+ 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.
+
+ 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.
+
+ :param log: Event log.
+ :param petri_net: Petri net.
+ :param initial_marking: Initial marking.
+ :param final_marking: Final marking.
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :return: The precision value.
+ :rtype: ``float``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ precision_tbr = pm4py.precision_token_based_replay(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.evaluation.precision import (
+ algorithm as precision_evaluator,
+ )
+
+ result = precision_evaluator.apply(
+ log,
+ petri_net,
+ initial_marking,
+ final_marking,
+ variant=precision_evaluator.Variants.ETCONFORMANCE_TOKEN,
+ parameters=properties,
+ )
+
+ return result
+
+
+def precision_alignments(
+ log: Union[EventLog, pd.DataFrame],
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> float:
+ """
+ Calculate the precision of the model with respect to the event log using alignments.
+
+ 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:
+
+ - **Sync move**: The event and transition labels correspond, advancing both the trace and the model simultaneously.
+ - **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.
+ - **Move on model**: The event is ``»``, indicating a replay move in the model not mirrored in the trace. These can be further classified as:
+ * **Moves on model involving hidden transitions**: Even if it's not a sync move, the move is fit.
+ * **Moves on model not involving hidden transitions**: The move is unfit and signals a deviation.
+
+ The reference paper for the alignments-based precision (Align-ETConformance) is:
+ Adriansyah, Arya, et al. "Measuring precision of modeled behavior." Information systems and e-Business Management 13.1 (2015): 37-67.
+
+ 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.
+
+ :param log: Event log.
+ :param petri_net: Petri net.
+ :param initial_marking: Initial marking.
+ :param final_marking: Final marking.
+ :param multi_processing: Boolean to enable multiprocessing (default is `constants.ENABLE_MULTIPROCESSING_DEFAULT`).
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :return: The precision value.
+ :rtype: ``float``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ precision_alignments = pm4py.precision_alignments(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.evaluation.precision import (
+ algorithm as precision_evaluator,
+ )
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["multiprocessing"] = multi_processing
+ result = precision_evaluator.apply(
+ log,
+ petri_net,
+ initial_marking,
+ final_marking,
+ variant=precision_evaluator.Variants.ALIGN_ETCONFORMANCE,
+ parameters=parameters,
+ )
+
+ return result
+
+
+def generalization_tbr(
+ log: Union[EventLog, pd.DataFrame],
+ petri_net: PetriNet,
+ initial_marking: Marking,
+ final_marking: Marking,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> float:
+ """
+ Compute the generalization of the model against the event log.
+ The approach is described in the paper:
+
+ 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.
+
+ :param log: Event log.
+ :param petri_net: Petri net.
+ :param initial_marking: Initial marking.
+ :param final_marking: Final marking.
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :return: The generalization value.
+ :rtype: ``float``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ generalization_tbr = pm4py.generalization_tbr(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.evaluation.generalization import (
+ algorithm as generalization_evaluator,
+ )
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ result = generalization_evaluator.apply(
+ log,
+ petri_net,
+ initial_marking,
+ final_marking,
+ variant=generalization_evaluator.Variants.GENERALIZATION_TOKEN,
+ parameters=parameters,
+ )
+
+ return result
+
+
+def replay_prefix_tbr(
+ prefix: List[str],
+ net: PetriNet,
+ im: Marking,
+ fm: Marking,
+ activity_key: str = "concept:name",
+) -> Marking:
+ """
+ Replay a prefix (list of activities) on a given accepting Petri net using Token-Based Replay.
+
+ :param prefix: List of activities representing the prefix.
+ :param net: Petri net.
+ :param im: Initial marking.
+ :param fm: Final marking.
+ :param activity_key: Attribute to be used as the activity key (default is "concept:name").
+ :return: The marking reached after replaying the prefix.
+ :rtype: ``Marking``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
+ marking = pm4py.replay_prefix_tbr(
+ ['register request', 'check ticket'],
+ net,
+ im,
+ fm,
+ activity_key='concept:name'
+ )
+
+ """
+ purpose_log = EventLog()
+ trace = Trace()
+ for act in prefix:
+ trace.append(Event({activity_key: act}))
+ purpose_log.append(trace)
+
+ from pm4py.algo.conformance.tokenreplay.variants import token_replay
+
+ parameters_tr = {
+ token_replay.Parameters.CONSIDER_REMAINING_IN_FITNESS: False,
+ token_replay.Parameters.TRY_TO_REACH_FINAL_MARKING_THROUGH_HIDDEN: False,
+ token_replay.Parameters.STOP_IMMEDIATELY_UNFIT: True,
+ token_replay.Parameters.WALK_THROUGH_HIDDEN_TRANS: True,
+ token_replay.Parameters.ACTIVITY_KEY: activity_key,
+ }
+ res = token_replay.apply(
+ purpose_log, net, im, fm, parameters=parameters_tr
+ )[0]
+ return res["reached_marking"]
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="Conformance checking using footprints will not be exposed in a future release.",
+)
+def __convert_to_fp(*args) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
+ """
+ Internal method to convert the provided event log or process model arguments
+ to footprints using footprints discovery.
+
+ :param args: Event log or process model.
+ :return: Footprints representation.
+ :rtype: ``Union[List[Dict[str, Any]], Dict[str, Any]]``
+
+ Note:
+ This is an internal method and is deprecated.
+
+ """
+ import pm4py
+
+ while isinstance(args, tuple):
+ if len(args) == 1:
+ args = args[0]
+ else:
+ fp = pm4py.discover_footprints(*args)
+ return fp
+ if isinstance(args, list) or isinstance(args, dict):
+ return args
+ fp = pm4py.discover_footprints(args)
+ return fp
+
+
+def conformance_diagnostics_footprints(
+ *args,
+) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
+ """
+ Provide conformance checking diagnostics using footprints.
+
+ :param args: Arguments where the first is an event log (or its footprints) and the others represent the process model (or its footprints).
+ :return: Conformance diagnostics based on footprints.
+ :rtype: ``Union[List[Dict[str, Any]], Dict[str, Any]]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ footprints_diagnostics = pm4py.conformance_diagnostics_footprints(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ fp1 = __convert_to_fp(args[0])
+ fp2 = __convert_to_fp(args[1:])
+ from pm4py.algo.conformance.footprints import (
+ algorithm as footprints_conformance,
+ )
+
+ if isinstance(fp1, list):
+ result = footprints_conformance.apply(
+ fp1, fp2, variant=footprints_conformance.Variants.TRACE_EXTENSIVE
+ )
+ else:
+ result = footprints_conformance.apply(
+ fp1, fp2, variant=footprints_conformance.Variants.LOG_EXTENSIVE
+ )
+
+ return result
+
+
+def fitness_footprints(*args) -> Dict[str, float]:
+ """
+ Calculate fitness using footprints.
+ The output is a dictionary containing two keys:
+
+ - **perc_fit_traces**: Percentage of fit traces (over the log).
+ - **log_fitness**: The fitness value over the log.
+
+ :param args: Arguments where the first is an event log (or its footprints) and the others represent the process model (or its footprints).
+ :return: A dictionary containing fitness metrics based on footprints.
+ :rtype: ``Dict[str, float]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ fitness_fp = pm4py.fitness_footprints(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ fp_conf = conformance_diagnostics_footprints(*args)
+ fp1 = __convert_to_fp(args[0])
+ fp2 = __convert_to_fp(args[1:])
+ from pm4py.algo.conformance.footprints.util import evaluation
+
+ result = evaluation.fp_fitness(fp1, fp2, fp_conf)
+
+ return result
+
+
+def precision_footprints(*args) -> float:
+ """
+ Calculate precision using footprints.
+
+ :param args: Arguments where the first is an event log (or its footprints) and the others represent the process model (or its footprints).
+ :return: The precision value based on footprints.
+ :rtype: ``float``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ precision_fp = pm4py.precision_footprints(
+ dataframe,
+ net,
+ im,
+ fm,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ fp1 = __convert_to_fp(args[0])
+ fp2 = __convert_to_fp(args[1:])
+ from pm4py.algo.conformance.footprints.util import evaluation
+
+ result = evaluation.fp_precision(fp1, fp2)
+
+ return result
+
+
+@deprecation.deprecated(
+ removed_in="2.3.0",
+ deprecated_in="3.0.0",
+ details="This method will be removed in a future release.",
+)
+def __check_is_fit_process_tree(trace, tree) -> bool:
+ """
+ Check if a trace object fits a process tree model.
+
+ :param trace: Trace.
+ :param tree: Process tree.
+ :return: True if the trace fits the process tree, False otherwise.
+ :rtype: ``bool``
+
+ Note:
+ This is an internal method and is deprecated.
+
+ """
+ __event_log_deprecation_warning(trace)
+
+ from pm4py.discovery import discover_footprints
+
+ log = EventLog()
+ log.append(trace)
+ fp_tree = discover_footprints(tree)
+ fp_log = discover_footprints(log)
+ fp_conf_res = conformance_diagnostics_footprints(fp_log, fp_tree)[0]
+ # CHECK 1) If footprints indicate non-conformance, return False
+ if not fp_conf_res["is_footprints_fit"]:
+ return False
+ else:
+ from pm4py.convert import convert_to_petri_net
+
+ net, im, fm = convert_to_petri_net(tree)
+ tbr_conf_res = conformance_diagnostics_token_based_replay(
+ log, net, im, fm, return_diagnostics_dataframe=False
+ )[0]
+ # CHECK 2) If TBR indicates fit, return True
+ if tbr_conf_res["trace_is_fit"]:
+ return True
+ else:
+ # CHECK 3) Use alignments for definitive fit assessment
+ align_conf_res = conformance_diagnostics_alignments(
+ log, tree, return_diagnostics_dataframe=False
+ )[0]
+ return align_conf_res["fitness"] == 1.0
+
+
+@deprecation.deprecated(
+ removed_in="2.3.0",
+ deprecated_in="3.0.0",
+ details="This method will be removed in a future release.",
+)
+def __check_is_fit_petri_net(
+ trace,
+ net: PetriNet,
+ im: Marking,
+ fm: Marking,
+ activity_key=xes_constants.DEFAULT_NAME_KEY,
+) -> bool:
+ """
+ Check if a trace object fits a Petri net model.
+
+ :param trace: Trace.
+ :param net: Petri net.
+ :param im: Initial marking.
+ :param fm: Final marking.
+ :param activity_key: Attribute to be used as the activity key (default is defined in `xes_constants.DEFAULT_NAME_KEY`).
+ :return: True if the trace fits the Petri net, False otherwise.
+ :rtype: ``bool``
+
+ Note:
+ This is an internal method and is deprecated.
+
+ """
+ __event_log_deprecation_warning(trace)
+
+ # Avoid checking footprints on Petri net (they are too slow)
+ activities_model = set(
+ trans.label for trans in net.transitions if trans.label is not None
+ )
+ activities_trace = set([x[activity_key] for x in trace])
+ diff = activities_trace.difference(activities_model)
+ if diff:
+ # CHECK 1) If there are activities in the trace not present in the
+ # model, return False
+ return False
+ else:
+ log = EventLog()
+ log.append(trace)
+ tbr_conf_res = conformance_diagnostics_token_based_replay(
+ log, net, im, fm, return_diagnostics_dataframe=False
+ )[0]
+ # CHECK 2) If TBR indicates fit, return True
+ if tbr_conf_res["trace_is_fit"]:
+ return True
+ else:
+ # CHECK 3) Use alignments for definitive fit assessment
+ align_conf_res = conformance_diagnostics_alignments(
+ log, net, im, fm, return_diagnostics_dataframe=False
+ )[0]
+ return align_conf_res["fitness"] == 1.0
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="This method will be removed in a future release.",
+)
+def check_is_fitting(
+ *args, activity_key=xes_constants.DEFAULT_NAME_KEY
+) -> bool:
+ """
+ Check if a trace object fits a process model.
+
+ :param args: Arguments where the first is a trace object and the others represent the process model (process tree, Petri net, BPMN).
+ :param activity_key: Attribute to be used as the activity key (default is defined in `xes_constants.DEFAULT_NAME_KEY`).
+ :return: True if the trace fits the process model, False otherwise.
+ :rtype: ``bool``
+
+ Note:
+ This is an internal method and is deprecated.
+
+ """
+ from pm4py.util import variants_util
+ from pm4py.convert import convert_to_process_tree, convert_to_petri_net
+
+ trace = args[0]
+ model = args[1:]
+
+ try:
+ model = convert_to_process_tree(*model)
+ except BaseException:
+ # If the model cannot be expressed as a process tree, attempt Petri net
+ # conversion
+ model = convert_to_petri_net(*model)
+
+ if not isinstance(trace, Trace):
+ activities = variants_util.get_activities_from_variant(trace)
+ trace = Trace()
+ for act in activities:
+ trace.append(Event({activity_key: act}))
+
+ if isinstance(model, ProcessTree):
+ return __check_is_fit_process_tree(trace, model)
+ elif isinstance(model, tuple) and isinstance(model[0], PetriNet):
+ return __check_is_fit_petri_net(
+ trace, model[0], model[1], model[2], activity_key=activity_key
+ )
+
+
+def conformance_temporal_profile(
+ log: Union[EventLog, pd.DataFrame],
+ temporal_profile: Dict[Tuple[str, str], Tuple[float, float]],
+ zeta: float = 1.0,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
+) -> List[List[Tuple[float, float, float, float]]]:
+ """
+ Perform conformance checking on the provided log using the provided temporal profile.
+ The result is a list of time-based deviations for every case.
+
+ For example, consider a log with a single case:
+
+ - A (timestamp: 2000-01)
+ - B (timestamp: 2002-01)
+
+ Given the temporal profile::
+
+ {
+ ('A', 'B'): (1.5, 0.5), # (mean, std)
+ ('A', 'C'): (5.0, 0.0),
+ ('A', 'D'): (2.0, 0.0)
+ }
+
+ 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.
+
+ :param log: Log object.
+ :param temporal_profile: Temporal profile. For example, if the log has two cases:
+
+ - Case 1: A (timestamp: 1980-01), B (timestamp: 1980-03), C (timestamp: 1980-06)
+ - Case 2: A (timestamp: 1990-01), B (timestamp: 1990-02), D (timestamp: 1990-03)
+
+ The temporal profile might look like::
+
+ {
+ ('A', 'B'): (1.5, 0.5), # (mean, std)
+ ('A', 'C'): (5.0, 0.0),
+ ('A', 'D'): (2.0, 0.0)
+ }
+
+ :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.
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
+ :return: A list containing lists of tuples representing time-based deviations for each case.
+ :rtype: ``List[List[Tuple[float, float, float, float]]]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ temporal_profile = pm4py.discover_temporal_profile(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ conformance_temporal_profile = pm4py.conformance_temporal_profile(
+ dataframe,
+ temporal_profile,
+ zeta=1,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ properties["zeta"] = zeta
+
+ from pm4py.algo.conformance.temporal_profile import (
+ algorithm as temporal_profile_conformance,
+ )
+
+ result = temporal_profile_conformance.apply(
+ log, temporal_profile, parameters=properties
+ )
+
+ if return_diagnostics_dataframe:
+ return temporal_profile_conformance.get_diagnostics_dataframe(
+ log, result, parameters=properties
+ )
+
+ return result
+
+
+def conformance_declare(
+ log: Union[EventLog, pd.DataFrame],
+ declare_model: Dict[str, Dict[Any, Dict[str, int]]],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
+) -> List[Dict[str, Any]]:
+ """
+ Apply conformance checking against a DECLARE model.
+
+ Reference paper:
+ 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.
+
+ :param log: Event log.
+ :param declare_model: DECLARE model represented as a nested dictionary.
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
+ :return: A list of dictionaries containing diagnostics for each trace.
+ :rtype: ``List[Dict[str, Any]]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ log = pm4py.read_xes("C:/receipt.xes")
+ declare_model = pm4py.discover_declare(log)
+ conf_result = pm4py.conformance_declare(
+ log,
+ declare_model,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if return_diagnostics_dataframe:
+ from pm4py.convert import convert_to_event_log
+
+ log = convert_to_event_log(log, case_id_key=case_id_key)
+ case_id_key = None
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.conformance.declare import algorithm as declare_conformance
+
+ result = declare_conformance.apply(
+ log, declare_model, parameters=properties
+ )
+
+ if return_diagnostics_dataframe:
+ return declare_conformance.get_diagnostics_dataframe(
+ log, result, parameters=properties
+ )
+
+ return result
+
+
+def conformance_log_skeleton(
+ log: Union[EventLog, pd.DataFrame],
+ log_skeleton: Dict[str, Any],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
+) -> List[Set[Any]]:
+ """
+ Perform conformance checking using the log skeleton.
+
+ Reference paper:
+ Verbeek, H. M. W., and R. Medeiros de Carvalho. "Log skeletons: A classification approach to process discovery." arXiv preprint arXiv:1806.08247 (2018).
+
+ A log skeleton is a declarative model consisting of six different constraints:
+
+ - **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'.
+ - **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'.
+ - **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'.
+ - **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'.
+ - **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'.
+ - **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'.
+
+ :param log: Log object.
+ :param log_skeleton: Log skeleton object, expressed as dictionaries of the six constraints along with the discovered rules.
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
+ :return: A list of sets containing deviations for each case.
+ :rtype: ``List[Set[Any]]``
+
+ Example:
+ .. code-block:: python
+
+ import pm4py
+
+ log_skeleton = pm4py.discover_log_skeleton(
+ dataframe,
+ noise_threshold=0.1,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ conformance_lsk = pm4py.conformance_log_skeleton(
+ dataframe,
+ log_skeleton,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if return_diagnostics_dataframe:
+ from pm4py.convert import convert_to_event_log
+
+ log = convert_to_event_log(log, case_id_key=case_id_key)
+ case_id_key = None
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.conformance.log_skeleton import (
+ algorithm as log_skeleton_conformance,
+ )
+
+ result = log_skeleton_conformance.apply(
+ log, log_skeleton, parameters=properties
+ )
+
+ if return_diagnostics_dataframe:
+ return log_skeleton_conformance.get_diagnostics_dataframe(
+ log, result, parameters=properties
+ )
+
+ return result
+
+
+def conformance_ocdfg(
+ ocel: Union[OCEL, Dict[str, Any]],
+ model: Dict[str, Any],
+ variant=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Dict[str, Any]:
+ """
+ Performs OC-DFG-based conformance checking between an object-centric event log (or OC-DFG) and a normative OC-DFG.
+
+ An object-centric directly-follows graph is expressed as a dictionary containing the following properties:
+
+ - activities: complete set of activities derived from the object-centric event log
+ - object_types: complete set of object types derived from the object-centric event log
+ - edges: dictionary connecting each object type to a set of directly-followed arcs between activities
+ - activities_indep: dictionary linking each activity, regardless of the object type
+ - activities_ot: dictionary linking each object type to another dictionary
+ - start_activities: dictionary linking each object type to start activities
+ - end_activities: dictionary linking each object type to end activities
+
+ Published in: https://publications.rwth-aachen.de/record/1014107
+
+ :param ocel: Object-centric event log or OC-DFG representing the real behavior.
+ :param model: Normative OC-DFG obtained from discovery.
+ :param variant: Variant of the OC-DFG conformance algorithm to use (default: graph comparison).
+ :param parameters: Optional variant-specific parameters.
+ :return: Dictionary containing conformance diagnostics.
+ :rtype: ``Dict[str, Any]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ diagnostics = pm4py.conformance_ocdfg(ocel, ocdfg_model)
+ """
+ from pm4py.algo.conformance.ocel.ocdfg import algorithm as ocdfg_conformance
+
+ if variant is None:
+ variant = ocdfg_conformance.Variants.GRAPH_COMPARISON
+
+ return ocdfg_conformance.apply(ocel, model, variant=variant, parameters=parameters)
+
+
+def conformance_otg(
+ ocel: Union[OCEL, Tuple[Set[str], Dict[Tuple[str, str, str], int]]],
+ model: Tuple[Set[str], Dict[Tuple[str, str, str], int]],
+ variant=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Dict[str, Any]:
+ """
+ Performs OTG-based conformance checking between an object-centric event log (or OTG) and a normative OTG.
+
+ An OTG summarizes how object types are related across different interaction graphs extracted from the OCEL.
+ Specifically, an OTG is a tuple containing:
+
+ - The set of object types
+ - The edges along with the frequency, where each edge is (object_type1, relationship, object_type2).
+
+ Relationship can be:
+
+ * object_interaction (objects related in some event)
+ * object_descendants (lifecycle of the first event starts before the other object)
+ * object_inheritance (lifecycle of the first object ends exactly when the second one starts)
+ * object_cobirth (objects start their lifecycle in the same event)
+ * object_codeath (objects end their lifecycle in the sae event)
+
+ Published in: https://publications.rwth-aachen.de/record/1014107
+
+ :param ocel: Object-centric event log or OTG capturing the real behavior.
+ :param model: Normative OTG, typically discovered from a reference log.
+ :param variant: Variant of the OTG conformance algorithm to use (default: graph comparison).
+ :param parameters: Optional variant-specific parameters.
+ :return: Dictionary containing OTG conformance diagnostics.
+ :rtype: ``Dict[str, Any]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ diagnostics = pm4py.conformance_otg(ocel, otg_model)
+ """
+ from pm4py.algo.conformance.ocel.otg import algorithm as otg_conformance
+
+ if variant is None:
+ variant = otg_conformance.Variants.GRAPH_COMPARISON
+
+ return otg_conformance.apply(ocel, model, variant=variant, parameters=parameters)
+
+
+def conformance_etot(
+ ocel: Union[
+ OCEL,
+ Tuple[
+ Set[str],
+ Set[str],
+ Set[Tuple[str, str]],
+ Dict[Tuple[str, str], int],
+ ],
+ ],
+ model: Tuple[
+ Set[str],
+ Set[str],
+ Set[Tuple[str, str]],
+ Dict[Tuple[str, str], int],
+ ],
+ variant=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Dict[str, Any]:
+ """
+ Performs ET-OT-based conformance checking between an object-centric event log (or ET-OT graph) and a normative ET-OT graph.
+
+ The ET-OT graph captures the relationships between event types and object types along with their frequencies.
+ Specifically, an ET-OT graph is a tuple consisting of:
+
+ - Set of activities
+ - Set of object types
+ - Set of relationships, where an edge (a, ot) indicates that events of type a are associated with objects of type ot
+ - A dictionary associating each relationship to a weight (frequency)
+
+ Published in: https://publications.rwth-aachen.de/record/1014107
+
+ :param ocel: Object-centric event log or ET-OT graph capturing the real behavior.
+ :param model: Normative ET-OT graph, typically discovered from a reference log.
+ :param variant: Variant of the ET-OT conformance algorithm to use (default: graph comparison).
+ :param parameters: Optional variant-specific parameters.
+ :return: Dictionary containing ET-OT conformance diagnostics.
+ :rtype: ``Dict[str, Any]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ diagnostics = pm4py.conformance_etot(ocel, etot_model)
+ """
+ from pm4py.algo.conformance.ocel.etot import algorithm as etot_conformance
+
+ if variant is None:
+ variant = etot_conformance.Variants.GRAPH_COMPARISON
+
+ return etot_conformance.apply(ocel, model, variant=variant, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/connectors.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/connectors.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac8715dacb898d190ff5de56447789905e1049e9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/connectors.py
@@ -0,0 +1,661 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Optional
+import pandas as pd
+from pm4py.objects.ocel.obj import OCEL
+
+
+def extract_log_outlook_mails() -> pd.DataFrame:
+ """
+ Extracts the history of conversations from the local instance of Microsoft Outlook
+ running on the current computer.
+
+ Columns:
+
+ - **CASE ID (case:concept:name)**: Identifier of the conversation.
+ - **ACTIVITY (concept:name)**: Activity performed in the current item (e.g., send e-mail, receive e-mail, refuse meeting).
+ - **TIMESTAMP (time:timestamp)**: Timestamp of creation of the item in Outlook.
+ - **RESOURCE (org:resource)**: Sender of the current item.
+
+ See Also:
+
+ * [MailItem Properties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.mailitem?redirectedfrom=MSDN&view=outlook-pia#properties_)
+ * [OlObjectClass Enumeration](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.olobjectclass?view=outlook-pia)
+
+ :rtype: ``pd.DataFrame``
+
+ Example::
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_outlook_mails()
+
+ """
+ from pm4py.algo.connectors.variants import outlook_mail_extractor
+
+ return outlook_mail_extractor.apply()
+
+
+def extract_log_outlook_calendar(
+ email_user: Optional[str] = None, calendar_id: int = 9
+) -> pd.DataFrame:
+ """
+ Extracts the history of calendar events (creation, update, start, end)
+ into a Pandas DataFrame from the local Outlook instance running on the current computer.
+
+ Columns:
+
+ - **CASE ID (case:concept:name)**: Identifier of the meeting.
+ - **ACTIVITY (concept:name)**: One of the following activities: Meeting Created, Last Change of Meeting, Meeting Started, Meeting Completed.
+ - **TIMESTAMP (time:timestamp)**: Timestamp of the event.
+ - **case:subject**: Subject of the meeting.
+
+ :param email_user: (optional) E-mail address from which the (shared) calendar should be extracted.
+ :param calendar_id: Identifier of the calendar for the given user (default: 9).
+
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ # Extract using default parameters
+ dataframe = pm4py.connectors.extract_log_outlook_calendar()
+
+ # Extract using a specific email user
+ dataframe = pm4py.connectors.extract_log_outlook_calendar("vacation-calendar@workplace.eu")
+ """
+ from pm4py.algo.connectors.variants import outlook_calendar
+
+ parameters = {}
+ parameters[outlook_calendar.Parameters.EMAIL_USER] = email_user
+ parameters[outlook_calendar.Parameters.CALENDAR_ID] = calendar_id
+ return outlook_calendar.apply(parameters=parameters)
+
+
+def extract_log_windows_events() -> pd.DataFrame:
+ """
+ Extracts a process mining DataFrame from all events recorded in the Windows registry.
+
+ Columns:
+
+ - **CASE ID (case:concept:name)**: Name of the computer emitting the events.
+ - **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))
+ - **TIMESTAMP (time:timestamp)**: Timestamp of event generation.
+ - **RESOURCE (org:resource)**: Username involved in the event.
+
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_windows_events()
+ """
+ from pm4py.algo.connectors.variants import windows_events
+
+ return windows_events.apply()
+
+
+def extract_log_chrome_history(
+ history_db_path: Optional[str] = None,
+) -> pd.DataFrame:
+ """
+ Extracts a DataFrame containing the navigation history of Google Chrome.
+ Please ensure that Google Chrome history is closed when extracting.
+
+ Columns:
+
+ - **CASE ID (case:concept:name)**: Identifier of the extracted profile.
+ - **ACTIVITY (concept:name)**: Complete path of the website, excluding GET arguments.
+ - **TIMESTAMP (time:timestamp)**: Timestamp of the visit.
+
+ :param history_db_path: Path to the Google Chrome history database (default: location of the Windows folder).
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_chrome_history()
+ """
+ from pm4py.algo.connectors.variants import chrome_history
+
+ parameters = {}
+ if history_db_path is not None:
+ parameters[chrome_history.Parameters.HISTORY_DB_PATH] = history_db_path
+ return chrome_history.apply(parameters=parameters)
+
+
+def extract_log_firefox_history(
+ history_db_path: Optional[str] = None,
+) -> pd.DataFrame:
+ """
+ Extracts a DataFrame containing the navigation history of Mozilla Firefox.
+ Please ensure that Mozilla Firefox history is closed when extracting.
+
+ Columns:
+
+ - **CASE ID (case:concept:name)**: Identifier of the extracted profile.
+ - **ACTIVITY (concept:name)**: Complete path of the website, excluding GET arguments.
+ - **TIMESTAMP (time:timestamp)**: Timestamp of the visit.
+
+ :param history_db_path: Path to the Mozilla Firefox history database (default: location of the Windows folder).
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_firefox_history()
+ """
+ from pm4py.algo.connectors.variants import firefox_history
+
+ parameters = {}
+ if history_db_path is not None:
+ parameters[firefox_history.Parameters.HISTORY_DB_PATH] = (
+ history_db_path
+ )
+ return firefox_history.apply(parameters=parameters)
+
+
+def extract_log_github(
+ owner: str = "pm4py",
+ repo: str = "pm4py-core",
+ auth_token: Optional[str] = None,
+) -> pd.DataFrame:
+ """
+ Extracts a DataFrame containing the history of issues from a GitHub repository.
+ Due to API rate limits for public and registered users, only a subset of events may be returned.
+
+ :param owner: Owner of the repository (e.g., pm4py).
+ :param repo: Name of the repository (e.g., pm4py-core).
+ :param auth_token: Authorization token.
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_github(owner='pm4py', repo='pm4py-core')
+ """
+ from pm4py.algo.connectors.variants import github_repo
+
+ parameters = {}
+ parameters[github_repo.Parameters.OWNER] = owner
+ parameters[github_repo.Parameters.REPOSITORY] = repo
+ parameters[github_repo.Parameters.AUTH_TOKEN] = auth_token
+ return github_repo.apply(parameters)
+
+
+def extract_log_camunda_workflow(connection_string: str) -> pd.DataFrame:
+ """
+ Extracts a DataFrame from the Camunda workflow system. In addition to traditional columns,
+ the process ID of the process in Camunda is included.
+
+ :param connection_string: ODBC connection string to the Camunda database.
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_camunda_workflow(
+ 'Driver={PostgreSQL Unicode(x64)};SERVER=127.0.0.3;DATABASE=process-engine;UID=xx;PWD=yy'
+ )
+ """
+ from pm4py.algo.connectors.variants import camunda_workflow
+
+ parameters = {}
+ parameters[camunda_workflow.Parameters.CONNECTION_STRING] = (
+ connection_string
+ )
+ return camunda_workflow.apply(None, parameters=parameters)
+
+
+def extract_log_sap_o2c(
+ connection_string: str, prefix: str = ""
+) -> pd.DataFrame:
+ """
+ Extracts a DataFrame for the SAP Order-to-Cash (O2C) process.
+
+ :param connection_string: ODBC connection string to the SAP database.
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_sap_o2c(
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
+ )
+ """
+ from pm4py.algo.connectors.variants import sap_o2c
+
+ parameters = {}
+ parameters[sap_o2c.Parameters.CONNECTION_STRING] = connection_string
+ parameters[sap_o2c.Parameters.PREFIX] = prefix
+ return sap_o2c.apply(None, parameters=parameters)
+
+
+def extract_log_sap_accounting(
+ connection_string: str, prefix: str = ""
+) -> pd.DataFrame:
+ """
+ Extracts a DataFrame for the SAP Accounting process.
+
+ :param connection_string: ODBC connection string to the SAP database.
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_sap_accounting(
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
+ )
+ """
+ from pm4py.algo.connectors.variants import sap_accounting
+
+ parameters = {}
+ parameters[sap_accounting.Parameters.CONNECTION_STRING] = connection_string
+ parameters[sap_accounting.Parameters.PREFIX] = prefix
+ return sap_accounting.apply(None, parameters=parameters)
+
+
+def extract_ocel_outlook_mails() -> OCEL:
+ """
+ Extracts the history of conversations from the local instance of Microsoft Outlook
+ running on the current computer as an object-centric event log.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: Activity performed in the current item (e.g., send e-mail, receive e-mail, refuse meeting).
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of creation of the item in Outlook.
+
+ Object Types:
+
+ - **org:resource**: Sender of the mail.
+ - **recipients**: List of recipients of the mail.
+ - **topic**: Topic of the discussion.
+
+ See Also:
+
+ * [MailItem Properties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.mailitem?redirectedfrom=MSDN&view=outlook-pia#properties_)
+ * [OlObjectClass Enumeration](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.olobjectclass?view=outlook-pia)
+
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_outlook_mails()
+
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_outlook_mails()
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": ["org:resource", "recipients", "topic"]},
+ )
+
+
+def extract_ocel_outlook_calendar(
+ email_user: Optional[str] = None, calendar_id: int = 9
+) -> OCEL:
+ """
+ Extracts the history of calendar events (creation, update, start, end)
+ as an object-centric event log from the local Outlook instance running on the current computer.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: One of the following activities: Meeting Created, Last Change of Meeting, Meeting Started, Meeting Completed.
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the event.
+
+ Object Types:
+
+ - **case:concept:name**: Identifier of the meeting.
+ - **case:subject**: Subject of the meeting.
+
+ :param email_user: (optional) E-mail address from which the (shared) calendar should be extracted.
+ :param calendar_id: Identifier of the calendar for the given user (default: 9).
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ # Extract using default parameters
+ ocel = pm4py.connectors.extract_ocel_outlook_calendar()
+
+ # Extract using a specific email user
+ ocel = pm4py.connectors.extract_ocel_outlook_calendar("vacation-calendar@workplace.eu")
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_outlook_calendar(
+ email_user, calendar_id
+ )
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "case:subject"]},
+ )
+
+
+def extract_ocel_windows_events() -> OCEL:
+ """
+ Extracts an object-centric event log from all events recorded in the Windows registry.
+
+ Columns:
+
+ - **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))
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of event generation.
+
+ Object Types:
+
+ - **categoryString**: Translation of the subcategory. The translation is source-specific.
+ - **computerName**: Name of the computer that generated the event.
+ - **eventIdentifier**: Identifier of the event, specific to the source that generated the event log entry.
+ - **eventType**: Event type classification (1=Error; 2=Warning; 3=Information; 4=Security Audit Success; 5=Security Audit Failure).
+ - **sourceName**: Name of the source (application, service, driver, or subsystem) that generated the entry.
+ - **user**: Username of the logged-on user when the event occurred. If the username cannot be determined, this will be NULL.
+
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_windows_events()
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_windows_events()
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types="case:concept:name",
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": [
+ "categoryString",
+ "computerName",
+ "eventIdentifier",
+ "eventType",
+ "sourceName",
+ "user",
+ ]},
+ )
+
+
+def extract_ocel_chrome_history(history_db_path: Optional[str] = None) -> OCEL:
+ """
+ Extracts an object-centric event log containing the navigation history of Google Chrome.
+ Please ensure that Google Chrome history is closed when extracting.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: Complete path of the website, excluding GET arguments.
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the visit.
+
+ Object Types:
+
+ - **case:concept:name**: Profile of Chrome used to visit the site.
+ - **complete_url**: Complete URL of the website.
+ - **url_wo_parameters**: Complete URL excluding the part after '?'.
+ - **domain**: Domain of the visited website.
+
+ :param history_db_path: Path to the Google Chrome history database (default: location of the Windows folder).
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_chrome_history()
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_chrome_history(history_db_path)
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": [
+ "case:concept:name",
+ "complete_url",
+ "url_wo_parameters",
+ "domain",
+ ]},
+ )
+
+
+def extract_ocel_firefox_history(
+ history_db_path: Optional[str] = None,
+) -> OCEL:
+ """
+ Extracts an object-centric event log containing the navigation history of Mozilla Firefox.
+ Please ensure that Mozilla Firefox history is closed when extracting.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: Complete path of the website, excluding GET arguments.
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the visit.
+
+ Object Types:
+
+ - **case:concept:name**: Profile of Firefox used to visit the site.
+ - **complete_url**: Complete URL of the website.
+ - **url_wo_parameters**: Complete URL excluding the part after '?'.
+ - **domain**: Domain of the visited website.
+
+ :param history_db_path: Path to the Mozilla Firefox history database (default: location of the Windows folder).
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_firefox_history()
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_firefox_history(history_db_path)
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": [
+ "case:concept:name",
+ "complete_url",
+ "url_wo_parameters",
+ "domain",
+ ]},
+ )
+
+
+def extract_ocel_github(
+ owner: str = "pm4py",
+ repo: str = "pm4py-core",
+ auth_token: Optional[str] = None,
+) -> OCEL:
+ """
+ Extracts an object-centric event log containing the history of issues from a GitHub repository.
+ Due to API rate limits for public and registered users, only a subset of events may be returned.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: The event type (e.g., created, commented, closed, subscribed).
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the event execution.
+
+ Object Types:
+
+ - **case:concept:name**: URL of the events related to the issue.
+ - **org:resource**: Involved resource.
+ - **case:repo**: Repository in which the issue was created.
+
+ :param owner: Owner of the repository (e.g., pm4py).
+ :param repo: Name of the repository (e.g., pm4py-core).
+ :param auth_token: Authorization token.
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_github(owner='pm4py', repo='pm4py-core')
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_github(owner, repo, auth_token)
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "org:resource", "case:repo"]},
+ )
+
+
+def extract_ocel_camunda_workflow(connection_string: str) -> OCEL:
+ """
+ Extracts an object-centric event log from the Camunda workflow system.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: Activity performed within Camunda.
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the activity execution.
+
+ Object Types:
+
+ - **case:concept:name**: Identifier of the case.
+ - **processID**: Process ID within Camunda.
+ - **org:resource**: Resource involved in the activity.
+
+ :param connection_string: ODBC connection string to the Camunda database.
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_camunda_workflow(
+ 'Driver={PostgreSQL Unicode(x64)};SERVER=127.0.0.3;DATABASE=process-engine;UID=xx;PWD=yy'
+ )
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_camunda_workflow(
+ connection_string
+ )
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "processID", "org:resource"]},
+ )
+
+
+def extract_ocel_sap_o2c(connection_string: str, prefix: str = "") -> OCEL:
+ """
+ Extracts an object-centric event log for the SAP Order-to-Cash (O2C) process.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: Activity performed in the O2C process.
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the activity execution.
+
+ Object Types:
+
+ - **case:concept:name**: Identifier of the case.
+ - **org:resource**: Resource involved in the activity.
+
+ :param connection_string: ODBC connection string to the SAP database.
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_sap_o2c(
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
+ )
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_sap_o2c(
+ connection_string, prefix=prefix
+ )
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "org:resource"]},
+ )
+
+
+def extract_ocel_sap_accounting(
+ connection_string: str, prefix: str = ""
+) -> OCEL:
+ """
+ Extracts an object-centric event log for the SAP Accounting process.
+
+ Columns:
+
+ - **ACTIVITY (ocel:activity)**: Activity performed in the Accounting process.
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the activity execution.
+
+ Object Types:
+
+ - **case:concept:name**: Identifier of the case.
+ - **org:resource**: Resource involved in the activity.
+
+ :param connection_string: ODBC connection string to the SAP database.
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.connectors.extract_ocel_sap_accounting(
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
+ )
+ """
+ import pm4py
+
+ dataframe = pm4py.connectors.extract_log_sap_accounting(
+ connection_string, prefix=prefix
+ )
+ return pm4py.convert_log_to_ocel(
+ dataframe,
+ object_types=["case:concept:name"],
+ timestamp_column="time:timestamp",
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "org:resource"]},
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/convert.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c9152caa4b2e58675a5c7715fe56f3ee9fd87e0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/convert.py
@@ -0,0 +1,713 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+The ``pm4py.convert`` module contains the cross-conversions implemented in ``pm4py``
+"""
+
+from typing import Union, Tuple, Optional, Collection, List, Any, Dict
+
+import pandas as pd
+from copy import deepcopy
+
+import pm4py
+from pm4py.objects.bpmn.obj import BPMN
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.powl.obj import POWL
+from pm4py.objects.heuristics_net.obj import HeuristicsNet
+from pm4py.objects.genetic_matrix.obj import GeneticMatrix
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.objects.petri_net.obj import Marking
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.objects.petri_net.obj import PetriNet
+from pm4py.util import constants, nx_utils
+from pm4py.utils import get_properties, __event_log_deprecation_warning
+from pm4py.objects.transition_system.obj import TransitionSystem
+from pm4py.util.pandas_utils import (
+ check_is_pandas_dataframe,
+ check_pandas_dataframe_columns,
+)
+import networkx as nx
+
+
+def convert_to_event_log(
+ obj: Union[pd.DataFrame, EventStream],
+ case_id_key: str = "case:concept:name",
+ **kwargs,
+) -> EventLog:
+ """
+ Converts a DataFrame or EventStream object to an event log object.
+
+ :param obj: The DataFrame or EventStream object to convert.
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "case:concept:name".
+ :param kwargs: Additional keyword arguments to pass to the converter.
+ :return: An ``EventLog`` object.
+
+ .. code-block:: python3
+
+ import pandas as pd
+ import pm4py
+
+ dataframe = pm4py.read_csv("tests/input_data/running-example.csv")
+ dataframe = pm4py.format_dataframe(dataframe, case_id_column='case:concept:name', activity_column='concept:name', timestamp_column='time:timestamp')
+ log = pm4py.convert_to_event_log(dataframe)
+ """
+
+ if check_is_pandas_dataframe(obj):
+ check_pandas_dataframe_columns(obj, case_id_key=case_id_key)
+
+ parameters = get_properties(obj, case_id_key=case_id_key)
+ for k, v in kwargs.items():
+ parameters[k] = v
+
+ from pm4py.objects.conversion.log import converter
+
+ log = converter.apply(
+ obj, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+
+ __event_log_deprecation_warning(log)
+
+ return log
+
+
+def convert_to_event_stream(
+ obj: Union[EventLog, pd.DataFrame],
+ case_id_key: str = "case:concept:name",
+ **kwargs,
+) -> EventStream:
+ """
+ Converts a log object or DataFrame to an event stream.
+
+ :param obj: The log object (``EventLog``) or DataFrame to convert.
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "case:concept:name".
+ :param kwargs: Additional keyword arguments to pass to the converter.
+ :return: An ``EventStream`` object.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+ event_stream = pm4py.convert_to_event_stream(log)
+ """
+ if check_is_pandas_dataframe(obj):
+ check_pandas_dataframe_columns(obj, case_id_key=case_id_key)
+
+ parameters = get_properties(obj, case_id_key=case_id_key)
+ for k, v in kwargs.items():
+ parameters[k] = v
+
+ from pm4py.objects.conversion.log import converter
+
+ stream = converter.apply(
+ obj, variant=converter.Variants.TO_EVENT_STREAM, parameters=parameters
+ )
+
+ __event_log_deprecation_warning(stream)
+
+ return stream
+
+
+def convert_to_dataframe(
+ obj: Union[EventStream, EventLog], **kwargs
+) -> pd.DataFrame:
+ """
+ Converts a log object (``EventStream`` or ``EventLog``) to a Pandas DataFrame.
+
+ :param obj: The log object to convert.
+ :param kwargs: Additional keyword arguments to pass to the converter.
+ :return: A ``pd.DataFrame`` object.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+ dataframe = pm4py.convert_to_dataframe(log)
+ """
+ if check_is_pandas_dataframe(obj):
+ check_pandas_dataframe_columns(obj)
+
+ parameters = get_properties(obj)
+ for k, v in kwargs.items():
+ parameters[k] = v
+
+ from pm4py.objects.conversion.log import converter
+
+ df = converter.apply(
+ obj, variant=converter.Variants.TO_DATA_FRAME, parameters=parameters
+ )
+ return df
+
+
+def convert_to_bpmn(
+ *args: Union[Tuple[PetriNet, Marking, Marking], ProcessTree]
+) -> BPMN:
+ """
+ Converts an object to a BPMN diagram.
+
+ As input, either a Petri net (with corresponding initial and final markings) or a process tree can be provided.
+ A process tree can always be converted into a BPMN model, ensuring the quality of the resulting object.
+ 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).
+
+ :param args:
+ - If converting a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
+ - If converting a process tree: a single ``ProcessTree`` object.
+ :return: A ``BPMN`` object.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ # Import a Petri net from a file
+ net, im, fm = pm4py.read_pnml("tests/input_data/running-example.pnml")
+ bpmn_graph = pm4py.convert_to_bpmn(net, im, fm)
+ """
+ from pm4py.objects.process_tree.obj import ProcessTree
+ from pm4py.objects.bpmn.obj import BPMN
+
+ if isinstance(args[0], BPMN):
+ # the object is already a BPMN
+ return args[0]
+ elif isinstance(args[0], ProcessTree):
+ from pm4py.objects.conversion.process_tree.variants import to_bpmn
+
+ return to_bpmn.apply(args[0])
+ else:
+ # try to convert the object to a Petri net. Then, use the PM4Py PN-to-BPMN converter
+ # to get the BPMN object
+ try:
+ net, im, fm = convert_to_petri_net(*args)
+ from pm4py.objects.conversion.wf_net.variants import to_bpmn
+
+ return to_bpmn.apply(net, im, fm)
+ except BaseException:
+ # don't do nothing and throw the following exception
+ pass
+ # if no conversion is done, then the format of the arguments is unsupported
+ raise Exception("Unsupported conversion of the provided object to BPMN")
+
+
+def convert_to_petri_net(
+ *args: Union[BPMN, ProcessTree, HeuristicsNet, GeneticMatrix, POWL, dict]
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Converts an input model to an (accepting) Petri net.
+
+ The input objects can be a process tree, BPMN model, Heuristic net, GeneticMatrix, POWL model, or a dictionary representing a Directly-Follows Graph (DFG).
+ The output is a tuple containing the Petri net and the initial and final markings.
+ The markings are only returned if they can be reasonably derived from the input model.
+
+ :param args:
+ - If converting from a BPMN, ProcessTree, HeuristicsNet, GeneticMatrix, or POWL: a single object of the respective type.
+ - If converting from a DFG: a dictionary representing the DFG, followed by lists of start and end activities.
+ :return: A tuple of (``PetriNet``, ``Marking``, ``Marking``).
+
+ .. code-block:: python3
+
+ import pm4py
+
+ # Imports a process tree from a PTML file
+ process_tree = pm4py.read_ptml("tests/input_data/running-example.ptml")
+ net, im, fm = pm4py.convert_to_petri_net(process_tree)
+ """
+ if isinstance(args[0], PetriNet):
+ # the object is already a Petri net
+ return args[0], args[1], args[2]
+ elif isinstance(args[0], ProcessTree):
+ if isinstance(args[0], POWL):
+ from pm4py.objects.conversion.powl import converter
+
+ return converter.apply(args[0])
+ from pm4py.objects.conversion.process_tree.variants import to_petri_net
+
+ return to_petri_net.apply(args[0])
+ elif isinstance(args[0], BPMN):
+ from pm4py.objects.conversion.bpmn.variants import to_petri_net
+
+ return to_petri_net.apply(args[0])
+ elif isinstance(args[0], HeuristicsNet):
+ from pm4py.objects.conversion.heuristics_net.variants import (
+ to_petri_net,
+ )
+
+ return to_petri_net.apply(args[0])
+ elif isinstance(args[0], GeneticMatrix):
+ from pm4py.objects.conversion.genetic_matrix.variants import (
+ to_petri_net,
+ )
+
+ return to_petri_net.apply(args[0])
+ elif isinstance(args[0], dict):
+ # DFG
+ from pm4py.objects.conversion.dfg.variants import (
+ to_petri_net_activity_defines_place,
+ )
+
+ return to_petri_net_activity_defines_place.apply(
+ args[0],
+ parameters={
+ to_petri_net_activity_defines_place.Parameters.START_ACTIVITIES: args[1],
+ to_petri_net_activity_defines_place.Parameters.END_ACTIVITIES: args[2],
+ },
+ )
+ # if no conversion is done, then the format of the arguments is unsupported
+ raise Exception(
+ "Unsupported conversion of the provided object to Petri net"
+ )
+
+
+def convert_to_process_tree(
+ *args: Union[Tuple[PetriNet, Marking, Marking], BPMN, ProcessTree, POWL]
+) -> ProcessTree:
+ """
+ Converts an input model to a process tree.
+
+ The input models can be Petri nets (with markings) or BPMN models.
+ For both input types, the conversion is not guaranteed to work and may raise an exception.
+
+ :param args:
+ - If converting from a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
+ - If converting from a BPMN or ProcessTree: a single object of the respective type.
+ :return: A ``ProcessTree`` object.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ # Imports a BPMN file
+ bpmn_graph = pm4py.read_bpmn("tests/input_data/running-example.bpmn")
+ # Converts the BPMN to a process tree (through intermediate conversion to a Petri net)
+ process_tree = pm4py.convert_to_process_tree(bpmn_graph)
+ """
+ from pm4py.objects.process_tree.obj import ProcessTree
+ from pm4py.objects.petri_net.obj import PetriNet
+
+ if isinstance(args[0], POWL):
+ from pm4py.objects.conversion.powl.variants import to_process_tree
+ return to_process_tree.apply(args[0])
+ elif isinstance(args[0], ProcessTree):
+ # the object is already a process tree
+ return args[0]
+
+ if isinstance(args[0], PetriNet):
+ net, im, fm = args[0], args[1], args[2]
+ else:
+ net, im, fm = convert_to_petri_net(*args)
+
+ from pm4py.objects.conversion.wf_net.variants import to_process_tree
+
+ tree = to_process_tree.apply(net, im, fm)
+ if tree is not None:
+ return tree
+
+ raise Exception(
+ "The object represents a model that cannot be represented as a process tree!"
+ )
+
+
+def convert_to_powl(*args: Union[Tuple[PetriNet, Marking, Marking], BPMN, ProcessTree]) -> POWL:
+ """
+ Converts an input model to a POWL model.
+
+ The input models can be Petri nets (with markings) or BPMN models or process trees.
+ For both input types, the conversion is not guaranteed to work and may raise an exception.
+
+ :param args:
+ - If converting from a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
+ - If converting from a BPMN or ProcessTree: a single object of the respective type.
+ :return: A ``ProcessTree`` object.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ # Imports a BPMN file
+ bpmn_graph = pm4py.read_bpmn("tests/input_data/running-example.bpmn")
+ # Converts the BPMN to a POWL (through intermediate conversion to a Petri net)
+ powl = pm4py.convert_to_powl(bpmn_graph)
+ print(powl)
+ """
+ from pm4py.objects.process_tree.obj import ProcessTree
+ from pm4py.objects.petri_net.obj import PetriNet
+
+ if isinstance(args[0], ProcessTree):
+ from pm4py.objects.conversion.process_tree.variants import to_powl
+ return to_powl.apply(args[0])
+ elif isinstance(args[0], PetriNet):
+ from pm4py.objects.conversion.wf_net.variants import to_powl
+ return to_powl.apply(args[0])
+ elif isinstance(args[0], BPMN):
+ from pm4py.objects.conversion.wf_net.variants import to_powl
+ net, im, fm = pm4py.convert_to_petri_net(args[0])
+ return to_powl.apply(net)
+
+ raise Exception(
+ "The object represents a model that cannot be directly represented as a POWL!"
+ )
+
+
+def convert_to_reachability_graph(
+ *args: Union[Tuple[PetriNet, Marking, Marking], BPMN, ProcessTree]
+) -> TransitionSystem:
+ """
+ Converts an input model to a reachability graph (transition system).
+
+ The input models can be Petri nets (with markings), BPMN models, or process trees.
+ The output is the state-space of the model, encoded as a ``TransitionSystem`` object.
+
+ :param args:
+ - If converting from a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
+ - If converting from a BPMN or ProcessTree: a single object of the respective type.
+ :return: A ``TransitionSystem`` object.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ # Reads a Petri net from a file
+ net, im, fm = pm4py.read_pnml("tests/input_data/running-example.pnml")
+ # Converts it to a reachability graph
+ reach_graph = pm4py.convert_to_reachability_graph(net, im, fm)
+ """
+ if isinstance(args[0], PetriNet):
+ net, im, fm = args[0], args[1], args[2]
+ else:
+ net, im, fm = convert_to_petri_net(*args)
+
+ from pm4py.objects.petri_net.utils import reachability_graph
+
+ return reachability_graph.construct_reachability_graph(net, im)
+
+
+def convert_log_to_ocel(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ activity_column: str = "concept:name",
+ timestamp_column: str = "time:timestamp",
+ object_types: Optional[Collection[str]] = None,
+ obj_separator: str = " AND ",
+ additional_event_attributes: Optional[Collection[str]] = None,
+ additional_object_attributes: Optional[Dict[str, Collection[str]]] = None,
+) -> OCEL:
+ """
+ Converts an event log to an object-centric event log (OCEL) with one or more object types.
+
+ :param log: The log object to convert.
+ :param activity_column: The name of the column representing activities.
+ :param timestamp_column: The name of the column representing timestamps.
+ :param object_types: A collection of column names to consider as object types. If None, defaults are used.
+ :param obj_separator: The separator used between different objects in the same column. Defaults to " AND ".
+ :param additional_event_attributes: Additional attribute names to include as event attributes in the OCEL.
+ :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.
+ :return: An ``OCEL`` object.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.convert_log_to_ocel(
+ log,
+ activity_column='concept:name',
+ timestamp_column='time:timestamp',
+ object_types=['case:concept:name']
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if isinstance(log, EventStream):
+ log = convert_to_dataframe(log)
+
+ if object_types is None:
+ object_types = list(
+ set(
+ x
+ for x in log.columns
+ if x == "case:concept:name" or x.startswith("ocel:type")
+ )
+ )
+
+ from pm4py.objects.ocel.util import log_ocel
+
+ return log_ocel.log_to_ocel_multiple_obj_types(
+ log,
+ activity_column,
+ timestamp_column,
+ object_types,
+ obj_separator,
+ additional_event_attributes=additional_event_attributes,
+ additional_object_attributes=additional_object_attributes,
+ )
+
+
+def convert_ocel_to_networkx(
+ ocel: OCEL, variant: str = "ocel_to_nx"
+) -> nx.DiGraph:
+ """
+ Converts an OCEL to a NetworkX DiGraph object.
+
+ :param ocel: The object-centric event log to convert.
+ :param variant: The variant of the conversion to use.
+ Options:
+ - "ocel_to_nx": Graph containing event and object IDs and two types of relations (REL=related objects, DF=directly-follows).
+ - "ocel_features_to_nx": Graph containing different types of interconnections at the object level.
+ :return: A ``nx.DiGraph`` object representing the OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ nx_digraph = pm4py.convert_ocel_to_networkx(ocel, variant='ocel_to_nx')
+ """
+ from pm4py.objects.conversion.ocel import converter
+
+ variant1 = None
+ if variant == "ocel_to_nx":
+ variant1 = converter.Variants.OCEL_TO_NX
+ elif variant == "ocel_features_to_nx":
+ variant1 = converter.Variants.OCEL_FEATURES_TO_NX
+ else:
+ raise ValueError(
+ f"Unsupported variant '{variant}'. Supported variants are 'ocel_to_nx' and 'ocel_features_to_nx'.")
+
+ return converter.apply(ocel, variant=variant1)
+
+
+def convert_log_to_networkx(
+ log: Union[EventLog, EventStream, pd.DataFrame],
+ include_df: bool = True,
+ case_id_key: str = "concept:name",
+ other_case_attributes_as_nodes: Optional[Collection[str]] = None,
+ event_attributes_as_nodes: Optional[Collection[str]] = None,
+) -> nx.DiGraph:
+ """
+ Converts an event log to a NetworkX DiGraph object.
+
+ The nodes of the graph include events, cases, and optionally log attributes.
+ The edges represent:
+ - BELONGS_TO: Connecting each event to its corresponding case.
+ - DF: Connecting events that directly follow each other (if enabled).
+ - ATTRIBUTE_EDGE: Connecting cases/events to their attribute values.
+
+ :param log: The log object to convert (``EventLog``, ``EventStream``, or Pandas DataFrame).
+ :param include_df: Whether to include the directly-follows relation in the graph. Defaults to True.
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "concept:name".
+ :param other_case_attributes_as_nodes: Attributes at the case level to include as nodes, excluding the case ID.
+ :param event_attributes_as_nodes: Attributes at the event level to include as nodes.
+ :return: A ``nx.DiGraph`` object representing the event log.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ nx_digraph = pm4py.convert_log_to_networkx(
+ log,
+ other_case_attributes_as_nodes=['responsible', 'department'],
+ event_attributes_as_nodes=['concept:name', 'org:resource']
+ )
+ """
+ from pm4py.objects.conversion.log import converter
+
+ return converter.apply(
+ log,
+ variant=converter.Variants.TO_NX,
+ parameters={
+ "include_df": include_df,
+ "case_id_attribute": case_id_key,
+ "other_case_attributes_as_nodes": other_case_attributes_as_nodes,
+ "event_attributes_as_nodes": event_attributes_as_nodes,
+ },
+ )
+
+
+def convert_log_to_time_intervals(
+ log: Union[EventLog, pd.DataFrame],
+ filter_activity_couple: Optional[Tuple[str, str]] = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ start_timestamp_key: str = "time:timestamp",
+) -> List[List[Any]]:
+ """
+ Extracts a list of time intervals from an event log.
+
+ Each interval contains two temporally consecutive events within the same case and measures the time between them
+ (complete timestamp of the first event against the start timestamp of the second event).
+
+ :param log: The log object to convert.
+ :param filter_activity_couple: Optional tuple to filter intervals by a specific pair of activities.
+ :param activity_key: The attribute to be used as the activity identifier. Defaults to "concept:name".
+ :param timestamp_key: The attribute to be used as the timestamp. Defaults to "time:timestamp".
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "case:concept:name".
+ :param start_timestamp_key: The attribute to be used as the start timestamp in the interval. Defaults to "time:timestamp".
+ :return: A list of intervals, where each interval is a list containing relevant information about the time gap.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
+ time_intervals = pm4py.convert_log_to_time_intervals(log)
+ print(len(time_intervals))
+ time_intervals = pm4py.convert_log_to_time_intervals(
+ log,
+ filter_activity_couple=('Confirmation of receipt', 'T02 Check confirmation of receipt')
+ )
+ print(len(time_intervals))
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+ properties["filter_activity_couple"] = filter_activity_couple
+ properties[constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY] = (
+ start_timestamp_key
+ )
+
+ from pm4py.algo.transformation.log_to_interval_tree.variants import (
+ open_paths,
+ )
+
+ return open_paths.log_to_intervals(log, parameters=properties)
+
+
+def convert_petri_net_to_networkx(
+ net: PetriNet, im: Marking, fm: Marking
+) -> nx.DiGraph:
+ """
+ Converts a Petri net to a NetworkX DiGraph.
+
+ Each place and transition in the Petri net is represented as a node in the graph.
+
+ :param net: The Petri net to convert.
+ :param im: The initial marking of the Petri net.
+ :param fm: The final marking of the Petri net.
+ :return: A ``nx.DiGraph`` object representing the Petri net.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
+ nx_digraph = pm4py.convert_petri_net_to_networkx(net, im, fm)
+ """
+ G = nx_utils.DiGraph()
+ for place in net.places:
+ G.add_node(
+ place.name,
+ attr={
+ "name": place.name,
+ "is_in_im": place in im,
+ "is_in_fm": place in fm,
+ "type": "place",
+ },
+ )
+ for trans in net.transitions:
+ G.add_node(
+ trans.name,
+ attr={
+ "name": trans.name,
+ "label": trans.label,
+ "type": "transition",
+ },
+ )
+ for arc in net.arcs:
+ G.add_edge(
+ arc.source.name,
+ arc.target.name,
+ attr={"weight": arc.weight, "properties": arc.properties},
+ )
+ return G
+
+
+def convert_petri_net_type(
+ net: PetriNet, im: Marking, fm: Marking, type: str = "classic"
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Changes the internal type of a Petri net.
+
+ Supports conversion to different Petri net types such as classic, reset, inhibitor, and reset_inhibitor nets.
+
+ :param net: The Petri net to convert.
+ :param im: The initial marking of the Petri net.
+ :param fm: The final marking of the Petri net.
+ :param type: The target Petri net type. Options are "classic", "reset", "inhibitor", "reset_inhibitor". Defaults to "classic".
+ :return: A tuple of the converted (``PetriNet``, ``Marking``, ``Marking``).
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
+ reset_net, new_im, new_fm = pm4py.convert_petri_net_type(net, im, fm, type='reset_inhibitor')
+ """
+ from pm4py.objects.petri_net.utils import petri_utils
+
+ [net, im, fm] = deepcopy([net, im, fm])
+ new_net = None
+ if type == "classic":
+ from pm4py.objects.petri_net.obj import PetriNet
+
+ new_net = PetriNet(net.name)
+ elif type == "reset":
+ from pm4py.objects.petri_net.obj import ResetNet
+
+ new_net = ResetNet(net.name)
+ elif type == "inhibitor":
+ from pm4py.objects.petri_net.obj import InhibitorNet
+
+ new_net = InhibitorNet(net.name)
+ elif type == "reset_inhibitor":
+ from pm4py.objects.petri_net.obj import ResetInhibitorNet
+
+ new_net = ResetInhibitorNet(net.name)
+ else:
+ raise ValueError(
+ f"Unsupported Petri net type '{type}'. Supported types are 'classic', 'reset', 'inhibitor', 'reset_inhibitor'.")
+
+ for place in net.places:
+ new_net.places.add(place)
+ in_arcs = set(place.in_arcs)
+ out_arcs = set(place.out_arcs)
+ for arc in in_arcs:
+ place.in_arcs.remove(arc)
+ for arc in out_arcs:
+ place.out_arcs.remove(arc)
+ for trans in net.transitions:
+ new_net.transitions.add(trans)
+ in_arcs = set(trans.in_arcs)
+ out_arcs = set(trans.out_arcs)
+ for arc in in_arcs:
+ trans.in_arcs.remove(arc)
+ for arc in out_arcs:
+ trans.out_arcs.remove(arc)
+ for arc in net.arcs:
+ arc_type = (
+ arc.properties["arctype"] if "arctype" in arc.properties else None
+ )
+ new_arc = petri_utils.add_arc_from_to(
+ arc.source, arc.target, new_net, weight=arc.weight, type=arc_type
+ )
+ return new_net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/discovery.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/discovery.py
new file mode 100644
index 0000000000000000000000000000000000000000..60bcac402667893316ff4d8b48a93be05dd77514
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/discovery.py
@@ -0,0 +1,1790 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+The ``pm4py.discovery`` module contains the process discovery algorithms implemented in ``pm4py``.
+"""
+
+from typing import Tuple, Union, List, Dict, Any, Optional, Set, TextIO
+from collections import Counter
+
+import pandas as pd
+from pandas import DataFrame
+
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.bpmn.obj import BPMN
+from pm4py.objects.dfg.obj import DFG
+from pm4py.objects.powl.obj import POWL
+from pm4py.objects.heuristics_net.obj import HeuristicsNet
+from pm4py.objects.transition_system.obj import TransitionSystem
+from pm4py.objects.trie.obj import Trie
+from pm4py.objects.log.obj import EventLog
+from pm4py.objects.log.obj import EventStream
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.util.pandas_utils import (
+ check_is_pandas_dataframe,
+ check_pandas_dataframe_columns,
+)
+from pm4py.utils import get_properties, __event_log_deprecation_warning, is_polars_lazyframe
+from pm4py.util import constants, pandas_utils
+from pm4py.util import deprecation
+import importlib.util
+
+
+def discover_dfg(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[dict, dict, dict]:
+ """
+ Discovers a Directly-Follows Graph (DFG) from a log.
+
+ This method returns a tuple containing:
+
+ - A dictionary with pairs of directly-following activities as keys and the frequency of the relationship as values.
+ - A dictionary of start activities with their respective frequencies.
+ - A dictionary of end activities with their respective frequencies.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A tuple of three dictionaries: (dfg, start_activities, end_activities).
+ :rtype: ``Tuple[dict, dict, dict]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dfg, start_activities, end_activities = pm4py.discover_dfg(
+ dataframe,
+ case_id_key='case:concept:name',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ from pm4py.util import constants
+
+ if is_polars_lazyframe(log):
+ from pm4py.algo.discovery.dfg.adapters.polars.df_statistics import get_dfg_graph
+ from pm4py.statistics.start_activities.polars import get as start_activities_module
+ from pm4py.statistics.end_activities.polars import get as end_activities_module
+ else:
+ from pm4py.algo.discovery.dfg.adapters.pandas.df_statistics import (
+ get_dfg_graph,
+ )
+ from pm4py.statistics.start_activities.pandas import (
+ get as start_activities_module,
+ )
+ from pm4py.statistics.end_activities.pandas import (
+ get as end_activities_module,
+ )
+
+ dfg = get_dfg_graph(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_glue=case_id_key,
+ )
+
+ start_activities = start_activities_module.get_start_activities(
+ log, parameters=properties
+ )
+ end_activities = end_activities_module.get_end_activities(
+ log, parameters=properties
+ )
+ else:
+ from pm4py.algo.discovery.dfg import algorithm as dfg_discovery
+
+ dfg = dfg_discovery.apply(log, parameters=properties)
+ from pm4py.statistics.start_activities.log import (
+ get as start_activities_module,
+ )
+ from pm4py.statistics.end_activities.log import (
+ get as end_activities_module,
+ )
+
+ start_activities = start_activities_module.get_start_activities(
+ log, parameters=properties
+ )
+ end_activities = end_activities_module.get_end_activities(
+ log, parameters=properties
+ )
+ return dfg, start_activities, end_activities
+
+
+def discover_directly_follows_graph(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[dict, dict, dict]:
+ return discover_dfg(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+
+def discover_dfg_typed(
+ log: pd.DataFrame,
+ case_id_key: str = "case:concept:name",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+) -> DFG:
+ """
+ Discovers a typed Directly-Follows Graph (DFG) from a log.
+
+ This method returns a typed DFG object, as specified in ``pm4py.objects.dfg.obj.py`` (``DirectlyFollowsGraph`` Class).
+ The DFG object includes the graph, start activities, and end activities.
+ - The graph is a collection of triples of the form (a, b, f) representing an arc a->b with frequency f.
+ - The start activities are a collection of tuples of the form (a, f) representing that activity a starts f cases.
+ - The end activities are a collection of tuples of the form (a, f) representing that activity a ends f cases.
+
+ 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.
+
+ :param log: ``pandas.DataFrame``
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :return: A typed DFG object containing the graph, start activities, and end activities.
+ :rtype: ``DFG``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ dfg = pm4py.discover_dfg_typed(
+ log,
+ case_id_key='case:concept:name',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ from pm4py.objects.dfg.obj import DFG
+
+ dfg, sa, ea = discover_dfg(log, activity_key=activity_key, case_id_key=case_id_key, timestamp_key=timestamp_key)
+ return DFG(dfg, sa, ea)
+
+
+def discover_performance_dfg(
+ log: Union[EventLog, pd.DataFrame],
+ business_hours: bool = False,
+ business_hour_slots=constants.DEFAULT_BUSINESS_HOUR_SLOTS,
+ workcalendar=constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ perf_aggregation_key: str = "all",
+) -> Tuple[dict, dict, dict]:
+ """
+ Discovers a Performance Directly-Follows Graph from an event log.
+
+ This method returns a tuple containing:
+
+ - A dictionary with pairs of directly-following activities as keys and the performance metrics of the relationship as values.
+ - A dictionary of start activities with their respective frequencies.
+ - A dictionary of end activities with their respective frequencies.
+
+ :param log: Event log or Pandas DataFrame.
+ :param business_hours: Enables or disables computation based on business hours (default: False).
+ :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.
+ :param workcalendar: Calendar exposing ``is_working_day(day)``. Dates
+ rejected by the calendar are excluded when business hours are enabled.
+
+ Example::
+
+ [
+ (7 * 60 * 60, 17 * 60 * 60), # Monday 07:00 - 17:00
+ ((24 + 7) * 60 * 60, (24 + 12) * 60 * 60), # Tuesday 07:00 - 12:00
+ ((24 + 13) * 60 * 60, (24 + 17) * 60 * 60) # Tuesday 13:00 - 17:00
+ ]
+
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :param perf_aggregation_key: Selector for the type of aggregation (all, mean, median, max, min, sum, stdev)
+ When business hours are enabled, the returned performance DFG remains
+ dictionary-compatible and also retains the configured schedule so that
+ visualizations can express its durations in working days.
+
+ :return: A tuple of three dictionaries: (performance_dfg, start_activities, end_activities).
+ :rtype: ``Tuple[dict, dict, dict]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ performance_dfg, start_activities, end_activities = pm4py.discover_performance_dfg(
+ dataframe,
+ case_id_key='case:concept:name',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ from pm4py.util import constants
+
+ if is_polars_lazyframe(log):
+ from pm4py.algo.discovery.dfg.adapters.polars.df_statistics import get_dfg_graph
+ from pm4py.statistics.start_activities.polars import get as start_activities_module
+ from pm4py.statistics.end_activities.polars import get as end_activities_module
+ else:
+ from pm4py.algo.discovery.dfg.adapters.pandas.df_statistics import (
+ get_dfg_graph,
+ )
+ from pm4py.statistics.start_activities.pandas import (
+ get as start_activities_module,
+ )
+ from pm4py.statistics.end_activities.pandas import (
+ get as end_activities_module,
+ )
+
+ dfg = get_dfg_graph(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_glue=case_id_key,
+ measure="performance",
+ perf_aggregation_key=perf_aggregation_key,
+ business_hours=business_hours,
+ business_hours_slot=business_hour_slots,
+ workcalendar=workcalendar,
+ )
+
+ start_activities = start_activities_module.get_start_activities(
+ log, parameters=properties
+ )
+ end_activities = end_activities_module.get_end_activities(
+ log, parameters=properties
+ )
+ else:
+ from pm4py.algo.discovery.dfg.variants import (
+ performance as dfg_discovery,
+ )
+
+ properties[dfg_discovery.Parameters.AGGREGATION_MEASURE] = (
+ perf_aggregation_key
+ )
+ properties[dfg_discovery.Parameters.BUSINESS_HOURS] = business_hours
+ properties[dfg_discovery.Parameters.BUSINESS_HOUR_SLOTS] = (
+ business_hour_slots
+ )
+ properties[dfg_discovery.Parameters.WORKCALENDAR] = workcalendar
+ dfg = dfg_discovery.apply(log, parameters=properties)
+ from pm4py.statistics.start_activities.log import (
+ get as start_activities_module,
+ )
+ from pm4py.statistics.end_activities.log import (
+ get as end_activities_module,
+ )
+
+ start_activities = start_activities_module.get_start_activities(
+ log, parameters=properties
+ )
+ end_activities = end_activities_module.get_end_activities(
+ log, parameters=properties
+ )
+ if business_hours:
+ from pm4py.objects.dfg.obj import PerformanceDFG
+
+ dfg = PerformanceDFG(
+ dfg, business_hour_slots=business_hour_slots
+ )
+
+ return dfg, start_activities, end_activities
+
+
+def discover_petri_net_alpha(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Discovers a Petri net using the Alpha Miner.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A tuple containing the Petri net, initial marking, and final marking.
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_alpha(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.discovery.alpha import algorithm as alpha_miner
+
+ return alpha_miner.apply(
+ log,
+ variant=alpha_miner.Variants.ALPHA_VERSION_CLASSIC,
+ parameters=get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ ),
+ )
+
+
+def discover_petri_net_ilp(
+ log: Union[EventLog, pd.DataFrame],
+ alpha: float = 1.0,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Discovers a Petri net using the ILP Miner.
+
+ :param log: Event log or Pandas DataFrame.
+ :param alpha: Noise threshold for the sequence encoding graph (1.0=no filtering, 0.0=maximum filtering) (default: 1.0).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A tuple containing the Petri net, initial marking, and final marking.
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_ilp(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["alpha"] = alpha
+
+ from pm4py.algo.discovery.ilp import algorithm as ilp_miner
+
+ return ilp_miner.apply(
+ log, variant=ilp_miner.Variants.CLASSIC, parameters=parameters
+ )
+
+
+def discover_petri_net_genetic(
+ log: Union[EventLog, pd.DataFrame],
+ population_size: int = 500,
+ elitism_rate: float = 0.01,
+ crossover_rate: float = 1.0,
+ mutation_rate: float = 0.01,
+ generations: int = 100,
+ elitism_min_sample: int = 5,
+ log_csv: TextIO = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Discovers a Petri net using the Genetic Miner.
+
+ Reference paper:
+ Maximilian Josef Frank. "Optimising and Implementing the Genetic Miner in PM4Py" (2026).
+
+ :param log: Event log or Pandas DataFrame.
+ :param population_size: Population size of genetic sampling (default: 500).
+ :param elitism_rate: Rate of best models used in next generation (default: 0.01).
+ :param crossover_rate: Rate of genetically combined models (offsprings) used in next generation (default: 1.0).
+ :param mutation_rate: Random model mutation rate (default: 0.01).
+ :param generations: Iterations of model improvement (default: 100).
+ :param elitism_min_sample: Minimum sample size for selecting best models (default: 5).
+ :param log_csv: Output stream for CSV log (default: None).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A tuple containing the Petri net, initial marking, and final marking.
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_genetic(
+ dataframe,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ from pm4py.algo.discovery.genetic import algorithm as genetic_miner
+
+ genetic_parameters = genetic_miner.Parameters
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters[genetic_parameters.POPULATION_SIZE] = population_size
+ parameters[genetic_parameters.ELITISM_RATE] = elitism_rate
+ parameters[genetic_parameters.CROSSOVER_RATE] = crossover_rate
+ parameters[genetic_parameters.MUTATION_RATE] = mutation_rate
+ parameters[genetic_parameters.GENERATIONS] = generations
+ parameters[genetic_parameters.ELITISM_MIN_SAMPLE] = elitism_min_sample
+ parameters[genetic_parameters.LOG_CSV] = log_csv
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ return genetic_miner.apply(
+ log,
+ variant=genetic_miner.Variants.CLASSIC,
+ parameters=parameters,
+ )
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="This method will be removed in a future release.",
+)
+def discover_petri_net_alpha_plus(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Discovers a Petri net using the Alpha+ algorithm.
+
+ .. deprecated:: 2.3.0
+ This method will be removed in version 3.0.0. Use other discovery methods instead.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A tuple containing the Petri net, initial marking, and final marking.
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_alpha_plus(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.discovery.alpha import algorithm as alpha_miner
+
+ return alpha_miner.apply(
+ log,
+ variant=alpha_miner.Variants.ALPHA_VERSION_PLUS,
+ parameters=get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ ),
+ )
+
+
+def discover_petri_net_inductive(
+ log: Union[EventLog, pd.DataFrame, DFG],
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
+ noise_threshold: float = 0.0,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ disable_fallthroughs: bool = False,
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Discovers a Petri net using the Inductive Miner algorithm.
+
+ 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.
+ Inductive miner models typically use hidden transitions for skipping or looping portions of the model, and each visible transition has a unique label.
+
+ :param log: Event log, Pandas DataFrame, or typed DFG.
+ :param multi_processing: Enables or disables multiprocessing in the Inductive Miner (default: constants.ENABLE_MULTIPROCESSING_DEFAULT).
+ :param noise_threshold: Noise threshold (default: 0.0).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :param disable_fallthroughs: Disables the Inductive Miner fall-throughs (default: False).
+ :return: A tuple containing the Petri net, initial marking, and final marking.
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ pt = discover_process_tree_inductive(
+ log,
+ noise_threshold,
+ multi_processing=multi_processing,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ disable_fallthroughs=disable_fallthroughs,
+ )
+ from pm4py.convert import convert_to_petri_net
+
+ return convert_to_petri_net(pt)
+
+
+def discover_petri_net_heuristics(
+ log: Union[EventLog, pd.DataFrame],
+ dependency_threshold: float = 0.5,
+ and_threshold: float = 0.65,
+ loop_two_threshold: float = 0.5,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Discovers a Petri net using the Heuristics Miner.
+
+ Heuristics Miner operates on the Directly-Follows Graph, handling noise and identifying common constructs such as dependencies between activities and parallelism.
+ The output is a Heuristics Net, which can then be converted into a Petri net.
+
+ :param log: Event log or Pandas DataFrame.
+ :param dependency_threshold: Dependency threshold (default: 0.5).
+ :param and_threshold: AND threshold for parallelism (default: 0.65).
+ :param loop_two_threshold: Loop two threshold (default: 0.5).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A tuple containing the Petri net, initial marking, and final marking.
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.discover_petri_net_heuristics(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ from pm4py.algo.discovery.heuristics.variants import (
+ classic as heuristics_miner,
+ )
+
+ heu_parameters = heuristics_miner.Parameters
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters[heu_parameters.DEPENDENCY_THRESH] = dependency_threshold
+ parameters[heu_parameters.AND_MEASURE_THRESH] = and_threshold
+ parameters[heu_parameters.LOOP_LENGTH_TWO_THRESH] = loop_two_threshold
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ return heuristics_miner.apply_pandas(log, parameters=parameters)
+ else:
+ return heuristics_miner.apply(log, parameters=parameters)
+
+
+def discover_process_tree_inductive(
+ log: Union[EventLog, pd.DataFrame, DFG],
+ noise_threshold: float = 0.0,
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ disable_fallthroughs: bool = False,
+) -> ProcessTree:
+ """
+ Discovers a Process Tree using the Inductive Miner algorithm.
+
+ 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.
+ Inductive miner models typically use hidden transitions for skipping or looping portions of the model, and each visible transition has a unique label.
+
+ :param log: Event log, Pandas DataFrame, or typed DFG.
+ :param noise_threshold: Noise threshold (default: 0.0).
+ :param multi_processing: Enables or disables multiprocessing in the Inductive Miner (default: constants.ENABLE_MULTIPROCESSING_DEFAULT).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :param disable_fallthroughs: Disables the Inductive Miner fall-throughs (default: False).
+ :return: A ProcessTree object.
+ :rtype: ``ProcessTree``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ process_tree = pm4py.discover_process_tree_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.discovery.inductive import algorithm as inductive_miner
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["noise_threshold"] = noise_threshold
+ parameters["multiprocessing"] = multi_processing
+ parameters["disable_fallthroughs"] = disable_fallthroughs
+
+ variant = (
+ inductive_miner.Variants.IMf
+ if noise_threshold > 0
+ else inductive_miner.Variants.IM
+ )
+
+ if isinstance(log, DFG):
+ variant = inductive_miner.Variants.IMd
+
+ return inductive_miner.apply(log, variant=variant, parameters=parameters)
+
+
+def discover_heuristics_net(
+ log: Union[EventLog, pd.DataFrame],
+ dependency_threshold: float = 0.5,
+ and_threshold: float = 0.65,
+ loop_two_threshold: float = 0.5,
+ min_act_count: int = 1,
+ min_dfg_occurrences: int = 1,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ decoration: str = "frequency",
+) -> HeuristicsNet:
+ """
+ Discovers a Heuristics Net.
+
+ Heuristics Miner operates on the Directly-Follows Graph, handling noise and identifying common constructs such as dependencies between activities and parallelism.
+ The output is a Heuristics Net, which can then be converted into a Petri net.
+
+ :param log: Event log or Pandas DataFrame.
+ :param dependency_threshold: Dependency threshold (default: 0.5).
+ :param and_threshold: AND threshold for parallelism (default: 0.65).
+ :param loop_two_threshold: Loop two threshold (default: 0.5).
+ :param min_act_count: Minimum number of occurrences per activity to be included in the discovery (default: 1).
+ :param min_dfg_occurrences: Minimum number of occurrences per arc in the DFG to be included in the discovery (default: 1).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :param decoration: The decoration to be used ("frequency" or "performance") (default: "frequency").
+ :return: A HeuristicsNet object.
+ :rtype: ``HeuristicsNet``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ heu_net = pm4py.discover_heuristics_net(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ from pm4py.algo.discovery.heuristics.variants import (
+ classic as heuristics_miner,
+ )
+
+ heu_parameters = heuristics_miner.Parameters
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters[heu_parameters.DEPENDENCY_THRESH] = dependency_threshold
+ parameters[heu_parameters.AND_MEASURE_THRESH] = and_threshold
+ parameters[heu_parameters.LOOP_LENGTH_TWO_THRESH] = loop_two_threshold
+ parameters[heu_parameters.MIN_ACT_COUNT] = min_act_count
+ parameters[heu_parameters.MIN_DFG_OCCURRENCES] = min_dfg_occurrences
+ parameters[heu_parameters.HEU_NET_DECORATION] = decoration
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ return heuristics_miner.apply_heu_pandas(log, parameters=parameters)
+ else:
+ return heuristics_miner.apply_heu(log, parameters=parameters)
+
+
+def derive_minimum_self_distance(
+ log: Union[DataFrame, EventLog, EventStream],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Dict[str, int]:
+ """
+ Computes the minimum self-distance for each activity observed in an event log.
+
+ The self-distance of activity `a` in `` is infinity,
+ in `` is 0,
+ in `` is 1,
+ etc. The activity key 'concept:name' is used.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A dictionary mapping each activity to its minimum self-distance.
+ :rtype: ``Dict[str, int]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ msd = pm4py.derive_minimum_self_distance(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.discovery.minimum_self_distance import algorithm as msd
+
+ return msd.apply(
+ log,
+ parameters=get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ ),
+ )
+
+
+def discover_footprints(
+ *args: Union[EventLog, Tuple[PetriNet, Marking, Marking], ProcessTree, POWL]
+) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
+ """
+ Discovers the footprints from the provided event log or process model.
+
+ Footprints are a high-level representation of the behavior captured in the event log or process model.
+
+ :param args: Event log, process model (Petri net and markings), or ProcessTree, or POWL.
+ :return: A list of footprint dictionaries or a single footprint dictionary.
+ :rtype: ``Union[List[Dict[str, Any]], Dict[str, Any]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ footprints = pm4py.discover_footprints(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ from pm4py.algo.discovery.footprints import algorithm as fp_discovery
+
+ return fp_discovery.apply(*args)
+
+
+def discover_eventually_follows_graph(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Dict[Tuple[str, str], int]:
+ """
+ Generates the Eventually-Follows Graph from a log.
+
+ 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.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A dictionary mapping each pair of activities to the count of their eventually-follows relationship.
+ :rtype: ``Dict[Tuple[str, str], int]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ efg = pm4py.discover_eventually_follows_graph(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ if is_polars_lazyframe(log):
+ from pm4py.statistics.eventually_follows.polars import get
+ return get.apply(log, parameters=properties)
+ else:
+ from pm4py.statistics.eventually_follows.pandas import get
+ return get.apply(log, parameters=properties)
+ else:
+ from pm4py.statistics.eventually_follows.log import get
+
+ return get.apply(log, parameters=properties)
+
+
+def discover_bpmn_inductive(
+ log: Union[EventLog, pd.DataFrame, DFG],
+ noise_threshold: float = 0.0,
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ disable_fallthroughs: bool = False,
+) -> BPMN:
+ """
+ Discovers a BPMN model using the Inductive Miner algorithm.
+
+ 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.
+ Inductive miner models typically use hidden transitions for skipping or looping portions of the model, and each visible transition has a unique label.
+
+ :param log: Event log, Pandas DataFrame, or typed DFG.
+ :param noise_threshold: Noise threshold (default: 0.0).
+ :param multi_processing: Enables or disables multiprocessing in the Inductive Miner (default: constants.ENABLE_MULTIPROCESSING_DEFAULT).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :param disable_fallthroughs: Disables the Inductive Miner fall-throughs (default: False).
+ :return: A BPMN object representing the discovered BPMN model.
+ :rtype: ``BPMN``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ bpmn_graph = pm4py.discover_bpmn_inductive(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ pt = discover_process_tree_inductive(
+ log,
+ noise_threshold,
+ multi_processing=multi_processing,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ disable_fallthroughs=disable_fallthroughs,
+ )
+ from pm4py.convert import convert_to_bpmn
+
+ return convert_to_bpmn(pt)
+
+
+def discover_bpmn_split_miner(
+ log: Union[EventLog, pd.DataFrame],
+ epsilon: float = 0.1,
+ eta: float = 0.4,
+ minimize_or_joins: bool = True,
+ variant: str = "classic",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> BPMN:
+ """Discover a BPMN model using Split Miner.
+
+ Two variants are available:
+
+ * ``"classic"`` — the original Split Miner of Augusto, Conforti,
+ Dumas, La Rosa, Polyvyanyy (KAIS, 2019).
+ * ``"sm2"`` — Split Miner 2.0 (Augusto, Dumas, La Rosa, 2021): uses
+ activity lifecycle information to detect true concurrency and
+ inclusive (OR) choices.
+
+ :param log: Event log or Pandas DataFrame.
+ :param epsilon: Concurrency threshold ε ∈ [0, 1] (default 0.1). With a
+ lower ε more pairs of activities are considered concurrent.
+ :param eta: Filtering percentile η ∈ [0, 1] (default 0.4). Lower η
+ keeps more edges (higher fitness, more complex model). Used by the
+ ``classic`` variant only; ``sm2`` pins η to 1.0 and ignores this.
+ :param minimize_or_joins: Replace trivial OR-joins with their XOR/AND
+ equivalent (Algorithm 9 of the SM 1.x paper). Default ``True``.
+ Used by the ``classic`` variant only; for ``sm2`` the OR handling
+ is an intrinsic stage that always runs, so this flag is ignored.
+ :param variant: ``"classic"`` (default) or ``"sm2"``.
+ :param activity_key: XES attribute holding the activity label
+ (default ``"concept:name"``).
+ :param timestamp_key: XES attribute holding the event timestamp
+ (default ``"time:timestamp"``). Used only by the ``sm2`` variant.
+ :param case_id_key: Attribute used as case identifier in pandas inputs
+ (default ``"case:concept:name"``).
+ :return: A :class:`BPMN` model.
+ :rtype: ``BPMN``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ bpmn_graph = pm4py.discover_bpmn_split_miner(
+ log,
+ epsilon=0.1,
+ eta=0.4,
+ variant="sm2",
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.discovery.split_miner import algorithm as sm_alg
+
+ if variant == "sm2":
+ sm_variant = sm_alg.SM2
+ from pm4py.algo.discovery.split_miner.variants.sm2 import (
+ Parameters as SmParameters,
+ )
+ elif variant == "classic":
+ sm_variant = sm_alg.CLASSIC
+ from pm4py.algo.discovery.split_miner.variants.classic import (
+ Parameters as SmParameters,
+ )
+ else:
+ raise ValueError(
+ f"Unknown Split Miner variant: {variant!r} "
+ f"(expected 'classic' or 'sm2')"
+ )
+
+ parameters = {
+ SmParameters.EPSILON: epsilon,
+ SmParameters.ETA: eta,
+ SmParameters.OR_MINIMISE: minimize_or_joins,
+ SmParameters.ACTIVITY_KEY: activity_key,
+ }
+ if variant == "sm2":
+ parameters[SmParameters.TIMESTAMP_KEY] = timestamp_key
+
+ return sm_alg.apply(log, parameters=parameters, variant=sm_variant)
+
+
+def discover_transition_system(
+ log: Union[EventLog, pd.DataFrame],
+ direction: str = "forward",
+ window: int = 2,
+ view: str = "sequence",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> TransitionSystem:
+ """
+ Discovers a Transition System from a log.
+
+ The Transition System is built based on the specified direction, window size, and view. It captures the transitions between states of activity sequences.
+
+ :param log: Event log or Pandas DataFrame.
+ :param direction: Direction in which the transition system is built ("forward" or "backward") (default: "forward").
+ :param window: Window size for state construction (e.g., 2, 3) (default: 2).
+ :param view: View to use in the construction of the states ("sequence", "set", "multiset") (default: "sequence").
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A TransitionSystem object representing the discovered transition system.
+ :rtype: ``TransitionSystem``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ transition_system = pm4py.discover_transition_system(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ properties["direction"] = direction
+ properties["window"] = window
+ properties["view"] = view
+
+ from pm4py.algo.discovery.transition_system import (
+ algorithm as ts_discovery,
+ )
+
+ return ts_discovery.apply(log, parameters=properties)
+
+
+def discover_prefix_tree(
+ log: Union[EventLog, pd.DataFrame],
+ max_path_length: Optional[int] = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Trie:
+ """
+ Discovers a Prefix Tree from the provided log.
+
+ A Prefix Tree represents all the unique prefixes of activity sequences in the log.
+
+ :param log: Event log or Pandas DataFrame.
+ :param max_path_length: maximum path length (each trace is trimmed afterwards).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A Trie object representing the discovered prefix tree.
+ :rtype: ``Trie``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ prefix_tree = pm4py.discover_prefix_tree(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties["max_path_length"] = max_path_length
+
+ from pm4py.algo.transformation.log_to_trie import (
+ algorithm as trie_discovery,
+ )
+
+ return trie_discovery.apply(log, parameters=properties)
+
+
+def discover_temporal_profile(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Dict[Tuple[str, str], Tuple[float, float]]:
+ """
+ Discovers a Temporal Profile from a log.
+
+ Implements the approach described in:
+ 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).
+
+ The output is a dictionary containing, for every pair of activities that eventually follow each other in at least one case of the log,
+ the average and the standard deviation of the time difference between their timestamps.
+
+ Example:
+ If the log has two cases:
+
+ - Case 1: A (timestamp: 1980-01) → B (timestamp: 1980-03) → C (timestamp: 1980-06)
+ - Case 2: A (timestamp: 1990-01) → B (timestamp: 1990-02) → D (timestamp: 1990-03)
+
+ The returned dictionary will contain::
+
+ {
+ ('A', 'B'): (1.5 months, 0.5 months),
+ ('A', 'C'): (5 months, 0),
+ ('A', 'D'): (2 months, 0)
+ }
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A dictionary mapping each pair of activities to a tuple of (average time difference, standard deviation).
+ :rtype: ``Dict[Tuple[str, str], Tuple[float, float]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ temporal_profile = pm4py.discover_temporal_profile(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.discovery.temporal_profile import (
+ algorithm as temporal_profile_discovery,
+ )
+
+ return temporal_profile_discovery.apply(log, parameters=properties)
+
+
+def discover_log_skeleton(
+ log: Union[EventLog, pd.DataFrame],
+ noise_threshold: float = 0.0,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Dict[str, Any]:
+ """
+ Discovers a Log Skeleton from an event log.
+
+ A Log Skeleton is a declarative model consisting of six different constraints:
+ - **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'.
+ - **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'.
+ - **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'.
+ - **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'.
+ - **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'.
+ - **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'.
+
+ Reference paper:
+ Verbeek, H. M. W., and R. Medeiros de Carvalho. "Log skeletons: A classification approach to process discovery." arXiv preprint arXiv:1806.08247 (2018).
+
+ :param log: Event log or Pandas DataFrame.
+ :param noise_threshold: Noise threshold influencing the strictness of constraints (default: 0.0).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A dictionary representing the Log Skeleton with various constraints.
+ :rtype: ``Dict[str, Any]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log_skeleton = pm4py.discover_log_skeleton(
+ dataframe,
+ noise_threshold=0.1,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ properties["noise_threshold"] = noise_threshold
+
+ from pm4py.algo.discovery.log_skeleton import (
+ algorithm as log_skeleton_discovery,
+ )
+
+ return log_skeleton_discovery.apply(log, parameters=properties)
+
+
+def discover_declare(
+ log: Union[EventLog, pd.DataFrame],
+ allowed_templates: Optional[Set[str]] = None,
+ considered_activities: Optional[Set[str]] = None,
+ min_support_ratio: Optional[float] = None,
+ min_confidence_ratio: Optional[float] = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Dict[str, Dict[Any, Dict[str, int]]]:
+ """
+ Discovers a DECLARE model from an event log.
+
+ Reference paper:
+ 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.
+
+ :param log: Event log or Pandas DataFrame.
+ :param allowed_templates: (Optional) Set of DECLARE templates to consider for discovery.
+ :param considered_activities: (Optional) Set of activities to consider for discovery.
+ :param min_support_ratio: (Optional) Minimum percentage of cases for which the discovered rules apply.
+ :param min_confidence_ratio: (Optional) Minimum percentage of cases for which the discovered rules are valid, based on the rule's support.
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A dictionary representing the discovered DECLARE model with constraints and their parameters.
+ :rtype: ``Dict[str, Dict[Any, Dict[str, int]]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ declare_model = pm4py.discover_declare(log)
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ properties["allowed_templates"] = allowed_templates
+ properties["considered_activities"] = considered_activities
+ properties["min_support_ratio"] = min_support_ratio
+ properties["min_confidence_ratio"] = min_confidence_ratio
+
+ from pm4py.algo.discovery.declare import algorithm as declare_discovery
+
+ return declare_discovery.apply(log, parameters=properties)
+
+
+def discover_powl(
+ log: Union[EventLog, pd.DataFrame],
+ variant=None,
+ filtering_weight_factor: float = 0.0,
+ order_graph_filtering_threshold: float = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> POWL:
+ """
+ Discovers a POWL (Partially Ordered Workflow Language) model from an event log.
+
+ Reference paper:
+ Kourani, Humam, and Sebastiaan J. van Zelst. "POWL: partially ordered workflow language." International Conference on Business Process Management. Cham: Springer Nature Switzerland, 2023.
+
+ :param log: Event log or Pandas DataFrame.
+ :param variant: Variant of the POWL discovery algorithm to use.
+ :param filtering_weight_factor: Factoring threshold for filtering weights, accepts values 0 <= x < 1 (default: 0.0).
+ :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).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :return: A POWL object representing the discovered POWL model.
+ :rtype: ``POWL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
+ powl_model = pm4py.discover_powl(
+ log,
+ activity_key='concept:name'
+ )
+ print(powl_model)
+ """
+ from pm4py.algo.discovery.powl.inductive.variants.dynamic_clustering_frequency.dynamic_clustering_frequency_partial_order_cut import (
+ ORDER_FREQUENCY_RATIO, )
+ from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import (
+ POWLDiscoveryVariant, )
+
+ if variant is None:
+ variant = POWLDiscoveryVariant.MAXIMAL
+
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ #import pm4py
+ #log = pm4py.convert_to_event_log(log, case_id_key=case_id_key)
+ properties = get_properties(log, activity_key=activity_key, timestamp_key=timestamp_key)
+
+ if order_graph_filtering_threshold is not None:
+ if variant is POWLDiscoveryVariant.DYNAMIC_CLUSTERING:
+ properties[ORDER_FREQUENCY_RATIO] = order_graph_filtering_threshold
+ else:
+ raise Exception(
+ "The order graph filtering threshold can only be used for the DYNAMIC_CLUSTERING variant."
+ )
+
+ properties["filtering_threshold"] = filtering_weight_factor
+
+ from pm4py.algo.discovery.powl import algorithm as powl_discovery
+
+ return powl_discovery.apply(log, variant=variant, parameters=properties)
+
+
+def discover_batches(
+ log: Union[EventLog, pd.DataFrame],
+ merge_distance: int = 15 * 60,
+ min_batch_size: int = 2,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ resource_key: str = "org:resource",
+) -> List[Tuple[Tuple[str, str], int, Dict[str, Any]]]:
+ """
+ Discovers batches from the provided log.
+
+ An activity is executed in batches by a given resource when the resource performs the same activity multiple times in a short period.
+ Identifying such activities may highlight repetitive tasks that could be automated.
+
+ The following batch categories are detected:
+ - **Simultaneous**: All events in the batch have identical start and end timestamps.
+ - **Batching at Start**: All events in the batch have identical start timestamps.
+ - **Batching at End**: All events in the batch have identical end timestamps.
+ - **Sequential Batching**: Consecutive events have the end of the first equal to the start of the second.
+ - **Concurrent Batching**: Consecutive events that do not match sequentially.
+
+ Reference paper:
+ 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).
+
+ :param log: Event log or Pandas DataFrame.
+ :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).
+ :param min_batch_size: Minimum number of events required to form a batch (default: 2).
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
+ :param resource_key: Attribute to be used as resource (default: "org:resource").
+ :return: A sorted list of tuples, each containing:
+ - The (activity, resource) pair.
+ - The number of batches for the given activity-resource.
+ - A dictionary with batch details.
+ :rtype: ``List[Tuple[Tuple[str, str], int, Dict[str, Any]]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ batches = pm4py.discover_batches(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp',
+ resource_key='org:resource'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ resource_key=resource_key,
+ )
+ properties["merge_distance"] = merge_distance
+ properties["min_batch_size"] = min_batch_size
+
+ from pm4py.algo.discovery.batches import algorithm as batches_discovery
+
+ return batches_discovery.apply(log, parameters=properties)
+
+
+def correlation_miner(
+ df: pd.DataFrame,
+ annotation: str = "frequency",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+) -> Tuple[dict, dict, dict]:
+ """
+ Applies the Correlation Miner to 'discover' the frequency/performance DFG from an event log without case ID.
+
+ The approach is described in:
+ Pourmirza, Shaya, Remco Dijkman, and Paul Grefen. "Correlation miner: mining business process models and event
+ correlations without case identifiers." International Journal of Cooperative Information Systems 26.02 (2017):
+ 1742002.
+
+ :param log: Pandas dataframe
+ :param annotation: annotation ('frequency' for the frequency DFG, or 'performance' for the performance DFG)
+ :param activity_key: attribute to be used for the activity
+ :param timestamp_key: attribute to be used for the timestamp
+ :rtype: ``Tuple[dict, dict, dict]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+ log = log[["concept:name", "time:timestamp"]]
+
+ dfg, sa, ea = pm4py.correlation_miner(log)
+ pm4py.view_dfg(dfg, sa, ea, format="svg")
+
+ perf_dfg, sa, ea = pm4py.correlation_miner(log, annotation="performance")
+ pm4py.view_performance_dfg(perf_dfg, sa, ea, format="svg")
+ """
+ properties = get_properties(
+ df, activity_key=activity_key, timestamp_key=timestamp_key
+ )
+
+ if is_polars_lazyframe(df):
+ if importlib.util.find_spec("polars") is None:
+ raise RuntimeError(
+ "Polars LazyFrame provided but 'polars' package is not installed."
+ )
+
+ import polars as pl # type: ignore[import-untyped]
+
+ if activity_key not in df.columns:
+ raise Exception(
+ f"Column '{activity_key}' is not present in the provided Polars LazyFrame."
+ )
+
+ first_row = (
+ df.select(pl.col(activity_key))
+ .head(1)
+ .collect()
+ )
+ if first_row.height == 0:
+ raise ValueError("The provided Polars LazyFrame must contain at least one event.")
+ first_activity = first_row[activity_key].to_list()[0]
+
+ last_row = (
+ df.select(pl.col(activity_key))
+ .tail(1)
+ .collect()
+ )
+ last_activity = last_row[activity_key].to_list()[0]
+ else:
+ # code for Pandas dataframes
+ first_activity = df[activity_key].iloc[0]
+ last_activity = df[activity_key].iloc[-1]
+
+ from pm4py.algo.discovery.correlation_mining import (
+ algorithm as correlation_miner,
+ )
+
+ dfg, perf_dfg = correlation_miner.apply(df, parameters=properties)
+ perf_dfg = {a: float(y) for a, y in perf_dfg.items()}
+
+ activities_entering = Counter()
+ activities_exiting = Counter()
+
+ for edge, freq in dfg.items():
+ activities_exiting[edge[0]] += freq
+ activities_entering[edge[1]] += freq
+
+ start_activities = {first_activity: activities_exiting[first_activity]}
+ end_activities = {last_activity: activities_entering[last_activity]}
+
+ if annotation == "frequency":
+ return dfg, start_activities, end_activities
+ else:
+ return perf_dfg, start_activities, end_activities
+
+
+def discover_otg(
+ ocel: OCEL,
+ variant=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Tuple[Set[str], Dict[Tuple[str, str, str], int]]:
+ """
+ Discovers an Object-Type Graph (OTG) from an object-centric event log.
+
+ Published in: https://publications.rwth-aachen.de/record/1014107
+
+ An OTG summarizes how object types are related across different interaction graphs extracted from the OCEL.
+ Specifically, an OTG is a tuple containing:
+ - The set of object types
+ - The edges along with the frequency, where each edge is (object_type1, relationship, object_type2).
+
+ Relationship can be:
+ * object_interaction (objects related in some event)
+ * object_descendants (lifecycle of the first event starts before the other object)
+ * object_inheritance (lifecycle of the first object ends exactly when the second one starts)
+ * object_cobirth (objects start their lifecycle in the same event)
+ * object_codeath (objects end their lifecycle in the sae event)
+
+ :param ocel: Object-centric event log.
+ :param variant: Variant of the OTG discovery algorithm to use (default: classic variant).
+ :param parameters: Optional variant-specific parameters.
+ :return: Tuple containing the set of object types and the OTG edges with their frequencies.
+ :rtype: ``Tuple[Set[str], Dict[Tuple[str, str, str], int]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ otg = pm4py.discover_otg(ocel)
+ """
+ from pm4py.algo.discovery.ocel.otg import algorithm as otg_discovery
+
+ if variant is None:
+ variant = otg_discovery.Variants.CLASSIC
+
+ return otg_discovery.apply(ocel, variant=variant, parameters=parameters)
+
+
+def discover_etot(
+ ocel: OCEL,
+ variant=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Tuple[
+ Set[str],
+ Set[str],
+ Set[Tuple[str, str]],
+ Dict[Tuple[str, str], int],
+]:
+ """
+ Discovers the ET-OT (Event Type - Object Type) graph from an object-centric event log.
+
+ Published in: https://publications.rwth-aachen.de/record/1014107
+
+ The ET-OT graph captures the relationships between event types and object types along with their frequencies.
+ Specifically, an ET-OT graph is a tuple consisting of:
+ - Set of activities
+ - Set of object types
+ - Set of relationships, where an edge (a, ot) indicates that events of type a are associated with objects of type ot
+ - A dictionary associating each relationship to a weight (frequency)
+
+ :param ocel: Object-centric event log.
+ :param variant: Variant of the ET-OT discovery algorithm to use (default: classic variant).
+ :param parameters: Optional variant-specific parameters.
+ :return: Tuple containing the set of activities, the set of object types, the ET-OT edges, and their frequencies.
+ :rtype: ``Tuple[Set[str], Set[str], Set[Tuple[str, str]], Dict[Tuple[str, str], int]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ etot = pm4py.discover_etot(ocel)
+ """
+ from pm4py.algo.discovery.ocel.etot import algorithm as etot_discovery
+
+ if variant is None:
+ variant = etot_discovery.Variants.CLASSIC
+
+ return etot_discovery.apply(ocel, variant=variant, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/filtering.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/filtering.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e5c10e565a568ce3a372b2a0022fbcd19cdc960
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/filtering.py
@@ -0,0 +1,2230 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+The ``pm4py.filtering`` module contains the filtering features offered in ``pm4py``.
+"""
+
+from typing import Union, Set, List, Tuple, Collection, Any, Dict, Optional
+from collections import Counter
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog
+from pm4py.util import constants, xes_constants, pandas_utils, nx_utils
+import warnings
+from pm4py.util.pandas_utils import (
+ check_is_pandas_dataframe,
+ check_pandas_dataframe_columns,
+)
+from pm4py.utils import (
+ get_properties,
+ __event_log_deprecation_warning,
+ is_polars_lazyframe,
+)
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.utils import __event_log_filtering_level_warning
+import datetime
+
+
+def _get_dataframe_filtering_package(df):
+ if is_polars_lazyframe(df):
+ import pm4py.algo.filtering.polars as filtering_pkg
+ else:
+ import pm4py.algo.filtering.pandas as filtering_pkg
+
+ return filtering_pkg
+
+
+def _is_dataframe_like(obj):
+ return check_is_pandas_dataframe(obj) or is_polars_lazyframe(obj)
+
+
+def _normalize_sequence_argument(value):
+ """Normalize a prefix/suffix input into the list-of-list structure expected by Polars filters."""
+ if isinstance(value, str):
+ return [[value]]
+ if isinstance(value, (list, tuple)):
+ if value and all(isinstance(elem, (list, tuple)) for elem in value):
+ return [list(elem) if isinstance(elem, tuple) else list(elem) for elem in value]
+ if all(isinstance(elem, str) for elem in value):
+ return [list(value)]
+ return [[str(value)]]
+
+
+def filter_log_relative_occurrence_event_attribute(
+ log: Union[EventLog, pd.DataFrame],
+ min_relative_stake: float,
+ attribute_key: str = xes_constants.DEFAULT_NAME_KEY,
+ level: str = "cases",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the event log, keeping only the events that have an attribute value which occurs:
+ - in at least the specified (min_relative_stake) percentage of events when level="events",
+ - in at least the specified (min_relative_stake) percentage of cases when level="cases".
+
+ :param log: Event log or Pandas DataFrame.
+ :param min_relative_stake: Minimum percentage of cases (expressed as a number between 0 and 1) in which the attribute should occur.
+ :param attribute_key: The attribute to filter.
+ :param level: The level of the filter (if level="events", then events; if level="cases", then cases).
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_log_relative_occurrence_event_attribute(
+ dataframe,
+ 0.5,
+ attribute_key='concept:name',
+ level='cases',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ activity_key=attribute_key,
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ attributes_filter = filtering_pkg.attributes.attributes_filter
+
+ parameters[attributes_filter.Parameters.ATTRIBUTE_KEY] = attribute_key
+ parameters[attributes_filter.Parameters.KEEP_ONCE_PER_CASE] = (
+ True if level == "cases" else False
+ )
+ return attributes_filter.filter_df_relative_occurrence_event_attribute(
+ log, min_relative_stake, parameters=parameters
+ )
+ else:
+ from pm4py.algo.filtering.log.attributes import attributes_filter
+
+ parameters[attributes_filter.Parameters.ATTRIBUTE_KEY] = attribute_key
+ parameters[attributes_filter.Parameters.KEEP_ONCE_PER_CASE] = (
+ True if level == "cases" else False
+ )
+ return (
+ attributes_filter.filter_log_relative_occurrence_event_attribute(
+ log, min_relative_stake, parameters=parameters
+ )
+ )
+
+
+def filter_start_activities(
+ log: Union[EventLog, pd.DataFrame],
+ activities: Union[Set[str], List[str]],
+ retain: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters cases that have a start activity in the provided list.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activities: Collection of start activities.
+ :param retain: If True, retains the traces containing the given start activities; if False, drops the traces.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_start_activities(
+ dataframe,
+ ['Act. A'],
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ start_activities_filter = (
+ filtering_pkg.start_activities.start_activities_filter
+ )
+
+ parameters[start_activities_filter.Parameters.POSITIVE] = retain
+ return start_activities_filter.apply(
+ log, activities, parameters=parameters
+ )
+ else:
+ from pm4py.algo.filtering.log.start_activities import (
+ start_activities_filter,
+ )
+
+ parameters[start_activities_filter.Parameters.POSITIVE] = retain
+ return start_activities_filter.apply(
+ log, activities, parameters=parameters
+ )
+
+
+def filter_end_activities(
+ log: Union[EventLog, pd.DataFrame],
+ activities: Union[Set[str], List[str]],
+ retain: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters cases that have an end activity in the provided list.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activities: Collection of end activities.
+ :param retain: If True, retains the traces containing the given end activities; if False, drops the traces.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_end_activities(
+ dataframe,
+ ['Act. Z'],
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ end_activities_filter = (
+ filtering_pkg.end_activities.end_activities_filter
+ )
+
+ parameters[end_activities_filter.Parameters.POSITIVE] = retain
+ return end_activities_filter.apply(
+ log, activities, parameters=parameters
+ )
+ else:
+ from pm4py.algo.filtering.log.end_activities import (
+ end_activities_filter,
+ )
+
+ parameters[end_activities_filter.Parameters.POSITIVE] = retain
+ return end_activities_filter.apply(
+ log, activities, parameters=parameters
+ )
+
+
+def filter_event_attribute_values(
+ log: Union[EventLog, pd.DataFrame],
+ attribute_key: str,
+ values: Union[Set[str], List[str]],
+ level: Optional[str] = None,
+ retain: bool = True,
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters a log object based on the values of a specified event attribute.
+
+ :param log: Event log or Pandas DataFrame.
+ :param attribute_key: Attribute to filter.
+ :param values: Admitted or forbidden values.
+ :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).
+ :param retain: Specifies if the values should be kept or removed.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_event_attribute_values(
+ dataframe,
+ 'concept:name',
+ ['Act. A', 'Act. Z'],
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if level is None:
+ __event_log_filtering_level_warning()
+
+ parameters = get_properties(log, case_id_key=case_id_key)
+ parameters[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = attribute_key
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ attributes_filter = filtering_pkg.attributes.attributes_filter
+
+ if level == "event":
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
+ return attributes_filter.apply_events(
+ log, values, parameters=parameters
+ )
+ elif level == "case":
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
+ return attributes_filter.apply(log, values, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.attributes import attributes_filter
+
+ if level == "event":
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
+ return attributes_filter.apply_events(
+ log, values, parameters=parameters
+ )
+ elif level == "case":
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
+ return attributes_filter.apply(log, values, parameters=parameters)
+
+
+def filter_trace_attribute_values(
+ log: Union[EventLog, pd.DataFrame],
+ attribute_key: str,
+ values: Union[Set[str], List[str]],
+ retain: bool = True,
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters a log based on the values of a specified trace attribute.
+
+ :param log: Event log or Pandas DataFrame.
+ :param attribute_key: Attribute to filter.
+ :param values: Collection of values to filter.
+ :param retain: Boolean value indicating whether to keep or discard matching traces.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_trace_attribute_values(
+ dataframe,
+ 'case:creator',
+ ['Mike'],
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(log, case_id_key=case_id_key)
+ parameters[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = attribute_key
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ attributes_filter = filtering_pkg.attributes.attributes_filter
+
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
+ return attributes_filter.apply(log, values, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.attributes import attributes_filter
+
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
+ return attributes_filter.apply_trace_attribute(
+ log, values, parameters=parameters
+ )
+
+
+def filter_variants(
+ log: Union[EventLog, pd.DataFrame],
+ variants: Union[Set[str], List[str], List[Tuple[str]]],
+ retain: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters a log based on a specified set of variants.
+
+ :param log: Event log or Pandas DataFrame.
+ :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')].
+ :param retain: Boolean indicating whether to retain (if True) or remove (if False) traces conforming to the specified variants.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_variants(
+ dataframe,
+ [('Act. A', 'Act. B', 'Act. Z'), ('Act. A', 'Act. C', 'Act. Z')],
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ from pm4py.util import variants_util
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ variants_filter = filtering_pkg.variants.variants_filter
+
+ parameters[variants_filter.Parameters.POSITIVE] = retain
+ return variants_filter.apply(log, variants, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.variants import variants_filter
+
+ parameters[variants_filter.Parameters.POSITIVE] = retain
+ return variants_filter.apply(log, variants, parameters=parameters)
+
+
+def filter_directly_follows_relation(
+ log: Union[EventLog, pd.DataFrame],
+ relations: List[str],
+ retain: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Retains traces that contain any of the specified 'directly follows' relations.
+ For example, if relations == [('a','b'),('a','c')] and log [,,],
+ the resulting log will contain traces describing [,].
+
+ :param log: Event log or Pandas DataFrame.
+ :param relations: List of activity name pairs, representing allowed or forbidden paths.
+ :param retain: Boolean indicating whether the paths should be kept (if True) or removed (if False).
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_directly_follows_relation(
+ dataframe,
+ [('A', 'B'), ('A', 'C')],
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ paths_filter = filtering_pkg.paths.paths_filter
+
+ parameters[paths_filter.Parameters.POSITIVE] = retain
+ return paths_filter.apply(log, relations, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.paths import paths_filter
+
+ parameters[paths_filter.Parameters.POSITIVE] = retain
+ return paths_filter.apply(log, relations, parameters=parameters)
+
+
+def filter_eventually_follows_relation(
+ log: Union[EventLog, pd.DataFrame],
+ relations: List[str],
+ retain: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Retains traces that contain any of the specified 'eventually follows' relations.
+ For example, if relations == [('a','b'),('a','c')] and log [,,],
+ the resulting log will contain traces describing [,,].
+
+ :param log: Event log or Pandas DataFrame.
+ :param relations: List of activity name pairs, representing allowed or forbidden paths.
+ :param retain: Boolean indicating whether the paths should be kept (if True) or removed (if False).
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_eventually_follows_relation(
+ dataframe,
+ [('A', 'B'), ('A', 'C')],
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ ltl_checker = filtering_pkg.ltl.ltl_checker
+
+ parameters[ltl_checker.Parameters.POSITIVE] = retain
+
+ if not is_polars_lazyframe(log):
+ if retain:
+ cases = set()
+ else:
+ cases = set(log[case_id_key].to_numpy().tolist())
+ for path in relations:
+ filt_log = ltl_checker.eventually_follows(
+ log, path, parameters=parameters
+ )
+ this_traces = set(filt_log[case_id_key].to_numpy().tolist())
+ if retain:
+ cases = cases.union(this_traces)
+ else:
+ cases = cases.intersection(this_traces)
+ return log[log[case_id_key].isin(cases)]
+ else:
+ import polars as pl # type: ignore[import-untyped]
+
+ case_frames = []
+ for path in relations:
+ filt_log = ltl_checker.eventually_follows(
+ log, path, parameters=parameters
+ )
+ case_frames.append(
+ filt_log.select(pl.col(case_id_key)).unique()
+ )
+
+ if retain:
+ if not case_frames:
+ return log.filter(pl.lit(False))
+ cases_frame = pl.concat(case_frames).unique()
+ return log.join(cases_frame, on=case_id_key, how="inner", maintain_order="left")
+ else:
+ if not case_frames:
+ return log
+ cases_frame = case_frames[0]
+ for frame in case_frames[1:]:
+ cases_frame = cases_frame.join(
+ frame, on=case_id_key, how="inner",
+ maintain_order="left",
+ )
+ return log.join(cases_frame, on=case_id_key, how="inner", maintain_order="left")
+ else:
+ from pm4py.algo.filtering.log.ltl import ltl_checker
+
+ parameters[ltl_checker.Parameters.POSITIVE] = retain
+ if retain:
+ cases = set()
+ else:
+ cases = set(id(trace) for trace in log)
+ for path in relations:
+ filt_log = ltl_checker.eventually_follows(
+ log, path, parameters=parameters
+ )
+ this_traces = set(id(trace) for trace in filt_log)
+ if retain:
+ cases = cases.union(this_traces)
+ else:
+ cases = cases.intersection(this_traces)
+ filtered_log = EventLog(
+ attributes=log.attributes,
+ extensions=log.extensions,
+ omni_present=log.omni_present,
+ classifiers=log.classifiers,
+ properties=log.properties,
+ )
+ for trace in log:
+ if id(trace) in cases:
+ filtered_log.append(trace)
+ return filtered_log
+
+
+def filter_time_range(
+ log: Union[EventLog, pd.DataFrame],
+ dt1: str,
+ dt2: str,
+ mode: str = "events",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters a log based on a time interval.
+
+ :param log: Event log or Pandas DataFrame.
+ :param dt1: Left extreme of the interval.
+ :param dt2: Right extreme of the interval.
+ :param mode: Modality of filtering. Supported:
+ - 'events': keep events within timeframe.
+ - 'traces_contained': keep traces fully contained in timeframe.
+ - 'traces_intersecting': keep traces intersecting timeframe.
+ - 'traces_starting_in': keep traces whose first event is in timeframe.
+ - 'traces_starting_in_exclude': exclude traces whose first event is in timeframe.
+ - 'traces_completing_in': keep traces whose last event is in timeframe.
+ - 'traces_completing_in_exclude': exclude traces whose last event is in timeframe.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
+ )
+
+ # Helper: compute "positive" flag from mode for the new variants
+ def _positive_from_mode(m: str) -> bool:
+ return not (m.endswith("_exclude"))
+
+ if _is_dataframe_like(log):
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ timestamp_filter = filtering_pkg.timestamp.timestamp_filter
+
+ if mode == "events":
+ return timestamp_filter.apply_events(
+ log, dt1, dt2, parameters=properties
+ )
+ elif mode == "traces_contained":
+ return timestamp_filter.filter_traces_contained(
+ log, dt1, dt2, parameters=properties
+ )
+ elif mode == "traces_intersecting":
+ return timestamp_filter.filter_traces_intersecting(
+ log, dt1, dt2, parameters=properties
+ )
+ elif mode in ("traces_starting_in", "traces_starting_in_exclude"):
+ params = dict(properties)
+ params["positive"] = _positive_from_mode(mode)
+ return timestamp_filter.filter_traces_starting_in_timeframe(
+ log, dt1, dt2, parameters=params
+ )
+ elif mode in ("traces_completing_in", "traces_completing_in_exclude"):
+ params = dict(properties)
+ params["positive"] = _positive_from_mode(mode)
+ return timestamp_filter.filter_traces_completing_in_timeframe(
+ log, dt1, dt2, parameters=params
+ )
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ f"Mode provided: {mode} is not recognized; original log returned!"
+ )
+ return log
+ else:
+ from pm4py.algo.filtering.log.timestamp import timestamp_filter
+
+ if mode == "events":
+ return timestamp_filter.apply_events(
+ log, dt1, dt2, parameters=properties
+ )
+ elif mode == "traces_contained":
+ return timestamp_filter.filter_traces_contained(
+ log, dt1, dt2, parameters=properties
+ )
+ elif mode == "traces_intersecting":
+ return timestamp_filter.filter_traces_intersecting(
+ log, dt1, dt2, parameters=properties
+ )
+ elif mode in ("traces_starting_in", "traces_starting_in_exclude"):
+ params = dict(properties)
+ params["positive"] = _positive_from_mode(mode)
+ return timestamp_filter.filter_traces_starting_in_timeframe(
+ log, dt1, dt2, parameters=params
+ )
+ elif mode in ("traces_completing_in", "traces_completing_in_exclude"):
+ params = dict(properties)
+ params["positive"] = _positive_from_mode(mode)
+ return timestamp_filter.filter_traces_completing_in_timeframe(
+ log, dt1, dt2, parameters=params
+ )
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ f"Mode provided: {mode} is not recognized; original log returned!"
+ )
+ return log
+
+
+def filter_between(
+ log: Union[EventLog, pd.DataFrame],
+ act1: Union[str, List[str]],
+ act2: Union[str, List[str]],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Finds all the sub-cases leading from an event with activity "act1" to an event with activity "act2" in the log,
+ and returns a log containing only them.
+
+ Example:
+
+ Log
+ A B C D E F
+ A B E F C
+ A B F C B C B E F C
+
+ act1 = B
+ act2 = C
+
+ Returned sub-cases:
+ B C (from the first case)
+ B E F C (from the second case)
+ B F C (from the third case)
+ B C (from the third case)
+ B E F C (from the third case)
+
+ :param log: Event log or Pandas DataFrame.
+ :param act1: Source activity or collection of activities.
+ :param act2: Target activity or collection of activities.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_between(
+ dataframe,
+ 'A',
+ 'D',
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ between_filter = filtering_pkg.between.between_filter
+
+ return between_filter.apply(log, act1, act2, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.between import between_filter
+
+ return between_filter.apply(log, act1, act2, parameters=parameters)
+
+
+def filter_case_size(
+ log: Union[EventLog, pd.DataFrame],
+ min_size: int,
+ max_size: int,
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the event log, keeping cases that have a length (number of events) between min_size and max_size.
+
+ :param log: Event log or Pandas DataFrame.
+ :param min_size: Minimum allowed number of events.
+ :param max_size: Maximum allowed number of events.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_case_size(
+ dataframe,
+ 5,
+ 10,
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(log, case_id_key=case_id_key)
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ case_filter = filtering_pkg.cases.case_filter
+
+ case_id = (
+ parameters[constants.PARAMETER_CONSTANT_CASEID_KEY]
+ if constants.PARAMETER_CONSTANT_CASEID_KEY in parameters
+ else constants.CASE_CONCEPT_NAME
+ )
+ return case_filter.filter_on_case_size(
+ log, case_id, min_size, max_size
+ )
+ else:
+ from pm4py.algo.filtering.log.cases import case_filter
+
+ return case_filter.filter_on_case_size(log, min_size, max_size)
+
+
+def filter_case_performance(
+ log: Union[EventLog, pd.DataFrame],
+ min_performance: float,
+ max_performance: float,
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the event log, keeping cases that have a duration (the timestamp of the last event minus the timestamp
+ of the first event) between min_performance and max_performance.
+
+ :param log: Event log or Pandas DataFrame.
+ :param min_performance: Minimum allowed case duration.
+ :param max_performance: Maximum allowed case duration.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_case_performance(
+ dataframe,
+ 3600.0,
+ 86400.0,
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ case_filter = filtering_pkg.cases.case_filter
+
+ return case_filter.filter_case_performance(
+ log, min_performance, max_performance, parameters=parameters
+ )
+ else:
+ from pm4py.algo.filtering.log.cases import case_filter
+
+ return case_filter.filter_case_performance(
+ log, min_performance, max_performance, parameters=parameters
+ )
+
+
+def filter_activities_rework(
+ log: Union[EventLog, pd.DataFrame],
+ activity: str,
+ min_occurrences: int = 2,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the event log, keeping cases where the specified activity occurs at least min_occurrences times.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity: Activity to consider.
+ :param min_occurrences: Minimum desired number of occurrences.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_activities_rework(
+ dataframe,
+ 'Approve Order',
+ 2,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["min_occurrences"] = min_occurrences
+ is_polars = is_polars_lazyframe(log)
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ rework_filter = filtering_pkg.rework.rework_filter
+
+ if is_polars:
+ if hasattr(rework_filter, "apply_activity_set"):
+ return rework_filter.apply_activity_set(
+ log, {activity}, parameters=parameters
+ )
+ return rework_filter.apply(log, parameters=parameters)
+
+ return rework_filter.apply(log, activity, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.rework import rework_filter
+
+ return rework_filter.apply(log, activity, parameters=parameters)
+
+
+def filter_paths_performance(
+ log: Union[EventLog, pd.DataFrame],
+ path: Tuple[str, str],
+ min_performance: float,
+ max_performance: float,
+ keep: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the event log based on the performance of specified paths.
+
+ - If keep=True, retains cases having the specified path (tuple of 2 activities) with a duration between min_performance and max_performance.
+ - If keep=False, discards cases having the specified path with a duration between min_performance and max_performance.
+
+ :param log: Event log or Pandas DataFrame.
+ :param path: Tuple of two activities (source_activity, target_activity).
+ :param min_performance: Minimum allowed performance of the path.
+ :param max_performance: Maximum allowed performance of the path.
+ :param keep: Boolean indicating whether to keep (if True) or discard (if False) the cases with the specified performance.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_paths_performance(
+ dataframe,
+ ('A', 'D'),
+ 3600.0,
+ 86400.0,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["positive"] = keep
+ parameters["min_performance"] = min_performance
+ parameters["max_performance"] = max_performance
+
+ path = tuple(path)
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ paths_filter = filtering_pkg.paths.paths_filter
+
+ return paths_filter.apply_performance(log, path, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.paths import paths_filter
+
+ return paths_filter.apply_performance(log, path, parameters=parameters)
+
+
+def filter_variants_top_k(
+ log: Union[EventLog, pd.DataFrame],
+ k: int,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Keeps the top-k variants of the log.
+
+ :param log: Event log or Pandas DataFrame.
+ :param k: Number of variants to keep.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_variants_top_k(
+ dataframe,
+ 5,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ variants_filter = filtering_pkg.variants.variants_filter
+
+ return variants_filter.filter_variants_top_k(
+ log, k, parameters=parameters
+ )
+ else:
+ from pm4py.algo.filtering.log.variants import variants_filter
+
+ return variants_filter.filter_variants_top_k(
+ log, k, parameters=parameters
+ )
+
+
+def filter_variants_by_coverage_percentage(
+ log: Union[EventLog, pd.DataFrame],
+ min_coverage_percentage: float,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the variants of the log based on a coverage percentage.
+ For example, if min_coverage_percentage=0.4 and the log has 1000 cases with:
+ - 500 cases of variant 1,
+ - 400 cases of variant 2,
+ - 100 cases of variant 3,
+ the filter keeps only the traces of variant 1 and variant 2.
+
+ :param log: Event log or Pandas DataFrame.
+ :param min_coverage_percentage: Minimum allowed percentage of coverage.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_variants_by_coverage_percentage(
+ dataframe,
+ 0.1,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ variants_filter = filtering_pkg.variants.variants_filter
+
+ return variants_filter.filter_variants_by_coverage_percentage(
+ log, min_coverage_percentage, parameters=parameters
+ )
+ else:
+ from pm4py.algo.filtering.log.variants import variants_filter
+
+ return variants_filter.filter_variants_by_coverage_percentage(
+ log, min_coverage_percentage, parameters=parameters
+ )
+
+
+def filter_prefixes(
+ log: Union[EventLog, pd.DataFrame],
+ activity: str,
+ strict: bool = True,
+ first_or_last: str = "first",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the log, keeping the prefixes leading up to a given activity.
+ For example, for a log with traces:
+ - A,B,C,D
+ - A,B,Z,A,B,C,D
+ - A,B,C,D,C,E,C,F
+
+ The prefixes to "C" are respectively:
+ - A,B
+ - A,B,Z,A,B
+ - A,B
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity: Target activity for the filter.
+ :param strict: Applies the filter strictly, cutting the occurrences of the selected activity.
+ :param first_or_last: Decides if the first or last occurrence of an activity should be selected as the baseline for the filter.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_prefixes(
+ dataframe,
+ 'Act. C',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["strict"] = strict
+ parameters["first_or_last"] = first_or_last
+
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ prefix_filter = filtering_pkg.prefixes.prefix_filter
+ prefixes_arg = (
+ _normalize_sequence_argument(activity)
+ if is_polars_lazyframe(log)
+ else activity
+ )
+
+ return prefix_filter.apply(log, prefixes_arg, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.prefixes import prefix_filter
+
+ return prefix_filter.apply(log, activity, parameters=parameters)
+
+
+def filter_suffixes(
+ log: Union[EventLog, pd.DataFrame],
+ activity: str,
+ strict: bool = True,
+ first_or_last: str = "first",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the log, keeping the suffixes starting from a given activity.
+ For example, for a log with traces:
+ - A,B,C,D
+ - A,B,Z,A,B,C,D
+ - A,B,C,D,C,E,C,F
+
+ The suffixes from "C" are respectively:
+ - D
+ - D
+ - D,C,E,C,F
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity: Target activity for the filter.
+ :param strict: Applies the filter strictly, cutting the occurrences of the selected activity.
+ :param first_or_last: Decides if the first or last occurrence of an activity should be selected as the baseline for the filter.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_suffixes(
+ dataframe,
+ 'Act. C',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["strict"] = strict
+ parameters["first_or_last"] = first_or_last
+
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ suffix_filter = filtering_pkg.suffixes.suffix_filter
+ suffixes_arg = (
+ _normalize_sequence_argument(activity)
+ if is_polars_lazyframe(log)
+ else activity
+ )
+
+ return suffix_filter.apply(log, suffixes_arg, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.suffixes import suffix_filter
+
+ return suffix_filter.apply(log, activity, parameters=parameters)
+
+
+def filter_ocel_event_attribute(
+ ocel: OCEL,
+ attribute_key: str,
+ attribute_values: Collection[Any],
+ positive: bool = True,
+) -> OCEL:
+ """
+ Filters the object-centric event log based on the provided event attribute values.
+
+ :param ocel: Object-centric event log.
+ :param attribute_key: Attribute at the event level to filter.
+ :param attribute_values: Collection of attribute values to keep or remove.
+ :param positive: Determines whether the values should be kept (True) or removed (False).
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_event_attribute(
+ ocel,
+ 'ocel:activity',
+ ['A', 'B', 'D']
+ )
+ """
+ from pm4py.algo.filtering.ocel import event_attributes
+
+ return event_attributes.apply(
+ ocel,
+ attribute_values,
+ parameters={
+ event_attributes.Parameters.ATTRIBUTE_KEY: attribute_key,
+ event_attributes.Parameters.POSITIVE: positive,
+ },
+ )
+
+
+def filter_ocel_object_attribute(
+ ocel: OCEL,
+ attribute_key: str,
+ attribute_values: Collection[Any],
+ positive: bool = True,
+) -> OCEL:
+ """
+ Filters the object-centric event log based on the provided object attribute values.
+
+ :param ocel: Object-centric event log.
+ :param attribute_key: Attribute at the object level to filter.
+ :param attribute_values: Collection of attribute values to keep or remove.
+ :param positive: Determines whether the values should be kept (True) or removed (False).
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_object_attribute(
+ ocel,
+ 'ocel:type',
+ ['order']
+ )
+ """
+ from pm4py.algo.filtering.ocel import object_attributes
+
+ return object_attributes.apply(
+ ocel,
+ attribute_values,
+ parameters={
+ object_attributes.Parameters.ATTRIBUTE_KEY: attribute_key,
+ object_attributes.Parameters.POSITIVE: positive,
+ },
+ )
+
+
+def filter_ocel_object_types_allowed_activities(
+ ocel: OCEL, correspondence_dict: Dict[str, Collection[str]]
+) -> OCEL:
+ """
+ Filters an object-centric event log, keeping only the specified object types with the specified set of allowed activities.
+
+ :param ocel: Object-centric event log.
+ :param correspondence_dict: Dictionary containing, for every object type of interest, a collection of allowed activities.
+ Example: {"order": ["Create Order"], "element": ["Create Order", "Create Delivery"]}.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_object_types_allowed_activities(
+ ocel,
+ {'order': ['create order', 'pay order'], 'item': ['create item', 'deliver item']}
+ )
+ """
+ from pm4py.algo.filtering.ocel import activity_type_matching
+
+ return activity_type_matching.apply(ocel, correspondence_dict)
+
+
+def filter_ocel_object_per_type_count(
+ ocel: OCEL, min_num_obj_type: Dict[str, int]
+) -> OCEL:
+ """
+ Filters the events of the object-centric logs that are related to at
+ least the specified number of objects per type.
+
+ Example::
+
+ pm4py.filter_object_per_type_count(ocel, {"order": 1, "element": 2})
+
+ Would keep the following events::
+
+ ocel:eid ocel:timestamp ocel:activity ocel:type:element ocel:type:order
+ 0 e1 1980-01-01 Create Order [i4, i1, i3, i2] [o1]
+ 1 e11 1981-01-01 Create Order [i6, i5] [o2]
+ 2 e14 1981-01-04 Create Order [i8, i7] [o3]
+
+ :param ocel: Object-centric event log.
+ :param min_num_obj_type: Minimum number of objects per type.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_object_per_type_count(
+ ocel,
+ {'order': 1, 'element': 2}
+ )
+
+ """
+ from pm4py.algo.filtering.ocel import objects_ot_count
+
+ return objects_ot_count.apply(ocel, min_num_obj_type)
+
+
+def filter_ocel_start_events_per_object_type(
+ ocel: OCEL, object_type: str
+) -> OCEL:
+ """
+ Filters the events in which a new object of the given object type is spawned.
+ For example, an event with activity "Create Order" might spawn new orders.
+
+ :param ocel: Object-centric event log.
+ :param object_type: Object type to consider.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_start_events_per_object_type(
+ ocel,
+ 'delivery'
+ )
+ """
+ from pm4py.algo.filtering.ocel import ot_endpoints
+
+ return ot_endpoints.filter_start_events_per_object_type(ocel, object_type)
+
+
+def filter_ocel_end_events_per_object_type(
+ ocel: OCEL, object_type: str
+) -> OCEL:
+ """
+ Filters the events in which an object of the given object type terminates its lifecycle.
+ For example, an event with activity "Pay Order" might terminate an order.
+
+ :param ocel: Object-centric event log.
+ :param object_type: Object type to consider.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_end_events_per_object_type(
+ ocel,
+ 'delivery'
+ )
+ """
+ from pm4py.algo.filtering.ocel import ot_endpoints
+
+ return ot_endpoints.filter_end_events_per_object_type(ocel, object_type)
+
+
+def filter_ocel_events_timestamp(
+ ocel: OCEL,
+ min_timest: Union[datetime.datetime, str],
+ max_timest: Union[datetime.datetime, str],
+ timestamp_key: str = "ocel:timestamp",
+) -> OCEL:
+ """
+ Filters the object-centric event log, keeping events within the provided timestamp range.
+
+ :param ocel: Object-centric event log.
+ :param min_timest: Left extreme of the allowed timestamp interval (format: YYYY-mm-dd HH:MM:SS).
+ :param max_timest: Right extreme of the allowed timestamp interval (format: YYYY-mm-dd HH:MM:SS).
+ :param timestamp_key: The attribute to use as timestamp (default: ocel:timestamp).
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_events_timestamp(
+ ocel,
+ '1990-01-01 00:00:00',
+ '2010-01-01 00:00:00'
+ )
+ """
+ from pm4py.algo.filtering.ocel import event_attributes
+
+ return event_attributes.apply_timestamp(
+ ocel,
+ min_timest,
+ max_timest,
+ parameters={"pm4py:param:timestamp_key": timestamp_key},
+ )
+
+
+def filter_four_eyes_principle(
+ log: Union[EventLog, pd.DataFrame],
+ activity1: str,
+ activity2: str,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ resource_key: str = "org:resource",
+ keep_violations: bool = False,
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters out the cases of the log that violate the four-eyes principle on the provided activities.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity1: First activity.
+ :param activity2: Second activity.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :param resource_key: Attribute to be used as resource.
+ :param keep_violations: Boolean indicating whether to discard (if False) or retain (if True) the violations.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_four_eyes_principle(
+ dataframe,
+ 'Act. A',
+ 'Act. B',
+ activity_key='concept:name',
+ resource_key='org:resource',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ resource_key=resource_key,
+ )
+ properties["positive"] = not keep_violations
+
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ ltl_checker = filtering_pkg.ltl.ltl_checker
+
+ return ltl_checker.four_eyes_principle(
+ log, activity1, activity2, parameters=properties
+ )
+ else:
+ from pm4py.algo.filtering.log.ltl import ltl_checker
+
+ return ltl_checker.four_eyes_principle(
+ log, activity1, activity2, parameters=properties
+ )
+
+
+def filter_activity_done_different_resources(
+ log: Union[EventLog, pd.DataFrame],
+ activity: str,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ resource_key: str = "org:resource",
+ keep_violations: bool = True,
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters the cases where an activity is performed by different resources multiple times.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity: Activity to consider.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :param resource_key: Attribute to be used as resource.
+ :param keep_violations: Boolean indicating whether to discard (if False) or retain (if True) the violations.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_dataframe = pm4py.filter_activity_done_different_resources(
+ dataframe,
+ 'Act. A',
+ activity_key='concept:name',
+ resource_key='org:resource',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ resource_key=resource_key,
+ )
+ properties["positive"] = keep_violations
+
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ ltl_checker = filtering_pkg.ltl.ltl_checker
+
+ return ltl_checker.attr_value_different_persons(
+ log, activity, parameters=properties
+ )
+ else:
+ from pm4py.algo.filtering.log.ltl import ltl_checker
+
+ return ltl_checker.attr_value_different_persons(
+ log, activity, parameters=properties
+ )
+
+
+def filter_trace_segments(
+ log: Union[EventLog, pd.DataFrame],
+ admitted_traces: List[List[str]],
+ positive: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Filters an event log based on a set of trace segments. A trace is a
+ sequence of activities and "...".
+
+ where:
+
+ - "..." before an activity indicates that other activities can precede the given activity.
+ - "..." after an activity indicates that other activities can follow the given activity.
+
+ Examples:
+
+ - pm4py.filter_trace_segments(log, [["A", "B"]]) retains only cases with the exact process variant A,B.
+ - pm4py.filter_trace_segments(log, [["...", "A", "B"]]) retains only cases ending with activities A,B.
+ - pm4py.filter_trace_segments(log, [["A", "B", "..."]]) retains only cases starting with activities A,B.
+ - pm4py.filter_trace_segments(log, [["...", "A", "B", "C", "..."], ["...", "D", "E", "F", "..."]]) retains cases where:
+ - At any point, there is A followed by B followed by C,
+ - And at any other point, there is D followed by E followed by F.
+
+ :param log: Event log or Pandas DataFrame.
+ :param admitted_traces: Collection of trace segments to admit based on the criteria above.
+ :param positive: Boolean indicating whether to keep (if True) or discard (if False) the cases satisfying the filter.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+ :return: Filtered event log or Pandas DataFrame.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+
+ filtered_log = pm4py.filter_trace_segments(
+ log,
+ [["...", "check ticket", "decide", "reinitiate request", "..."]]
+ )
+ print(filtered_log)
+
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["positive"] = positive
+
+ if _is_dataframe_like(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ filtering_pkg = _get_dataframe_filtering_package(log)
+ trace_filter = filtering_pkg.traces.trace_filter
+
+ return trace_filter.apply(log, admitted_traces, parameters=parameters)
+ else:
+ from pm4py.algo.filtering.log.traces import trace_filter
+
+ return trace_filter.apply(log, admitted_traces, parameters=parameters)
+
+
+def filter_ocel_object_types(
+ ocel: OCEL,
+ obj_types: Collection[str],
+ positive: bool = True,
+ level: int = 1,
+) -> OCEL:
+ """
+ Filters the object types of an object-centric event log.
+
+ :param ocel: Object-centric event log.
+ :param obj_types: Object types to keep or remove.
+ :param positive: Boolean indicating whether to keep (True) or remove (False) the specified object types.
+ :param level: Recursively expands the set of object identifiers until the specified level.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('log.jsonocel')
+ filtered_ocel = pm4py.filter_ocel_object_types(
+ ocel,
+ ['order']
+ )
+ """
+ from copy import copy
+ from pm4py.objects.ocel.util import filtering_utils
+
+ if level == 1:
+ filtered_ocel = copy(ocel)
+ if positive:
+ filtered_ocel.objects = filtered_ocel.objects[
+ filtered_ocel.objects[filtered_ocel.object_type_column].isin(
+ obj_types
+ )
+ ]
+ else:
+ filtered_ocel.objects = filtered_ocel.objects[
+ ~filtered_ocel.objects[filtered_ocel.object_type_column].isin(
+ obj_types
+ )
+ ]
+ return filtering_utils.propagate_object_filtering(filtered_ocel)
+ else:
+ object_ids = pandas_utils.format_unique(
+ ocel.objects[
+ ocel.objects[ocel.object_type_column].isin(obj_types)
+ ][ocel.object_id_column].unique()
+ )
+ return filter_ocel_objects(
+ ocel, object_ids, level=level, positive=positive
+ )
+
+
+def filter_ocel_objects(
+ ocel: OCEL,
+ object_identifiers: Collection[str],
+ positive: bool = True,
+ level: int = 1,
+) -> OCEL:
+ """
+ Filters the object identifiers of an object-centric event log.
+
+ :param ocel: Object-centric event log.
+ :param object_identifiers: Object identifiers to keep or remove.
+ :param positive: Boolean indicating whether to keep (True) or remove (False) the specified object identifiers.
+ :param level: Recursively expands the set of object identifiers until the specified level.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('log.jsonocel')
+ filtered_ocel = pm4py.filter_ocel_objects(
+ ocel,
+ ['o1'],
+ level=1
+ )
+ """
+ object_identifiers = set(object_identifiers)
+ if level > 1:
+ ev_rel_obj = (
+ ocel.relations.groupby(ocel.event_id_column)[ocel.object_id_column]
+ .agg(list)
+ .to_dict()
+ )
+ objects_ids = ocel.objects[ocel.object_id_column].to_numpy().tolist()
+ graph = {o: set() for o in objects_ids}
+ for ev in ev_rel_obj:
+ rel_obj = ev_rel_obj[ev]
+ for o1 in rel_obj:
+ for o2 in rel_obj:
+ if o1 != o2:
+ graph[o1].add(o2)
+ while level > 1:
+ curr = list(object_identifiers)
+ for el in curr:
+ for el2 in graph[el]:
+ object_identifiers.add(el2)
+ level = level - 1
+ from copy import copy
+ from pm4py.objects.ocel.util import filtering_utils
+
+ filtered_ocel = copy(ocel)
+ if positive:
+ filtered_ocel.objects = filtered_ocel.objects[
+ filtered_ocel.objects[ocel.object_id_column].isin(
+ object_identifiers
+ )
+ ]
+ else:
+ filtered_ocel.objects = filtered_ocel.objects[
+ ~filtered_ocel.objects[ocel.object_id_column].isin(
+ object_identifiers
+ )
+ ]
+ filtered_ocel = filtering_utils.propagate_object_filtering(filtered_ocel)
+ return filtered_ocel
+
+def filter_ocel_events(
+ ocel: OCEL, event_identifiers: Collection[str], positive: bool = True
+) -> OCEL:
+ """
+ Filters the event identifiers of an object-centric event log.
+
+ :param ocel: Object-centric event log.
+ :param event_identifiers: Event identifiers to keep or remove.
+ :param positive: Boolean indicating whether to keep (True) or remove (False) the specified event identifiers.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('log.jsonocel')
+ filtered_ocel = pm4py.filter_ocel_events(
+ ocel,
+ ['e1']
+ )
+ """
+ from copy import copy
+ from pm4py.objects.ocel.util import filtering_utils
+
+ filtered_ocel = copy(ocel)
+ if positive:
+ filtered_ocel.events = filtered_ocel.events[
+ filtered_ocel.events[ocel.event_id_column].isin(event_identifiers)
+ ]
+ else:
+ filtered_ocel.events = filtered_ocel.events[
+ ~filtered_ocel.events[ocel.event_id_column].isin(event_identifiers)
+ ]
+ return filtering_utils.propagate_event_filtering(filtered_ocel)
+
+
+def filter_ocel_activities_connected_object_type(
+ ocel: OCEL, object_type: str
+) -> OCEL:
+ """
+ Filter an OCEL on the set of activities executed on objects of the given object type.
+
+ :param ocel: object-centric event log
+ :param object_type: object type
+ :rtype: ``OCEL``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel2("tests/input_data/ocel/ocel20_example.xmlocel")
+ filtered_ocel = pm4py.filter_ocel_activities_connected_object_type(ocel, "Purchase Order")
+ print(filtered_ocel)
+ """
+ from copy import copy
+ from pm4py.objects.ocel.util import filtering_utils
+
+ relations = ocel.relations[
+ ocel.relations[ocel.object_type_column] == object_type
+ ]
+ activities = relations[ocel.event_activity].unique()
+ filtered_ocel = copy(ocel)
+ filtered_ocel.relations = filtered_ocel.relations[
+ filtered_ocel.relations[ocel.event_activity].isin(activities)
+ ]
+
+ return filtering_utils.propagate_relations_filtering(filtered_ocel)
+
+
+def filter_ocel_cc_object(
+ ocel: OCEL,
+ object_id: str,
+ conn_comp: Optional[List[List[str]]] = None,
+ return_conn_comp: bool = False,
+) -> Union[OCEL, Tuple[OCEL, List[List[str]]]]:
+ """
+ Returns the connected component of the object-centric event log to which the specified object belongs.
+
+ :param ocel: Object-centric event log.
+ :param object_id: Object identifier.
+ :param conn_comp: (Optional) Precomputed connected components of the OCEL objects.
+ :param return_conn_comp: If True, returns the filtered OCEL along with the computed connected components.
+ :return: Filtered OCEL, optionally with the list of connected components.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('log.jsonocel')
+ filtered_ocel = pm4py.filter_ocel_cc_object(
+ ocel,
+ 'order1'
+ )
+ """
+ if conn_comp is None:
+ from pm4py.algo.transformation.ocel.graphs import (
+ object_interaction_graph,
+ )
+
+ g0 = object_interaction_graph.apply(ocel)
+ g = nx_utils.Graph()
+
+ for edge in g0:
+ g.add_edge(edge[0], edge[1])
+
+ conn_comp = list(nx_utils.connected_components(g))
+
+ for cc in conn_comp:
+ if object_id in cc:
+ if return_conn_comp:
+ return filter_ocel_objects(ocel, cc), conn_comp
+ else:
+ return filter_ocel_objects(ocel, cc)
+
+ if return_conn_comp:
+ return filter_ocel_objects(ocel, [object_id]), conn_comp
+ else:
+ return filter_ocel_objects(ocel, [object_id])
+
+
+def filter_ocel_cc_length(
+ ocel: OCEL, min_cc_length: int, max_cc_length: int
+) -> OCEL:
+ """
+ Keeps only the objects in an OCEL belonging to a connected component with a length
+ falling within the specified range.
+
+ Reference:
+ Adams, Jan Niklas, et al. "Defining cases and variants for object-centric event data."
+ 2022 4th International Conference on Process Mining (ICPM). IEEE, 2022.
+
+ :param ocel: Object-centric event log.
+ :param min_cc_length: Minimum allowed length for the connected component.
+ :param max_cc_length: Maximum allowed length for the connected component.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ filtered_ocel = pm4py.filter_ocel_cc_length(
+ ocel,
+ 2,
+ 10
+ )
+ """
+ from pm4py.algo.transformation.ocel.graphs import object_interaction_graph
+
+ g0 = object_interaction_graph.apply(ocel)
+ g = nx_utils.Graph()
+
+ for edge in g0:
+ g.add_edge(edge[0], edge[1])
+
+ conn_comp = list(nx_utils.connected_components(g))
+ conn_comp = [
+ x for x in conn_comp if min_cc_length <= len(x) <= max_cc_length
+ ]
+ objs = [y for x in conn_comp for y in x]
+
+ return filter_ocel_objects(ocel, objs)
+
+
+def filter_ocel_cc_otype(
+ ocel: OCEL, otype: str, positive: bool = True
+) -> OCEL:
+ """
+ Filters the objects belonging to connected components that have at least one object of the specified type.
+
+ Reference:
+ Adams, Jan Niklas, et al. "Defining cases and variants for object-centric event data."
+ 2022 4th International Conference on Process Mining (ICPM). IEEE, 2022.
+
+ :param ocel: Object-centric event log.
+ :param otype: Object type to consider.
+ :param positive: Boolean indicating whether to keep (True) or discard (False) the objects in these components.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('log.jsonocel')
+ filtered_ocel = pm4py.filter_ocel_cc_otype(
+ ocel,
+ 'order'
+ )
+ """
+ if positive:
+ objs = set(
+ ocel.objects[ocel.objects[ocel.object_type_column] == otype][
+ ocel.object_id_column
+ ]
+ )
+ else:
+ objs = set(
+ ocel.objects[~(ocel.objects[ocel.object_type_column] == otype)][
+ ocel.object_id_column
+ ]
+ )
+
+ from pm4py.algo.transformation.ocel.graphs import object_interaction_graph
+
+ g0 = object_interaction_graph.apply(ocel)
+ g = nx_utils.Graph()
+
+ for edge in g0:
+ g.add_edge(edge[0], edge[1])
+
+ conn_comp = list(nx_utils.connected_components(g))
+ conn_comp = [x for x in conn_comp if len(set(x).intersection(objs)) > 0]
+
+ objs = [y for x in conn_comp for y in x]
+
+ return filter_ocel_objects(ocel, objs)
+
+
+def filter_ocel_cc_activity(ocel: OCEL, activity: str) -> OCEL:
+ """
+ Filters the objects belonging to connected components that include at least one event with the specified activity.
+
+ Reference:
+ Adams, Jan Niklas, et al. "Defining cases and variants for object-centric event data."
+ 2022 4th International Conference on Process Mining (ICPM). IEEE, 2022.
+
+ :param ocel: Object-centric event log.
+ :param activity: Activity to consider.
+ :return: Filtered OCEL.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('log.jsonocel')
+ filtered_ocel = pm4py.filter_ocel_cc_activity(
+ ocel,
+ 'Create Order'
+ )
+ """
+ evs = (
+ ocel.events[ocel.events[ocel.event_activity] == activity][
+ ocel.event_id_column
+ ]
+ .to_numpy()
+ .tolist()
+ )
+ objs = pandas_utils.format_unique(
+ ocel.relations[ocel.relations[ocel.event_id_column].isin(evs)][
+ ocel.object_id_column
+ ].unique()
+ )
+
+ from pm4py.algo.transformation.ocel.graphs import object_interaction_graph
+
+ g0 = object_interaction_graph.apply(ocel)
+ g = nx_utils.Graph()
+
+ for edge in g0:
+ g.add_edge(edge[0], edge[1])
+
+ conn_comp = list(nx_utils.connected_components(g))
+ conn_comp = [x for x in conn_comp if len(set(x).intersection(objs)) > 0]
+
+ objs = [y for x in conn_comp for y in x]
+
+ return filter_ocel_objects(ocel, objs)
+
+
+def filter_dfg_activities_percentage(
+ dfg: Dict[Tuple[str, str], int],
+ start_activities: Dict[str, int],
+ end_activities: Dict[str, int],
+ percentage: float = 0.2,
+) -> Tuple[Dict[Tuple[str, str], int], Dict[str, int], Dict[str, int]]:
+ """
+ Filters the DFG on the provided percentage of activities.
+
+ :param dfg: frequency directly-follows graph
+ :param start_activities: dictionary of the start activities
+ :param end_activities: dictionary of the end activities
+ :param percentage: percentage of activities to keep
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
+ dfg, sa, ea = pm4py.discover_dfg(log)
+ dfg, sa, ea = pm4py.filter_dfg_activities_percentage(dfg, sa, ea, percentage=0.2)
+ pm4py.view_dfg(dfg, sa, ea, format='svg')
+ """
+ activities_entering_arcs = Counter()
+ activities_exiting_arcs = Counter()
+ all_activities = set()
+ for arc, count in dfg.items():
+ activities_entering_arcs[arc[0]] += count
+ activities_exiting_arcs[arc[1]] += count
+ all_activities.add(arc[0])
+ all_activities.add(arc[1])
+ activities_frequency = {
+ a: max(activities_entering_arcs[a], activities_exiting_arcs[a])
+ for a in all_activities
+ }
+
+ from pm4py.algo.filtering.dfg.dfg_filtering import (
+ filter_dfg_on_activities_percentage,
+ )
+
+ dfg, start_activities, end_activities, activities_frequency = (
+ filter_dfg_on_activities_percentage(
+ dfg,
+ start_activities,
+ end_activities,
+ activities_frequency,
+ percentage=percentage,
+ )
+ )
+
+ return dfg, start_activities, end_activities
+
+
+def filter_dfg_paths_percentage(
+ dfg: Dict[Tuple[str, str], int],
+ start_activities: Dict[str, int],
+ end_activities: Dict[str, int],
+ percentage: float = 0.2,
+) -> Tuple[Dict[Tuple[str, str], int], Dict[str, int], Dict[str, int]]:
+ """
+ Filters the DFG on the provided percentage of paths.
+
+ :param dfg: frequency directly-follows graph
+ :param start_activities: dictionary of the start activities
+ :param end_activities: dictionary of the end activities
+ :param percentage: percentage of paths to keep
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
+ dfg, sa, ea = pm4py.discover_dfg(log)
+ dfg, sa, ea = pm4py.filter_dfg_paths_percentage(dfg, sa, ea, percentage=0.2)
+ pm4py.view_dfg(dfg, sa, ea, format='svg')
+ """
+ activities_entering_arcs = Counter()
+ activities_exiting_arcs = Counter()
+ all_activities = set()
+ for arc, count in dfg.items():
+ activities_entering_arcs[arc[0]] += count
+ activities_exiting_arcs[arc[1]] += count
+ all_activities.add(arc[0])
+ all_activities.add(arc[1])
+ activities_frequency = {
+ a: max(activities_entering_arcs[a], activities_exiting_arcs[a])
+ for a in all_activities
+ }
+
+ from pm4py.algo.filtering.dfg.dfg_filtering import (
+ filter_dfg_on_paths_percentage,
+ )
+
+ dfg, start_activities, end_activities, activities_frequency = (
+ filter_dfg_on_paths_percentage(
+ dfg,
+ start_activities,
+ end_activities,
+ activities_frequency,
+ percentage=percentage,
+ )
+ )
+
+ return dfg, start_activities, end_activities
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/hof.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/hof.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bb9cbe30663257955863d0b76bc896a0f68b046
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/hof.py
@@ -0,0 +1,170 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+"""
+
+import warnings
+from pm4py.util import constants
+from typing import Callable, Any, Union
+
+from pm4py.objects.log import obj as log_inst
+from pm4py.utils import __event_log_deprecation_warning
+from pm4py.util import deprecation
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="the EventLog class will be removed in a future release.",
+)
+def filter_log(
+ f: Callable[[Any], bool], log: log_inst.EventLog
+) -> Union[log_inst.EventLog, log_inst.EventStream]:
+ """
+ Filters the log according to a given (lambda) function.
+
+ :param f: function that specifies the filter criterion, may be a lambda
+ :param log: event log; either EventLog or EventStream Object
+ :rtype: ``Union[log_inst.EventLog, log_inst.EventStream]``
+ """
+ __event_log_deprecation_warning(log)
+
+ if isinstance(log, log_inst.EventLog):
+ return log_inst.EventLog(
+ list(filter(f, log)),
+ attributes=log.attributes,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ extensions=log.extensions,
+ properties=log.properties,
+ )
+ elif isinstance(log, log_inst.EventStream):
+ return log_inst.EventStream(
+ list(filter(f, log)),
+ attributes=log.attributes,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ extensions=log.extensions,
+ properties=log.properties,
+ )
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "input log object not of appropriate type, filter() not applied"
+ )
+ return log
+
+
+def filter_trace(
+ f: Callable[[Any], bool], trace: log_inst.Trace
+) -> log_inst.Trace:
+ """
+ Filters the trace according to a given (lambda) function.
+
+ :param f: function that specifies the filter criterion, may be a lambda
+ :param trace: trace; PM4Py trace object
+ :rtype: ``log_inst.Trace``
+ """
+ __event_log_deprecation_warning(trace)
+
+ if isinstance(trace, log_inst.Trace):
+ return log_inst.Trace(
+ list(filter(f, trace)), attributes=trace.attributes
+ )
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "input trace object is not of the appropriate type, filter() not applied"
+ )
+ return trace
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="the EventLog class will be removed in a future release.",
+)
+def sort_log(
+ log: log_inst.EventLog, key, reverse: bool = False
+) -> Union[log_inst.EventLog, log_inst.EventStream]:
+ """
+ Sorts the event log according to a given key.
+
+ :param log: event log object; either EventLog or EventStream
+ :param key: sorting key
+ :param reverse: indicates whether sorting should be reversed or not
+ :rtype: ``Union[log_inst.EventLog, log_inst.EventStream]``
+ """
+ __event_log_deprecation_warning(log)
+
+ if isinstance(log, log_inst.EventLog):
+ return log_inst.EventLog(
+ sorted(log, key=key, reverse=reverse),
+ attributes=log.attributes,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ extensions=log.extensions,
+ properties=log.properties,
+ )
+ elif isinstance(log, log_inst.EventStream):
+ return log_inst.EventStream(
+ sorted(log, key=key, reverse=reverse),
+ attributes=log.attributes,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ extensions=log.extensions,
+ properties=log.properties,
+ )
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "input log object not of appropriate type, sorted() not applied"
+ )
+ return log
+
+
+@deprecation.deprecated(
+ deprecated_in="2.3.0",
+ removed_in="3.0.0",
+ details="the EventLog class will be removed in a future release.",
+)
+def sort_trace(
+ trace: log_inst.Trace, key, reverse: bool = False
+) -> log_inst.Trace:
+ """
+ Sorts the events in a trace according to a given key.
+
+ :param trace: input trace
+ :param key: sorting key
+ :param reverse: indicates whether sorting should be reversed (default False)
+ :rtype: ``log_inst.Trace``
+ """
+ __event_log_deprecation_warning(trace)
+
+ if isinstance(trace, log_inst.Trace):
+ return log_inst.Trace(sorted(trace, key=key, reverse=reverse))
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "input trace object not of appropriate type, sorted() not applied"
+ )
+ return trace
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/llm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/llm.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c40ed16d95c723f44e28176bc2f4eba5b957ee2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/llm.py
@@ -0,0 +1,971 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import pandas as pd
+from pm4py.objects.log.obj import EventLog, EventStream, Trace
+from typing import Union, Optional, Dict, Tuple, List, Any
+from pm4py.utils import get_properties, constants, check_is_pandas_dataframe
+from pm4py.utils import __event_log_deprecation_warning
+from pm4py.objects.ocel.obj import OCEL
+from tempfile import NamedTemporaryFile
+from copy import copy
+import re
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+
+
+def openai_query(
+ prompt: str,
+ api_key: Optional[str] = None,
+ openai_model: Optional[str] = None,
+ api_url: Optional[str] = None,
+ extra_payload: Optional[Dict[Any, Any]] = None,
+ **kwargs
+) -> str:
+ r"""
+ Executes the provided prompt, obtaining the answer from the OpenAI APIs.
+
+ :param prompt: The prompt to be executed.
+ :param api_key: (Optional) OpenAI API key.
+ :param openai_model: (Optional) OpenAI model to be used (default: "gpt-3.5-turbo").
+ :param api_url: (Optional) OpenAI API URL.
+ :param extra_payload: (Optional) Additional payload fields merged into the request body.
+ :param \**kwargs: Additional parameters to pass to the OpenAI API.
+ :return: The response from the OpenAI API as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ resp = pm4py.llm.openai_query('What is the result of 3+3?', api_key="sk-382393", openai_model="gpt-3.5-turbo")
+ print(resp)
+ """
+ parameters = copy(kwargs) if kwargs is not None else {}
+ if api_url is not None:
+ parameters["api_url"] = api_url
+ if api_key is not None:
+ parameters["api_key"] = api_key
+ if openai_model is not None:
+ parameters["openai_model"] = openai_model
+ if extra_payload is not None:
+ parameters["extra_payload"] = extra_payload
+
+ from pm4py.algo.querying.llm.connectors import openai as perform_query
+
+ return perform_query.apply(prompt, parameters=parameters)
+
+
+def google_query(
+ prompt: str,
+ api_key: Optional[str] = None,
+ model: Optional[str] = None,
+ extra_payload: Optional[Dict[Any, Any]] = None,
+ **kwargs
+) -> str:
+ """
+ Executes the provided prompt, obtaining the answer from the Google APIs.
+
+ :param prompt: prompt that should be executed
+ :param api_key: API key
+ :param model: Model to be used (default: gemini-1.5-flash-002)
+ :param extra_payload: (Optional) Additional payload fields merged into the request body.
+ :rtype: ``str``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ resp = pm4py.llm.google_query('what is the result of 3+3?', api_key="sk-382393", model="gemini-1.5-flash-002")
+ print(resp)
+ """
+ parameters = copy(kwargs) if kwargs is not None else {}
+ if api_key is not None:
+ parameters["api_key"] = api_key
+ if model is not None:
+ parameters["google_model"] = model
+ if extra_payload is not None:
+ parameters["extra_payload"] = extra_payload
+
+ from pm4py.algo.querying.llm.connectors import google as perform_query
+
+ return perform_query.apply(prompt, parameters=parameters)
+
+
+def anthropic_query(
+ prompt: str,
+ api_key: Optional[str] = None,
+ model: Optional[str] = None,
+ extra_payload: Optional[Dict[Any, Any]] = None,
+ **kwargs
+) -> str:
+ """
+ Executes the provided prompt, obtaining the answer from the Google APIs.
+
+ :param prompt: prompt that should be executed
+ :param api_key: API key
+ :param model: Model to be used (default: claude-3-5-sonnet-20241022)
+ :param extra_payload: (Optional) Additional payload fields merged into the request body.
+ :rtype: ``str``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ resp = pm4py.llm.anthropic_query('what is the result of 3+3?', api_key="sk-382393", model="claude-3-5-sonnet-20241022")
+ print(resp)
+ """
+ parameters = copy(kwargs) if kwargs is not None else {}
+ if api_key is not None:
+ parameters["api_key"] = api_key
+ if model is not None:
+ parameters["anthropic_model"] = model
+ if extra_payload is not None:
+ parameters["extra_payload"] = extra_payload
+
+ from pm4py.algo.querying.llm.connectors import anthropic as perform_query
+
+ return perform_query.apply(prompt, parameters=parameters)
+
+
+def abstract_dfg(
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
+ max_len: int = constants.OPENAI_MAX_LEN,
+ include_performance: bool = True,
+ relative_frequency: bool = False,
+ response_header: bool = True,
+ primary_performance_aggregation: str = "mean",
+ secondary_performance_aggregation: Optional[str] = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> str:
+ """
+ Obtains the DFG (Directly-Follows Graph) abstraction of a traditional event log.
+
+ :param log_obj: The log object to abstract.
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
+ :param include_performance: Whether to include the performance of the paths in the abstraction.
+ :param relative_frequency: Whether to use relative instead of absolute frequency of the paths.
+ :param response_header: Whether to include a short header before the paths, describing the abstraction.
+ :param primary_performance_aggregation: Primary aggregation method for the arc's performance (default: "mean"). Other options: "median", "min", "max", "sum", "stdev".
+ :param secondary_performance_aggregation: (Optional) Secondary aggregation method for the arc's performance (default: None). Other options: "mean", "median", "min", "max", "sum", "stdev".
+ :param activity_key: The column name to be used as activity.
+ :param timestamp_key: The column name to be used as timestamp.
+ :param case_id_key: The column name to be used as case identifier.
+ :return: The DFG abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
+ print(pm4py.llm.abstract_dfg(log))
+ """
+ __event_log_deprecation_warning(log_obj)
+
+ parameters = get_properties(
+ log_obj,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["max_len"] = max_len
+ parameters["include_performance"] = include_performance
+ parameters["relative_frequency"] = relative_frequency
+ parameters["response_header"] = response_header
+ parameters["primary_performance_aggregation"] = (
+ primary_performance_aggregation
+ )
+ parameters["secondary_performance_aggregation"] = (
+ secondary_performance_aggregation
+ )
+
+ from pm4py.algo.querying.llm.abstractions import log_to_dfg_descr
+
+ return log_to_dfg_descr.apply(log_obj, parameters=parameters)
+
+
+def abstract_variants(
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
+ max_len: int = constants.OPENAI_MAX_LEN,
+ include_performance: bool = True,
+ relative_frequency: bool = False,
+ response_header: bool = True,
+ primary_performance_aggregation: str = "mean",
+ secondary_performance_aggregation: Optional[str] = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ **kwargs
+) -> str:
+ """
+ Obtains the variants abstraction of a traditional event log.
+
+ :param log_obj: The log object to abstract.
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
+ :param include_performance: Whether to include the performance of the variants in the abstraction.
+ :param relative_frequency: Whether to use relative instead of absolute frequency of the variants.
+ :param response_header: Whether to include a short header before the variants, describing the abstraction.
+ :param primary_performance_aggregation: Primary aggregation method for the variants' performance (default: "mean"). Other options: "median", "min", "max", "sum", "stdev".
+ :param secondary_performance_aggregation: (Optional) Secondary aggregation method for the variants' performance (default: None). Other options: "mean", "median", "min", "max", "sum", "stdev".
+ :param activity_key: The column name to be used as activity.
+ :param timestamp_key: The column name to be used as timestamp.
+ :param case_id_key: The column name to be used as case identifier.
+ :return: The variants abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
+ print(pm4py.llm.abstract_variants(log))
+ """
+ __event_log_deprecation_warning(log_obj)
+
+ parameters = get_properties(
+ log_obj,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["max_len"] = max_len
+ parameters["include_performance"] = include_performance
+ parameters["relative_frequency"] = relative_frequency
+ parameters["response_header"] = response_header
+ parameters["primary_performance_aggregation"] = (
+ primary_performance_aggregation
+ )
+ parameters["secondary_performance_aggregation"] = (
+ secondary_performance_aggregation
+ )
+
+ from pm4py.algo.querying.llm.abstractions import log_to_variants_descr
+
+ return log_to_variants_descr.apply(log_obj, parameters=parameters)
+
+
+def abstract_ocel(ocel: OCEL, include_timestamps: bool = True) -> str:
+ """
+ Obtains the abstraction of an object-centric event log, including the list of events and the objects of the OCEL.
+
+ :param ocel: The object-centric event log to abstract.
+ :param include_timestamps: Whether to include timestamp information in the abstraction.
+ :return: The OCEL abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel("tests/input_data/ocel/example_log.jsonocel")
+ print(pm4py.llm.abstract_ocel(ocel))
+ """
+ parameters = {}
+ parameters["include_timestamps"] = include_timestamps
+
+ from pm4py.algo.transformation.ocel.description import (
+ algorithm as ocel_description,
+ )
+
+ return ocel_description.apply(ocel, parameters=parameters)
+
+
+def abstract_ocel_ocdfg(
+ ocel: OCEL,
+ include_header: bool = True,
+ include_timestamps: bool = True,
+ max_len: int = constants.OPENAI_MAX_LEN,
+) -> str:
+ """
+ Obtains the abstraction of an object-centric event log, representing the object-centric directly-follows graph in text.
+
+ :param ocel: The object-centric event log to abstract.
+ :param include_header: Whether to include a header in the abstraction.
+ :param include_timestamps: Whether to include timestamp information in the abstraction.
+ :param max_len: Maximum length of the abstraction (default: constants.OPENAI_MAX_LEN).
+ :return: The object-centric DFG abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel("tests/input_data/ocel/example_log.jsonocel")
+ print(pm4py.llm.abstract_ocel_ocdfg(ocel))
+ """
+ parameters = {}
+ parameters["include_header"] = include_header
+ parameters["include_timestamps"] = include_timestamps
+ parameters["max_len"] = max_len
+
+ from pm4py.algo.querying.llm.abstractions import ocel_ocdfg_descr
+
+ return ocel_ocdfg_descr.apply(ocel, parameters=parameters)
+
+
+def abstract_ocel_features(
+ ocel: OCEL,
+ obj_type: str,
+ include_header: bool = True,
+ max_len: int = constants.OPENAI_MAX_LEN,
+ debug: bool = False,
+ enable_object_lifecycle_paths: bool = True,
+) -> str:
+ """
+ Obtains the abstraction of an object-centric event log, representing the features and their values in text.
+
+ :param ocel: The object-centric event log to abstract.
+ :param obj_type: The object type to consider in feature extraction.
+ :param include_header: Whether to include a header in the abstraction.
+ :param max_len: Maximum length of the abstraction (default: constants.OPENAI_MAX_LEN).
+ :param debug: Enables debugging mode, providing insights into feature extraction steps.
+ :param enable_object_lifecycle_paths: Enables the "lifecycle paths" feature in the abstraction.
+ :return: The OCEL features abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel("tests/input_data/ocel/example_log.jsonocel")
+ print(pm4py.llm.abstract_ocel_features(ocel, obj_type="Resource"))
+ """
+ parameters = {}
+ parameters["include_header"] = include_header
+ parameters["max_len"] = max_len
+ parameters["debug"] = debug
+ parameters["enable_object_lifecycle_paths"] = enable_object_lifecycle_paths
+
+ from pm4py.algo.querying.llm.abstractions import ocel_fea_descr
+
+ return ocel_fea_descr.apply(ocel, obj_type, parameters=parameters)
+
+
+def abstract_event_stream(
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
+ max_len: int = constants.OPENAI_MAX_LEN,
+ response_header: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> str:
+ """
+ Obtains the event stream abstraction of a traditional event log.
+
+ :param log_obj: The log object to abstract.
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
+ :param response_header: Whether to include a short header before the event stream, describing the abstraction.
+ :param activity_key: The column name to be used as activity.
+ :param timestamp_key: The column name to be used as timestamp.
+ :param case_id_key: The column name to be used as case identifier.
+ :return: The event stream abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
+ print(pm4py.llm.abstract_event_stream(log))
+ """
+ __event_log_deprecation_warning(log_obj)
+
+ parameters = get_properties(
+ log_obj,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["max_len"] = max_len
+ parameters["response_header"] = response_header
+
+ from pm4py.algo.querying.llm.abstractions import stream_to_descr
+
+ return stream_to_descr.apply(log_obj, parameters=parameters)
+
+
+def abstract_petri_net(
+ net: PetriNet, im: Marking, fm: Marking, response_header: bool = True
+) -> str:
+ """
+ Obtains an abstraction of a Petri net.
+
+ :param net: The Petri net to abstract.
+ :param im: The initial marking of the Petri net.
+ :param fm: The final marking of the Petri net.
+ :param response_header: Whether to include a header in the abstraction.
+ :return: The Petri net abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
+ print(pm4py.llm.abstract_petri_net(net, im, fm))
+ """
+ parameters = {}
+ parameters["response_header"] = response_header
+
+ from pm4py.algo.querying.llm.abstractions import net_to_descr
+
+ return net_to_descr.apply(net, im, fm, parameters=parameters)
+
+
+def abstract_log_attributes(
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
+ max_len: int = constants.OPENAI_MAX_LEN,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> str:
+ """
+ Abstracts the attributes of a log by reporting their names, types, and top values.
+
+ :param log_obj: The log object whose attributes are to be abstracted.
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
+ :param activity_key: The column name to be used as activity.
+ :param timestamp_key: The column name to be used as timestamp.
+ :param case_id_key: The column name to be used as case identifier.
+ :return: The log attributes abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
+ print(pm4py.llm.abstract_log_attributes(log))
+ """
+ __event_log_deprecation_warning(log_obj)
+
+ parameters = get_properties(
+ log_obj,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["max_len"] = max_len
+
+ from pm4py.algo.querying.llm.abstractions import log_to_cols_descr
+
+ return log_to_cols_descr.apply(log_obj, parameters=parameters)
+
+
+def abstract_log_features(
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
+ max_len: int = constants.OPENAI_MAX_LEN,
+ include_header: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> str:
+ """
+ Abstracts the machine learning features obtained from a log by reporting the top features until the desired length is achieved.
+
+ :param log_obj: The log object from which to extract features.
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
+ :param include_header: Whether to include a header in the abstraction.
+ :param activity_key: The column name to be used as activity.
+ :param timestamp_key: The column name to be used as timestamp.
+ :param case_id_key: The column name to be used as case identifier.
+ :return: The log features abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
+ print(pm4py.llm.abstract_log_features(log))
+ """
+ __event_log_deprecation_warning(log_obj)
+
+ parameters = get_properties(
+ log_obj,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["max_len"] = max_len
+ parameters["include_header"] = include_header
+
+ from pm4py.algo.querying.llm.abstractions import log_to_fea_descr
+
+ return log_to_fea_descr.apply(log_obj, parameters=parameters)
+
+
+def abstract_temporal_profile(
+ temporal_profile: Dict[Tuple[str, str], Tuple[float, float]],
+ include_header: bool = True,
+) -> str:
+ """
+ Abstracts a temporal profile model into a descriptive string.
+
+ :param temporal_profile: The temporal profile model to abstract.
+ :param include_header: Whether to include a header in the abstraction describing the temporal profile.
+ :return: The temporal profile abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
+ temporal_profile = pm4py.discover_temporal_profile(log)
+ text_abstr = pm4py.llm.abstract_temporal_profile(temporal_profile, include_header=True)
+ print(text_abstr)
+ """
+ parameters = {}
+ parameters["include_header"] = include_header
+
+ from pm4py.algo.querying.llm.abstractions import tempprofile_to_descr
+
+ return tempprofile_to_descr.apply(temporal_profile, parameters=parameters)
+
+
+def abstract_case(
+ case: Trace,
+ include_case_attributes: bool = True,
+ include_event_attributes: bool = True,
+ include_timestamp: bool = True,
+ include_header: bool = True,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+) -> str:
+ """
+ Textually abstracts a single case from an event log.
+
+ :param case: The case object to abstract.
+ :param include_case_attributes: Whether to include attributes at the case level.
+ :param include_event_attributes: Whether to include attributes at the event level.
+ :param include_timestamp: Whether to include event timestamps in the abstraction.
+ :param include_header: Whether to include a header in the abstraction.
+ :param activity_key: The column name to be used as activity.
+ :param timestamp_key: The column name to be used as timestamp.
+ :return: The case abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
+ print(pm4py.llm.abstract_case(log[0]))
+ """
+ parameters = {}
+ parameters["include_case_attributes"] = include_case_attributes
+ parameters["include_event_attributes"] = include_event_attributes
+ parameters["include_timestamp"] = include_timestamp
+ parameters["include_header"] = include_header
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY] = activity_key
+ parameters[constants.PARAMETER_CONSTANT_TIMESTAMP_KEY] = timestamp_key
+
+ from pm4py.algo.querying.llm.abstractions import case_to_descr
+
+ return case_to_descr.apply(case, parameters=parameters)
+
+
+def abstract_declare(declare_model, include_header: bool = True) -> str:
+ """
+ Textually abstracts a DECLARE model.
+
+ :param declare_model: The DECLARE model to abstract.
+ :param include_header: Whether to include a header in the abstraction.
+ :return: The DECLARE model abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
+ log_ske = pm4py.discover_declare(log)
+ print(pm4py.llm.abstract_declare(log_ske))
+ """
+ parameters = {}
+ parameters["include_header"] = include_header
+
+ from pm4py.algo.querying.llm.abstractions import declare_to_descr
+
+ return declare_to_descr.apply(declare_model, parameters=parameters)
+
+
+def abstract_log_skeleton(log_skeleton, include_header: bool = True) -> str:
+ """
+ Textually abstracts a log skeleton process model.
+
+ :param log_skeleton: The log skeleton to abstract.
+ :param include_header: Whether to include a header in the abstraction.
+ :return: The log skeleton abstraction as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
+ log_ske = pm4py.discover_log_skeleton(log)
+ print(pm4py.llm.abstract_log_skeleton(log_ske))
+ """
+ parameters = {}
+ parameters["include_header"] = include_header
+
+ from pm4py.algo.querying.llm.abstractions import logske_to_descr
+
+ return logske_to_descr.apply(log_skeleton, parameters=parameters)
+
+
+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]]:
+ """
+ Performs LLM-based clustering on the variants' list.
+
+ Parameters
+ -----------------
+ log
+ Pandas dataframe
+ executor
+ The connector that should be used (openai, google, anthropic)
+ case_id_key
+ Column representing the case ID
+ activity_key
+ Column representing the activity
+
+ Returns
+ -----------------
+ final_clusters
+ A list of tuples. The first element is the name associated to the cluster, the second one is the sub-event-log.
+ """
+ import pm4py, json, re
+
+ prompt = pm4py.llm.abstract_variants(log, include_performance=False, **kwargs)
+ prompt += "\n\nCould you identify clusters of traces in the provided list? "
+ prompt += "Please provide a JSON list, contained in the ```json tags, containing a dictionary for each cluster. "
+ prompt += " The dictionary has a key 'name' and a key 'regex'."
+ prompt += " The 'name' should be a meaningful name for the cluster. The 'regex' should be a regular expression,"
+ prompt += "that I can use to filter the traces."
+
+ result = executor(prompt, **kwargs)
+ result = json.loads(result.split("```json")[1].split("```")[0])
+
+ final_clusters = []
+ agg0 = log.groupby(case_id_key, sort=False)[activity_key].agg(list).reset_index()
+ agg0["concept:name"] = agg0["concept:name"].apply(lambda x: " -> ".join(x))
+
+ for res in result:
+ reg = re.compile(res["regex"])
+ agg = agg0[agg0[activity_key].str.contains(reg)]
+ df = log[log[case_id_key].isin(agg[case_id_key])]
+
+ final_clusters.append((res["name"], df))
+
+ return final_clusters
+
+
+def __validate_safe_select_query(sql_query: str) -> str:
+ """
+ Validates that a SQL query is read-only and free from statements/functions
+ that could access or modify local files/databases.
+ """
+ query = sql_query.strip()
+ if query.endswith(";"):
+ query = query[:-1].strip()
+
+ if not query:
+ raise ValueError("The response does not contain a valid SQL query.")
+
+ if ";" in query:
+ raise ValueError("Only a single SQL statement is allowed.")
+
+ if "--" in query or "/*" in query or "*/" in query:
+ raise ValueError("SQL comments are not allowed in auto-executed queries.")
+
+ normalized = " ".join(query.lower().split())
+ if not (normalized.startswith("select ") or normalized.startswith("with ")):
+ raise ValueError("Only read-only SELECT queries can be auto-executed.")
+
+ forbidden_patterns = [
+ r"\b(insert|update|delete|drop|alter|create|replace|truncate|merge)\b",
+ r"\b(attach|detach|copy|call|pragma|install|load|export|import|vacuum)\b",
+ r"\b(read_csv|read_csv_auto|read_parquet|read_json|read_json_auto)\b",
+ r"\bwrite_(csv|parquet)\b",
+ ]
+
+ for pattern in forbidden_patterns:
+ if re.search(pattern, normalized):
+ raise ValueError("Unsafe SQL detected in LLM-generated query.")
+
+ return query
+
+
+def __execute_prompt_to_db_query(
+ log: pd.DataFrame,
+ prompt: str,
+ executor=openai_query,
+ execute_query: bool = True,
+ **kwargs
+) -> Union[str, pd.DataFrame]:
+ """
+ Internal method to retrieve (and execute) a SQL query corresponding to a prompt
+ """
+ if check_is_pandas_dataframe(log):
+ kwargs["table_name"] = "dataframe"
+ dataframe = log
+
+ response = executor(prompt, **kwargs)
+
+ sql_query = ""
+ if "```sql" in response:
+ sql_query = response.split("```sql")[1].split("```")[0]
+ sql_query = sql_query.strip()
+
+ if not sql_query:
+ raise Exception(
+ "The response does not contain a valid SQL query: " + response
+ )
+
+ if execute_query:
+ safe_sql_query = __validate_safe_select_query(sql_query)
+ import duckdb
+
+ result = duckdb.query(safe_sql_query).to_df()
+
+ if check_is_pandas_dataframe(log):
+ return result
+
+ return sql_query
+
+
+def nlp_to_log_query(
+ log: pd.DataFrame,
+ query: str,
+ executor=openai_query,
+ obtain_query: bool = True,
+ execute_query: bool = True,
+ **kwargs
+) -> Union[str, pd.DataFrame]:
+ """
+ Translates a natural language statement into a database (SQL) query executable against the event log.
+
+ :param log: event log object
+ :param query: query expressed in natural language
+ :param executor: the connector to the LLM (e.g., pm4py.llm.openai_query)
+ :param obtain_query: executes the prompt, to transform the natural statements into a database (SQL) query
+ :param execute_query: executes the database (SQL) query against the event data
+ :param kwargs: additional keyword arguments to the method
+ :rtype: ``Union[str, pd.DataFrame]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+ resp = pm4py.llm.nlp_to_log_query(log, "How many cases are contained in the event log?", api_key="sk-5HNn")
+ print(resp)
+ """
+ from pm4py.algo.querying.llm.injection import (
+ algorithm as domain_knowledge_injector,
+ )
+
+ prompt = (
+ "Could you provide a database query for the following question?\n\n"
+ + query
+ )
+ prompt += domain_knowledge_injector.apply(log, parameters=kwargs)
+ prompt += "\n\nPlease include the SQL query between the ```sql and the ``` tags.\n\n"
+
+ if obtain_query:
+ return __execute_prompt_to_db_query(
+ log,
+ prompt,
+ executor=executor,
+ execute_query=execute_query,
+ **kwargs
+ )
+
+ return prompt
+
+
+def nlp_to_log_filter(
+ log: pd.DataFrame,
+ filter_query: str,
+ executor=openai_query,
+ obtain_query: bool = True,
+ execute_query: bool = True,
+ **kwargs
+) -> Union[str, pd.DataFrame]:
+ """
+ Translates a filtering query expressed in natural language into a database (SQL) query that is used to filter the
+ event log.
+
+ :param log: event log object
+ :param filter_query: filtering query expressed in natural language
+ :param executor: the connector to the LLM (e.g., pm4py.llm.openai_query)
+ :param obtain_query: executes the prompt, to transform the natural statements into a database (SQL) query
+ :param execute_query: executes the database (SQL) query against the event data
+ :param kwargs: additional keyword arguments to the method
+ :rtype: ``Union[str, pd.DataFrame]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+ resp = pm4py.llm.nlp_to_log_filter(log, "There is an event with activity: pay compensation", api_key="sk-5HNn")
+ print(resp)
+ """
+ from pm4py.algo.querying.llm.injection import (
+ algorithm as domain_knowledge_injector,
+ )
+
+ prompt = (
+ "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" +
+ filter_query)
+ prompt += domain_knowledge_injector.apply(log, parameters=kwargs)
+ prompt += "\n\nPlease include the SQL query between the ```sql and the ``` tags.\n\n"
+
+ if obtain_query:
+ return __execute_prompt_to_db_query(
+ log,
+ prompt,
+ executor=executor,
+ execute_query=execute_query,
+ **kwargs
+ )
+
+ return prompt
+
+
+def automated_hypotheses_formulation(
+ dataframe: pd.DataFrame,
+ executor=openai_query,
+ obtain_query: bool = True,
+ execute_query: bool = True,
+ max_len=10000,
+ **kwargs
+) -> Union[str, List[Tuple[str, str, Union[str, None]]]]:
+ """
+ Automatically formulate some hypotheses on the event data.
+ The result of this method is either:
+ - The prompt (to be executed manually against the LLM) when obtain_query=False
+ - A list of different hypotheses. Each hypothesis comes with a description (position 0), the SQL query (position 1),
+ and (if execute_query=True) the result of the execution of the query in position 2.
+
+ :param dataframe: event log object
+ :param executor: the connector to the LLM (e.g., pm4py.llm.openai_query)
+ :param obtain_query: executes the prompt and get the hypotheses along with the corresponding SQL queries
+ :param execute_query: executes the obtained SQL queries and stores the results
+ :param kwargs: additional keyword arguments to the method
+ :param max_len: maximum length of the obtained prompt
+ :rtype: ``Union[str, List[Tuple[str, str, Union[str, None]]]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+ result = pm4py.llm.automated_hypotheses_formulation(log, api_key="sk-5HN")
+ print(result)
+ """
+ import duckdb
+ from pm4py.algo.querying.llm.abstractions import log_to_cols_descr
+
+ from pm4py.algo.querying.llm.injection import (
+ algorithm as domain_knowledge_injector,
+ )
+
+ 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"
+ prompt += abstract_dfg(dataframe, max_len=int(max_len / 3))
+ prompt += "\n\n"
+ prompt += log_to_cols_descr.apply(
+ dataframe, parameters={"max_len": int(max_len / 3)}
+ )
+ prompt += "\n\n"
+ prompt += domain_knowledge_injector.apply(dataframe, parameters=kwargs)
+ prompt += "Please provide each hypothesis along with a SQL query. Please include the SQL queries between the ```sql and the ``` tags.\n"
+ prompt += "Can you please include also a description of each hypothesis between some and tags?\n\n"
+
+ if obtain_query:
+ response = executor(prompt, **kwargs)
+
+ obtained_queries = response.split("```sql")
+ obtained_descriptions = response.split("")
+
+ if (
+ len(obtained_queries) > 1
+ and len(obtained_descriptions) > 1
+ and len(obtained_queries) == len(obtained_descriptions)
+ ):
+ del obtained_queries[0]
+ del obtained_descriptions[0]
+
+ obtained_queries = [x.split("```")[0] for x in obtained_queries]
+ obtained_descriptions = [
+ x.split("")[0].strip()
+ for x in obtained_descriptions
+ ]
+ obtained_results = [None] * len(obtained_descriptions)
+
+ if execute_query:
+ for i in range(len(obtained_queries)):
+ try:
+ obtained_results[i] = duckdb.sql(
+ obtained_queries[i]
+ ).to_df()
+ except BaseException:
+ print("Exception executing query nr. %d" % i)
+
+ return [
+ (
+ obtained_descriptions[i],
+ obtained_queries[i],
+ obtained_results[i],
+ )
+ for i in range(len(obtained_queries))
+ ]
+
+ return prompt
+
+
+def explain_visualization(
+ vis_saver, *args, connector=openai_query, **kwargs
+) -> str:
+ r"""Explains a process mining visualization using LLMs by saving it as a
+ .png image and providing the image to the Large Language Model along with a
+ description.
+
+ :param vis_saver: The visualizer function used to save the visualization to disk.
+ :param args: Positional arguments required by the visualizer function.
+ :param connector: (Optional) The connector method to communicate with the large language model (default: openai_query).
+ :param \**kwargs: Additional keyword arguments for the visualizer function or the connector (e.g., annotations, API key).
+ :return: The explanation of the visualization as a string.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
+ descr = pm4py.llm.explain_visualization(pm4py.save_vis_dotted_chart, log, api_key="sk-5HN", show_legend=False)
+ print(descr)
+ """
+ F = NamedTemporaryFile(suffix=".png")
+ image_path = F.name
+ F.close()
+
+ description = vis_saver(*args, image_path, **kwargs)
+
+ parameters = copy(kwargs) if kwargs is not None else {}
+ parameters["image_path"] = image_path
+
+ return connector(
+ "Could you explain the included process mining visualization?\n\n"
+ + description,
+ **parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/meta.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..ada4c8c525beb873c15ede1019c48c11efd72ca7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/meta.py
@@ -0,0 +1,29 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__name__ = "pm4py"
+__version__ = "2.7.23.11"
+VERSION = __version__
+__doc__ = "Process mining for Python"
+__author__ = "Process Intelligence Solutions (PIS)"
+__author_email__ = "info@processintelligence.solutions"
+__maintainer__ = "Process Intelligence Solutions (PIS)"
+__maintainer_email__ = "info@processintelligence.solutions"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ml.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ml.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dfaccf7df78b517999ad5a278b372135328c21e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ml.py
@@ -0,0 +1,543 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+The ``pm4py.ml`` module contains the machine learning features offered in ``pm4py``.
+"""
+
+from typing import Union, Tuple, Any, List, Collection, Optional
+import pandas as pd
+import numpy as np
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.log.obj import EventLog
+from pm4py.utils import __event_log_deprecation_warning
+import random
+from copy import copy
+from pm4py.util.pandas_utils import (
+ check_is_pandas_dataframe,
+ check_pandas_dataframe_columns,
+)
+from pm4py.utils import get_properties, constants, pandas_utils, is_polars_lazyframe, check_is_pandas_dataframe
+
+
+def split_train_test(
+ log: Union[EventLog, pd.DataFrame],
+ train_percentage: float = 0.8,
+ case_id_key: str = "case:concept:name",
+) -> Union[Tuple[EventLog, EventLog], Tuple[pd.DataFrame, pd.DataFrame]]:
+ """
+ Splits an event log into a training log and a test log for machine learning purposes.
+
+ This function separates the provided log into two parts based on the specified training percentage.
+ It ensures that entire cases are included in either the training set or the test set.
+
+ :param log: The event log or Pandas DataFrame to be split.
+ :param train_percentage: Fraction of cases to be included in the training log (between 0.0 and 1.0).
+ :param case_id_key: Attribute to be used as the case identifier.
+ :return: A tuple containing the training and test event logs or DataFrames.
+ :rtype: ``Union[Tuple[EventLog, EventLog], Tuple[pd.DataFrame, pd.DataFrame]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ train_df, test_df = pm4py.split_train_test(dataframe, train_percentage=0.75)
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(log)
+ cases = pandas_utils.format_unique(log[case_id_key].unique())
+ train_cases = set()
+ test_cases = set()
+ for c in cases:
+ r = random.random()
+ if r <= train_percentage:
+ train_cases.add(c)
+ else:
+ test_cases.add(c)
+ train_df = log[log[case_id_key].isin(train_cases)]
+ test_df = log[log[case_id_key].isin(test_cases)]
+ return train_df, test_df
+ else:
+ from pm4py.objects.log.util import split_train_test
+
+ return split_train_test.split(log, train_percentage=train_percentage)
+
+
+def get_prefixes_from_log(
+ log: Union[EventLog, pd.DataFrame],
+ length: int,
+ case_id_key: str = "case:concept:name",
+) -> Union[EventLog, pd.DataFrame]:
+ """
+ Retrieves prefixes of traces in a log up to a specified length.
+
+ The returned log contains prefixes of each trace:
+
+ - If a trace has a length less than or equal to the specified length, it is included as-is.
+ - If a trace exceeds the specified length, it is truncated to that length.
+
+ :param log: The event log or Pandas DataFrame from which to extract prefixes.
+ :param length: The maximum length of prefixes to extract.
+ :param case_id_key: Attribute to be used as the case identifier.
+ :return: A log containing the prefixes of the original log.
+ :rtype: ``Union[EventLog, pd.DataFrame]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ trimmed_df = pm4py.get_prefixes_from_log(dataframe, length=5, case_id_key='case:concept:name')
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
+ from pm4py.util import pandas_utils
+
+ log = pandas_utils.insert_ev_in_tr_index(log, case_id=case_id_key)
+ return log[log[constants.DEFAULT_INDEX_IN_TRACE_KEY] <= (length - 1)]
+ else:
+ from pm4py.objects.log.util import get_prefixes
+
+ return get_prefixes.get_prefixes_from_log(log, length)
+
+
+def extract_outcome_enriched_dataframe(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+ start_timestamp_key: str = "time:timestamp",
+) -> pd.DataFrame:
+ """
+ Enriches a dataframe with additional outcome-related columns computed from the entire case.
+
+ This function adds columns that model the outcome of each case by computing metrics such as
+ arrival rates and service waiting times.
+
+ :param log: The event log or Pandas DataFrame to be enriched.
+ :param activity_key: Attribute to be used for the activity.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as the case identifier.
+ :param start_timestamp_key: Attribute to be used as the start timestamp.
+ :return: An enriched Pandas DataFrame with additional outcome-related columns.
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ enriched_df = pm4py.extract_outcome_enriched_dataframe(
+ log,
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name',
+ start_timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+
+ if not check_is_pandas_dataframe(log):
+ from pm4py.objects.conversion.log import converter as log_converter
+ log = log_converter.apply(
+ log,
+ variant=log_converter.Variants.TO_DATA_FRAME,
+ parameters=properties,
+ )
+
+ log = copy(log)
+ fea_df = extract_features_dataframe(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ include_case_id=True,
+ )
+ log = pandas_utils.insert_case_arrival_finish_rate(
+ log,
+ timestamp_column=timestamp_key,
+ case_id_column=case_id_key,
+ start_timestamp_column=start_timestamp_key,
+ )
+ log = pandas_utils.insert_case_service_waiting_time(
+ log,
+ timestamp_column=timestamp_key,
+ case_id_column=case_id_key,
+ start_timestamp_column=start_timestamp_key,
+ )
+
+ if is_polars_lazyframe(log):
+ return log.join(fea_df, on=case_id_key, maintain_order="left")
+ else:
+ return log.merge(fea_df, on=case_id_key)
+
+
+def extract_features_dataframe(
+ log: Union[EventLog, pd.DataFrame],
+ str_tr_attr: Optional[List[str]] = None,
+ num_tr_attr: Optional[List[str]] = None,
+ str_ev_attr: Optional[List[str]] = None,
+ num_ev_attr: Optional[List[str]] = None,
+ str_evsucc_attr: Optional[List[str]] = None,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: Optional[str] = None,
+ resource_key: str = "org:resource",
+ include_case_id: bool = False,
+ count_occurrences: bool = False,
+ enable_numeric_attribute_statistics: bool = False,
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
+ **kwargs,
+) -> pd.DataFrame:
+ r"""
+ Extracts a dataframe containing features for each case in the provided
+ log object.
+
+ This function processes the log to generate a set of features that can be used for machine learning tasks.
+ Features can include both case-level and event-level attributes, with options for one-hot encoding.
+
+ :param log: The event log or Pandas DataFrame from which to extract features.
+ :param str_tr_attr: (Optional) List of string attributes at the case level to extract as features.
+ :param num_tr_attr: (Optional) List of numeric attributes at the case level to extract as features.
+ :param str_ev_attr: (Optional) List of string attributes at the event level to extract as features (one-hot encoded).
+ :param num_ev_attr: (Optional) List of numeric attributes at the event level to extract as features
+ (uses the last value per attribute in a case).
+ :param str_evsucc_attr: (Optional) List of string successor attributes at the event level to extract as features.
+ :param activity_key: Attribute to be used as the activity identifier.
+ :param timestamp_key: Attribute to be used for timestamps.
+ :param case_id_key: (Optional) Attribute to be used as the case identifier. If not provided, the default is used.
+ :param resource_key: Attribute to be used as the resource identifier.
+ :param include_case_id: Whether to include the case identifier column in the features table.
+ :param count_occurrences: If True, count occurrences of string attributes instead of binary encoding.
+ :param enable_numeric_attribute_statistics: If True, expand numeric attributes to aggregation columns. If False,
+ keep the existing ``ATTRIBUTE`` last-value column unless
+ ``numeric_attribute_aggregations`` is provided. If not provided,
+ defaults to False.
+ :param numeric_attribute_aggregations: Optional collection of numeric aggregations to compute. Supported values are
+ ``last``, ``first``, ``min``, ``max``, ``mean``, ``median``, ``stdev``,
+ and ``sum``. Applied only to numeric attributes whose names do not start
+ with ``@@``.
+ :param \**kwargs: Additional keyword arguments to pass to the feature extraction algorithm.
+ :return: A Pandas DataFrame containing the extracted features for each case.
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ features_df = pm4py.extract_features_dataframe(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = kwargs if kwargs else {}
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ for prop in properties:
+ parameters[prop] = properties[prop]
+
+ parameters["str_tr_attr"] = str_tr_attr or []
+ parameters["num_tr_attr"] = num_tr_attr or []
+ parameters["str_ev_attr"] = str_ev_attr or []
+ parameters["num_ev_attr"] = num_ev_attr or []
+ parameters["str_evsucc_attr"] = str_evsucc_attr or []
+ parameters["add_case_identifier_column"] = include_case_id
+ parameters["count_occurrences"] = count_occurrences
+ if enable_numeric_attribute_statistics is None:
+ enable_numeric_attribute_statistics = False
+ parameters["enable_numeric_attribute_statistics"] = (
+ enable_numeric_attribute_statistics
+ )
+ if numeric_attribute_aggregations is not None:
+ parameters["numeric_attribute_aggregations"] = (
+ numeric_attribute_aggregations
+ )
+
+ from pm4py.algo.transformation.trace_encodings import (
+ algorithm as trace_encodings,
+ )
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ case_id_key=case_id_key,
+ timestamp_key=timestamp_key,
+ )
+
+ data, feature_names = trace_encodings.apply(log, parameters=parameters)
+ if is_polars_lazyframe(data):
+ return data
+
+ return pandas_utils.instantiate_dataframe(data, columns=feature_names)
+
+
+def extract_ocel_features(
+ ocel: OCEL,
+ obj_type: str,
+ enable_object_lifecycle_paths: bool = True,
+ enable_object_work_in_progress: bool = False,
+ object_str_attributes: Optional[Collection[str]] = None,
+ object_num_attributes: Optional[Collection[str]] = None,
+ include_obj_id: bool = False,
+ debug: bool = False,
+) -> pd.DataFrame:
+ """
+ Extracts a set of features from an object-centric event log (OCEL) for objects of a specified type.
+
+ This function computes various features based on the lifecycle paths and work-in-progress metrics
+ of objects within the OCEL. It also supports encoding of string and numeric object attributes.
+
+ The approach is based on:
+ Berti, A., Herforth, J., Qafari, M.S. et al. Graph-based feature extraction on object-centric event logs.
+ Int J Data Sci Anal (2023). https://doi.org/10.1007/s41060-023-00428-2
+
+ :param ocel: The object-centric event log from which to extract features.
+ :param obj_type: The object type to consider for feature extraction.
+ :param enable_object_lifecycle_paths: Whether to enable the "lifecycle paths" feature.
+ :param enable_object_work_in_progress: Whether to enable the "work in progress" feature,
+ which has a high computational cost.
+ :param object_str_attributes: (Optional) Collection of string attributes at the object level to one-hot encode.
+ :param object_num_attributes: (Optional) Collection of numeric attributes at the object level to encode.
+ :param include_obj_id: Whether to include the object identifier as a column in the features DataFrame.
+ :param debug: Whether to enable debugging mode to track the feature extraction process.
+ :return: A Pandas DataFrame containing the extracted features for the specified object type.
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('log.jsonocel')
+ fea_df = pm4py.extract_ocel_features(ocel, "item")
+ """
+ if object_str_attributes is None:
+ object_str_attributes = []
+
+ if object_num_attributes is None:
+ object_num_attributes = []
+
+ parameters = {
+ "filter_per_type": obj_type,
+ "enable_object_lifecycle_paths": enable_object_lifecycle_paths,
+ "enable_object_work_in_progress": enable_object_work_in_progress,
+ "enable_object_str_attributes": bool(object_str_attributes),
+ "enable_object_num_attributes": bool(object_num_attributes),
+ "str_obj_attr": object_str_attributes,
+ "num_obj_attr": object_num_attributes,
+ "debug": debug,
+ }
+
+ from pm4py.algo.transformation.ocel.features.objects import (
+ algorithm as ocel_feature_extraction,
+ )
+
+ data, feature_names = ocel_feature_extraction.apply(
+ ocel, parameters=parameters
+ )
+
+ dataframe = pandas_utils.instantiate_dataframe(data, columns=feature_names)
+ dataframe = dataframe.dropna(how="any", axis=1)
+ dataframe = dataframe.select_dtypes(include=np.number)
+
+ if include_obj_id:
+ objects_with_type = ocel.objects[
+ [ocel.object_id_column, ocel.object_type_column]
+ ].to_dict(orient="records")
+ objects_with_type = [
+ x[ocel.object_id_column]
+ for x in objects_with_type
+ if x[ocel.object_type_column] == obj_type
+ ]
+ dataframe[ocel.object_id_column] = objects_with_type
+
+ return dataframe
+
+
+def extract_temporal_features_dataframe(
+ log: Union[EventLog, pd.DataFrame],
+ grouper_freq: str = "W",
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: Optional[str] = None,
+ start_timestamp_key: str = "time:timestamp",
+ resource_key: str = "org:resource",
+) -> pd.DataFrame:
+ """
+ Extracts temporal features from a log object and returns them as a dataframe.
+
+ This function computes temporal metrics based on the specified grouping frequency, which can be
+ daily (D), weekly (W), monthly (M), or yearly (Y). These features are useful for analyzing
+ system dynamics and simulation in the context of process mining.
+
+ The approach is based on:
+ Pourbafrani, Mahsa, Sebastiaan J. van Zelst, and Wil MP van der Aalst.
+ "Supporting automatic system dynamics model generation for simulation in the context of process mining."
+ International Conference on Business Information Systems. Springer, Cham, 2020.
+
+ :param log: The event log or Pandas DataFrame from which to extract temporal features.
+ :param grouper_freq: The frequency to use for grouping (e.g., 'D' for daily, 'W' for weekly,
+ 'M' for monthly, 'Y' for yearly).
+ :param activity_key: Attribute to be used as the activity identifier.
+ :param timestamp_key: Attribute to be used for timestamps.
+ :param case_id_key: (Optional) Attribute to be used as the case identifier. If not provided, the default is used.
+ :param start_timestamp_key: Attribute to be used as the start timestamp.
+ :param resource_key: Attribute to be used as the resource identifier.
+ :return: A Pandas DataFrame containing the extracted temporal features.
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ temporal_features_df = pm4py.extract_temporal_features_dataframe(
+ dataframe,
+ activity_key='concept:name',
+ case_id_key='case:concept:name',
+ timestamp_key='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ parameters["grouper_freq"] = grouper_freq
+ parameters["pm4py:param:activity_key"] = activity_key
+ parameters["pm4py:param:timestamp_key"] = timestamp_key
+ if case_id_key is not None:
+ parameters["pm4py:param:case_id_key"] = case_id_key
+ parameters["pm4py:param:start_timestamp_key"] = (
+ start_timestamp_key
+ )
+ parameters["pm4py:param:resource_key"] = resource_key
+
+ if is_polars_lazyframe(log):
+ from pm4py.algo.transformation.trace_encodings.variants import temporal_lazy as temporal
+ else:
+ from pm4py.algo.transformation.trace_encodings.variants import temporal
+
+ return temporal.apply(log, parameters=parameters)
+
+
+def extract_target_vector(
+ log: Union[EventLog, pd.DataFrame],
+ variant: str,
+ activity_key: str = "concept:name",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> Tuple[Any, List[str]]:
+ """
+ Extracts the target vector from a log object for a specific machine learning use case.
+
+ Supported variants include:
+
+ - 'next_activity': Predicts the next activity in a case.
+ - 'next_time': Predicts the timestamp of the next activity.
+ - 'remaining_time': Predicts the remaining time for the case.
+
+ :param log: The event log or Pandas DataFrame from which to extract the target vector.
+ :param variant: The variant of the algorithm to use. Must be one of:
+ 'next_activity', 'next_time', 'remaining_time'.
+ :param activity_key: Attribute to be used as the activity identifier.
+ :param timestamp_key: Attribute to be used for timestamps.
+ :param case_id_key: Attribute to be used as the case identifier.
+ :return: A tuple containing the target vector and a list of class labels (if applicable).
+ :rtype: ``Tuple[Any, List[str]]``
+
+ :raises Exception: If an unsupported variant is provided.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ vector_next_act, class_next_act = pm4py.extract_target_vector(
+ log,
+ 'next_activity',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ vector_next_time, class_next_time = pm4py.extract_target_vector(
+ log,
+ 'next_time',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ vector_rem_time, class_rem_time = pm4py.extract_target_vector(
+ log,
+ 'remaining_time',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ parameters = get_properties(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.transformation.log_to_target import (
+ algorithm as log_to_target,
+ )
+
+ var_map = {
+ "next_activity": log_to_target.Variants.NEXT_ACTIVITY,
+ "next_time": log_to_target.Variants.NEXT_TIME,
+ "remaining_time": log_to_target.Variants.REMAINING_TIME,
+ }
+
+ if variant not in var_map:
+ raise Exception(
+ "Please provide the variant as one of the following: 'next_activity', 'next_time', 'remaining_time'."
+ )
+
+ target, classes = log_to_target.apply(
+ log, variant=var_map[variant], parameters=parameters
+ )
+ return target, classes
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9ef3b19b56c2bd0f9e304338410aa14b3d35dba
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/__init__.py
@@ -0,0 +1,43 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects import (
+ log,
+ petri_net,
+ transition_system,
+ conversion,
+ process_tree,
+ dfg,
+ trie,
+ org,
+ heuristics_net,
+ genetic_matrix,
+ ocel,
+ powl,
+ random_variables,
+ )
+ import importlib.util
+
+ if importlib.util.find_spec("networkx"):
+ from pm4py.objects import bpmn
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..452faedb4f211dd923b8c37fea839a46066976d0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/__init__.py
@@ -0,0 +1,29 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.bpmn import obj, exporter, layout, semantics, util
+ import importlib.util
+
+ if importlib.util.find_spec("lxml"):
+ from pm4py.objects.bpmn import importer
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..04612959fb3e24dfcebcaf1231de7539971f6cd5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.exporter import exporter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a2fe39028a2269d2571cd57982f62af5020a176
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/exporter.py
@@ -0,0 +1,83 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.bpmn.exporter.variants import etree
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ ETREE = etree
+
+
+DEFAULT_VARIANT = Variants.ETREE
+
+
+def apply(bpmn_graph, target_path, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Exports the BPMN diagram to a file
+
+ Parameters
+ -------------
+ bpmn_graph
+ BPMN diagram
+ target_path
+ Target path
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.ETREE
+ parameters
+ Possible parameters of the algorithm
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).apply(
+ bpmn_graph, target_path, parameters=parameters
+ )
+
+
+def serialize(bpmn_graph, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Serializes the BPMN object into a binary string
+
+ Parameters
+ -------------
+ bpmn_graph
+ BPMN diagram
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.ETREE
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ -------------
+ serialization
+ Binary string (BPMN 2.0 XML standard)
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).get_xml_string(
+ bpmn_graph, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a44298beae10e3ada4887d9f88b52383f666a964
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.exporter.variants import etree
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/etree.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/etree.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c28b4f6f37bd92feef7db4ddcad9c3fa0b8baad
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/etree.py
@@ -0,0 +1,369 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import uuid
+
+from pm4py.objects.bpmn.obj import BPMN
+from pm4py.util import constants, exec_utils
+from enum import Enum
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+ ENABLE_BPMN_PLANE_EXPORTING = "enble_bpmn_plane_exporting"
+ ENABLE_INCOMING_OUTGOING_EXPORTING = "enable_incoming_outgoing_exporting"
+
+
+def apply(bpmn_graph, target_path, parameters=None):
+ """
+ Exports the BPMN diagram to a file
+
+ Parameters
+ -------------
+ bpmn_graph
+ BPMN diagram
+ target_path
+ Target path
+ parameters
+ Possible parameters of the algorithm
+ """
+ xml_string = get_xml_string(bpmn_graph, parameters=parameters)
+ F = open(target_path, "wb")
+ F.write(xml_string)
+ F.close()
+
+
+def get_xml_string(bpmn_graph, parameters=None):
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ enble_bpmn_plane_exporting = exec_utils.get_param_value(
+ Parameters.ENABLE_BPMN_PLANE_EXPORTING, parameters, True
+ )
+ enable_incoming_outgoing_exporting = exec_utils.get_param_value(
+ Parameters.ENABLE_INCOMING_OUTGOING_EXPORTING, parameters, True
+ )
+
+ layout = bpmn_graph.get_layout()
+
+ import xml.etree.ElementTree as ET
+ from xml.dom import minidom
+
+ definitions = ET.Element("bpmn:definitions")
+ definitions.set(
+ "xmlns:bpmn", "http://www.omg.org/spec/BPMN/20100524/MODEL"
+ )
+ definitions.set("xmlns:bpmndi", "http://www.omg.org/spec/BPMN/20100524/DI")
+ definitions.set("xmlns:omgdc", "http://www.omg.org/spec/DD/20100524/DC")
+ definitions.set("xmlns:omgdi", "http://www.omg.org/spec/DD/20100524/DI")
+ definitions.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
+ definitions.set("targetNamespace", "http://www.signavio.com/bpmn20")
+ definitions.set("typeLanguage", "http://www.w3.org/2001/XMLSchema")
+ definitions.set("expressionLanguage", "http://www.w3.org/1999/XPath")
+ definitions.set("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
+
+ all_processes = set()
+ process_planes = {}
+ process_process = {}
+ process_collaboration = None
+
+ for node in bpmn_graph.get_nodes():
+ all_processes.add(node.get_process())
+ for flow in bpmn_graph.get_flows():
+ all_processes.add(flow.get_process())
+
+ if len(all_processes) > 1:
+ # when several swimlanes exist, their elements should be annexed to the
+ # same BPMN plane
+ collaboration_nodes = [
+ x
+ for x in bpmn_graph.get_nodes()
+ if isinstance(x, BPMN.Collaboration)
+ ]
+ if collaboration_nodes:
+ bpmn_plane_id = collaboration_nodes[0].get_id()
+
+ process_collaboration = ET.SubElement(
+ definitions, "bpmn:collaboration", {"id": bpmn_plane_id}
+ )
+
+ participant_nodes = [
+ x
+ for x in bpmn_graph.get_nodes()
+ if isinstance(x, BPMN.Participant)
+ ]
+ if participant_nodes:
+ for process in participant_nodes:
+ ET.SubElement(
+ process_collaboration,
+ "bpmn:participant",
+ {
+ "id": process.get_id(),
+ "name": process.get_name(),
+ "processRef": "id" + process.process_ref,
+ },
+ )
+ all_processes.add(process.process_ref)
+ else:
+ bpmn_plane_id = "id" + list(all_processes)[0]
+
+ for process in all_processes:
+ if process != bpmn_plane_id:
+ p = ET.SubElement(
+ definitions,
+ "bpmn:process",
+ {
+ "id": "id" + process,
+ "isClosed": "false",
+ "isExecutable": "false",
+ "processType": "None",
+ },
+ )
+ process_process[process] = p
+ elif process_collaboration is not None:
+ process_process[process] = process_collaboration
+
+ diagram = ET.SubElement(
+ definitions,
+ "bpmndi:BPMNDiagram",
+ {"id": "id" + str(uuid.uuid4()), "name": "diagram"},
+ )
+
+ if enble_bpmn_plane_exporting:
+ plane = ET.SubElement(
+ diagram,
+ "bpmndi:BPMNPlane",
+ {"bpmnElement": bpmn_plane_id, "id": "id" + str(uuid.uuid4())},
+ )
+ for process in all_processes:
+ process_planes[process] = plane
+
+ for node in bpmn_graph.get_nodes():
+ process = node.get_process()
+
+ if process != bpmn_plane_id:
+ node_shape = ET.SubElement(
+ process_planes[process],
+ "bpmndi:BPMNShape",
+ {
+ "bpmnElement": node.get_id(),
+ "id": node.get_id() + "_gui",
+ },
+ )
+ node_shape_layout = ET.SubElement(
+ node_shape,
+ "omgdc:Bounds",
+ {
+ "height": str(layout.get(node).get_height()),
+ "width": str(layout.get(node).get_width()),
+ "x": str(layout.get(node).get_x()),
+ "y": str(layout.get(node).get_y()),
+ },
+ )
+
+ for flow in bpmn_graph.get_flows():
+ process = flow.get_process()
+
+ flow_shape = ET.SubElement(
+ process_planes[process],
+ "bpmndi:BPMNEdge",
+ {
+ "bpmnElement": "id" + str(flow.get_id()),
+ "id": "id" + str(flow.get_id()) + "_gui",
+ },
+ )
+ for x, y in layout.get(flow).get_waypoints():
+ waypoint = ET.SubElement(
+ flow_shape, "omgdi:waypoint", {"x": str(x), "y": str(y)}
+ )
+
+ for node in bpmn_graph.get_nodes():
+ process = process_process[node.get_process()]
+
+ if isinstance(node, BPMN.TextAnnotation):
+ annotation = ET.SubElement(
+ process, "bpmn:textAnnotation", {"id": node.get_id()}
+ )
+ text = ET.SubElement(annotation, "bpmn:text")
+ text.text = node.text
+ elif isinstance(node, BPMN.StartEvent):
+ isInterrupting = "true" if node.get_isInterrupting() else "false"
+ parallelMultiple = (
+ "true" if node.get_parallelMultiple() else "false"
+ )
+ task = ET.SubElement(
+ process,
+ "bpmn:startEvent",
+ {
+ "id": node.get_id(),
+ "isInterrupting": isInterrupting,
+ "name": node.get_name(),
+ "parallelMultiple": parallelMultiple,
+ },
+ )
+ elif isinstance(node, BPMN.EndEvent):
+ task = ET.SubElement(
+ process,
+ "bpmn:endEvent",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ elif isinstance(node, BPMN.IntermediateCatchEvent):
+ task = ET.SubElement(
+ process,
+ "bpmn:intermediateCatchEvent",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ messageEventDefinition = ET.SubElement(
+ task, "bpmn:messageEventDefinition"
+ )
+ elif isinstance(node, BPMN.IntermediateThrowEvent):
+ task = ET.SubElement(
+ process,
+ "bpmn:intermediateThrowEvent",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ elif isinstance(node, BPMN.BoundaryEvent):
+ task = ET.SubElement(
+ process,
+ "bpmn:boundaryEvent",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ elif isinstance(node, BPMN.Task):
+ if isinstance(node, BPMN.UserTask):
+ task = ET.SubElement(
+ process,
+ "bpmn:userTask",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ elif isinstance(node, BPMN.SendTask):
+ task = ET.SubElement(
+ process,
+ "bpmn:sendTask",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ else:
+ task = ET.SubElement(
+ process,
+ "bpmn:task",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ elif isinstance(node, BPMN.SubProcess):
+ task = ET.SubElement(
+ process,
+ "bpmn:subProcess",
+ {"id": node.get_id(), "name": node.get_name()},
+ )
+ elif isinstance(node, BPMN.ExclusiveGateway):
+ task = ET.SubElement(
+ process,
+ "bpmn:exclusiveGateway",
+ {
+ "id": node.get_id(),
+ "gatewayDirection": node.get_gateway_direction().value,
+ "name": node.get_name(),
+ },
+ )
+ elif isinstance(node, BPMN.ParallelGateway):
+ task = ET.SubElement(
+ process,
+ "bpmn:parallelGateway",
+ {
+ "id": node.get_id(),
+ "gatewayDirection": node.get_gateway_direction().value,
+ "name": node.get_name(),
+ },
+ )
+ elif isinstance(node, BPMN.InclusiveGateway):
+ task = ET.SubElement(
+ process,
+ "bpmn:inclusiveGateway",
+ {
+ "id": node.get_id(),
+ "gatewayDirection": node.get_gateway_direction().value,
+ "name": node.get_name(),
+ },
+ )
+ elif isinstance(node, BPMN.EventBasedGateway):
+ task = ET.SubElement(
+ process,
+ "bpmn:eventBasedGateway",
+ {
+ "id": node.get_id(),
+ "gatewayDirection": node.get_gateway_direction().value,
+ "name": node.get_name(),
+ },
+ )
+
+ if enable_incoming_outgoing_exporting:
+ for in_arc in node.get_in_arcs():
+ arc_xml = ET.SubElement(task, "bpmn:incoming")
+ arc_xml.text = "id" + str(in_arc.get_id())
+
+ for out_arc in node.get_out_arcs():
+ arc_xml = ET.SubElement(task, "bpmn:outgoing")
+ arc_xml.text = "id" + str(out_arc.get_id())
+
+ for flow in bpmn_graph.get_flows():
+ process = process_process[flow.get_process()]
+
+ source = flow.get_source()
+ target = flow.get_target()
+
+ if isinstance(flow, BPMN.SequenceFlow):
+ flow_xml = ET.SubElement(
+ process,
+ "bpmn:sequenceFlow",
+ {
+ "id": "id" + str(flow.get_id()),
+ "name": flow.get_name(),
+ "sourceRef": str(source.get_id()),
+ "targetRef": str(target.get_id()),
+ },
+ )
+ elif isinstance(flow, BPMN.MessageFlow):
+ flow_xml = ET.SubElement(
+ process,
+ "bpmn:messageFlow",
+ {
+ "id": "id" + str(flow.get_id()),
+ "name": flow.get_name(),
+ "sourceRef": str(source.get_id()),
+ "targetRef": str(target.get_id()),
+ },
+ )
+
+ elif isinstance(flow, BPMN.Association):
+ flow_xml = ET.SubElement(
+ process,
+ "bpmn:association",
+ {
+ "id": "id" + str(flow.get_id()),
+ "sourceRef": str(source.get_id()),
+ "targetRef": str(target.get_id()),
+ },
+ )
+
+ return minidom.parseString(ET.tostring(definitions)).toprettyxml(
+ encoding=encoding
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..20a002608e730908882046a78036783c1c39ee8e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.importer import importer, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a595e8570723d7a673bccef355d6ce0799f0157
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/importer.py
@@ -0,0 +1,84 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.bpmn.importer.variants import lxml
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ LXML = lxml
+
+
+DEFAULT_VARIANT = Variants.LXML
+
+
+def apply(path, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Imports a BPMN diagram from a file
+
+ Parameters
+ -------------
+ path
+ Path to the file
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.LXML
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ bpmn_graph
+ BPMN graph
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).apply(path, parameters=parameters)
+
+
+def deserialize(bpmn_string, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Deserialize a text/binary string representing a BPMN 2.0
+
+ Parameters
+ -------------
+ bpmn_string
+ BPMN string
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.LXML
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ bpmn_graph
+ BPMN graph
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).import_from_string(
+ bpmn_string, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1c3d71a8508581e112b875a129e1cff17ad9a9e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.importer.variants import lxml
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/lxml.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/lxml.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7519a8f76cb371d66af6799d9e1f4b822e1227a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/lxml.py
@@ -0,0 +1,736 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.obj import BPMN
+from pm4py.util import constants, exec_utils
+from enum import Enum
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+class Counts:
+ def __init__(self):
+ self.number_processes = 0
+
+
+def parse_element(
+ bpmn_graph,
+ counts,
+ curr_el,
+ parents,
+ incoming_dict,
+ outgoing_dict,
+ nodes_dict,
+ nodes_bounds,
+ flow_info,
+ process=None,
+ node=None,
+ bpmn_element=None,
+ flow=None,
+ rec_depth=0,
+):
+ """
+ Parses a BPMN element from the XML file
+ """
+ layout = bpmn_graph.get_layout()
+ tag = curr_el.tag.lower()
+
+ if curr_el.get("id") is not None:
+ if tag.endswith("collaboration"):
+ collaboration_id = curr_el.get("id")
+ collaboration = BPMN.Collaboration(
+ id=collaboration_id, process=collaboration_id
+ )
+ bpmn_graph.add_node(collaboration)
+ nodes_dict[collaboration_id] = collaboration
+ elif tag.endswith("participant"):
+ participant_id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ process_ref = curr_el.get("processRef")
+ participant = BPMN.Participant(
+ id=participant_id,
+ name=name,
+ process=None,
+ process_ref=process_ref,
+ )
+ bpmn_graph.add_node(participant)
+ nodes_dict[participant_id] = participant
+ elif tag.endswith("textannotation"):
+ annotation_id = curr_el.get("id")
+ text = ""
+ for child in curr_el:
+ text = child.text
+ annotation = BPMN.TextAnnotation(
+ id=annotation_id, text=text, process=process
+ )
+ bpmn_graph.add_node(annotation)
+ nodes_dict[annotation_id] = annotation
+ elif tag.endswith("subprocess"): # subprocess invocation
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ subprocess = BPMN.SubProcess(
+ id=curr_el.get("id"),
+ name=name,
+ process=process,
+ depth=rec_depth,
+ )
+ bpmn_graph.add_node(subprocess)
+ node = subprocess
+ process = curr_el.get("id")
+ nodes_dict[process] = node
+ elif tag.endswith("process"): # process of the current subtree
+ process = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ bpmn_graph.set_process_id(process)
+ bpmn_graph.set_name(name)
+ elif tag.endswith(
+ "shape"
+ ): # shape of a node, contains x,y,width,height information
+ bpmn_element = curr_el.get("bpmnElement")
+ elif tag.endswith("task"): # simple task object
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ # this_type = str(curr_el.tag)
+ # this_type = this_type[this_type.index("}") + 1:]
+ if tag.endswith("usertask"):
+ task = BPMN.UserTask(id=id, name=name, process=process)
+ elif tag.endswith("sendtask"):
+ task = BPMN.SendTask(id=id, name=name, process=process)
+ else:
+ task = BPMN.Task(id=id, name=name, process=process)
+ bpmn_graph.add_node(task)
+ node = task
+ nodes_dict[id] = node
+ elif tag.endswith(
+ "startevent"
+ ): # start node starting the (sub)process
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ event_definitions = [
+ child.tag.lower().replace("eventdefinition", "")
+ for child in curr_el
+ if child.tag.lower().endswith("eventdefinition")
+ ]
+ if len(event_definitions) > 0:
+ event_type = event_definitions[0]
+ if event_type.endswith("message"):
+ start_event = BPMN.MessageStartEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ else: # TODO: expand functionality, support more start event types
+ start_event = BPMN.NormalStartEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ else:
+ start_event = BPMN.NormalStartEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ bpmn_graph.add_node(start_event)
+ node = start_event
+ nodes_dict[id] = node
+ elif tag.endswith("endevent"): # end node ending the (sub)process
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ event_definitions = [
+ child.tag.lower().replace("eventdefinition", "")
+ for child in curr_el
+ if child.tag.lower().endswith("eventdefinition")
+ ]
+ if len(event_definitions) > 0:
+ event_type = event_definitions[0]
+ if event_type.endswith("message"):
+ end_event = BPMN.MessageEndEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ elif event_type.endswith("terminate"):
+ end_event = BPMN.TerminateEndEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ elif event_type.endswith("error"):
+ end_event = BPMN.ErrorEndEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ elif event_type.endswith("cancel"):
+ end_event = BPMN.CancelEndEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ else: # TODO: expand functionality, support more start event types
+ end_event = BPMN.NormalEndEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ else:
+ end_event = BPMN.NormalEndEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ bpmn_graph.add_node(end_event)
+ node = end_event
+ nodes_dict[id] = node
+ elif tag.endswith(
+ "intermediatecatchevent"
+ ): # intermediate event that happens (externally) and can be catched
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ event_definitions = [
+ child.tag.lower().replace("eventdefinition", "")
+ for child in curr_el
+ if child.tag.lower().endswith("eventdefinition")
+ ]
+ if len(event_definitions) > 0:
+ event_type = event_definitions[0]
+ if event_type.endswith("message"):
+ intermediate_catch_event = (
+ BPMN.MessageIntermediateCatchEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ )
+ elif event_type.endswith("error"):
+ intermediate_catch_event = (
+ BPMN.ErrorIntermediateCatchEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ )
+ elif event_type.endswith("cancel"):
+ intermediate_catch_event = (
+ BPMN.CancelIntermediateCatchEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ )
+ else:
+ intermediate_catch_event = BPMN.IntermediateCatchEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ else:
+ intermediate_catch_event = BPMN.IntermediateCatchEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ bpmn_graph.add_node(intermediate_catch_event)
+ node = intermediate_catch_event
+ nodes_dict[id] = node
+ elif tag.endswith(
+ "intermediatethrowevent"
+ ): # intermediate event that is activated through the (sub)process
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ event_definitions = [
+ child.tag.lower().replace("eventdefinition", "")
+ for child in curr_el
+ if child.tag.lower().endswith("eventdefinition")
+ ]
+ if len(event_definitions) > 0:
+ event_type = event_definitions[0]
+ if event_type.endswith("message"):
+ intermediate_throw_event = (
+ BPMN.MessageIntermediateThrowEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ )
+ else:
+ intermediate_throw_event = (
+ BPMN.NormalIntermediateThrowEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ )
+ else:
+ intermediate_throw_event = BPMN.NormalIntermediateThrowEvent(
+ id=curr_el.get("id"), name=name, process=process
+ )
+ bpmn_graph.add_node(intermediate_throw_event)
+ node = intermediate_throw_event
+ nodes_dict[id] = node
+ elif tag.endswith("boundaryevent"):
+ id = curr_el.get("id")
+ ref_activity = curr_el.get("attachedToRef")
+ name = (
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ event_definitions = [
+ child.tag.lower().replace("eventdefinition", "")
+ for child in curr_el
+ if child.tag.lower().endswith("eventdefinition")
+ ]
+ if len(event_definitions) > 0:
+ event_type = event_definitions[0]
+ if event_type.endswith("message"):
+ boundary_event = BPMN.MessageBoundaryEvent(
+ id=curr_el.get("id"),
+ name=name,
+ process=process,
+ activity=ref_activity,
+ )
+ elif event_type.endswith("error"):
+ boundary_event = BPMN.ErrorBoundaryEvent(
+ id=curr_el.get("id"),
+ name=name,
+ process=process,
+ activity=ref_activity,
+ )
+ elif event_type.endswith("cancel"):
+ boundary_event = BPMN.CancelBoundaryEvent(
+ id=curr_el.get("id"),
+ name=name,
+ process=process,
+ activity=ref_activity,
+ )
+ else:
+ boundary_event = BPMN.BoundaryEvent(
+ id=curr_el.get("id"),
+ name=name,
+ process=process,
+ activity=ref_activity,
+ )
+ else:
+ boundary_event = BPMN.BoundaryEvent(
+ id=curr_el.get("id"),
+ name=name,
+ process=process,
+ activity=ref_activity,
+ )
+ bpmn_graph.add_node(boundary_event)
+ node = boundary_event
+ nodes_dict[id] = node
+ elif tag.endswith("edge"): # related to the x, y information of an arc
+ bpmnElement = curr_el.get("bpmnElement")
+ flow = bpmnElement
+ elif tag.endswith("exclusivegateway"):
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ try:
+ direction = BPMN.Gateway.Direction[
+ curr_el.get("gatewayDirection").upper()
+ ]
+ exclusive_gateway = BPMN.ExclusiveGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=direction,
+ process=process,
+ )
+ except BaseException:
+ exclusive_gateway = BPMN.ExclusiveGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
+ process=process,
+ )
+ bpmn_graph.add_node(exclusive_gateway)
+ node = exclusive_gateway
+ nodes_dict[id] = node
+ elif tag.endswith("parallelgateway"):
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ try:
+ direction = BPMN.Gateway.Direction[
+ curr_el.get("gatewayDirection").upper()
+ ]
+ parallel_gateway = BPMN.ParallelGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=direction,
+ process=process,
+ )
+ except BaseException:
+ parallel_gateway = BPMN.ParallelGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
+ process=process,
+ )
+ bpmn_graph.add_node(parallel_gateway)
+ node = parallel_gateway
+ nodes_dict[id] = node
+ elif tag.endswith("inclusivegateway"):
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ try:
+ direction = BPMN.Gateway.Direction[
+ curr_el.get("gatewayDirection").upper()
+ ]
+ inclusive_gateway = BPMN.InclusiveGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=direction,
+ process=process,
+ )
+ except BaseException:
+ inclusive_gateway = BPMN.InclusiveGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
+ process=process,
+ )
+ bpmn_graph.add_node(inclusive_gateway)
+ node = inclusive_gateway
+ nodes_dict[id] = node
+ elif tag.endswith("eventbasedgateway"):
+ id = curr_el.get("id")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ try:
+ direction = BPMN.Gateway.Direction[
+ curr_el.get("gatewayDirection").upper()
+ ]
+ event_based_gateway = BPMN.EventBasedGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=direction,
+ process=process,
+ )
+ except BaseException:
+ event_based_gateway = BPMN.EventBasedGateway(
+ id=curr_el.get("id"),
+ name=name,
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
+ process=process,
+ )
+ bpmn_graph.add_node(event_based_gateway)
+ node = event_based_gateway
+ nodes_dict[id] = node
+ # FIXED: Moved the flow handling inside the id block
+ elif (
+ tag.endswith("sequenceflow")
+ or tag.endswith("messageflow")
+ or tag.endswith("association")
+ ):
+ seq_flow_id = curr_el.get("id")
+ source_ref = curr_el.get("sourceRef")
+ target_ref = curr_el.get("targetRef")
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ if source_ref is not None and target_ref is not None:
+ incoming_dict[seq_flow_id] = (
+ target_ref,
+ process,
+ tag,
+ name,
+ parents,
+ )
+ outgoing_dict[seq_flow_id] = (
+ source_ref,
+ process,
+ tag,
+ name,
+ parents,
+ )
+ elif tag.endswith("incoming"): # incoming flow of a node
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ if node is not None:
+ if curr_el.text.strip() not in incoming_dict:
+ incoming_dict[curr_el.text.strip()] = (
+ node,
+ process,
+ tag,
+ name,
+ parents,
+ )
+ elif tag.endswith("outgoing"): # outgoing flow of a node
+ name = (
+ curr_el.get("name").replace("\r", "").replace("\n", "")
+ if "name" in curr_el.attrib
+ else ""
+ )
+ if node is not None:
+ if curr_el.text.strip() not in outgoing_dict:
+ outgoing_dict[curr_el.text.strip()] = (
+ node,
+ process,
+ tag,
+ name,
+ parents,
+ )
+ elif tag.endswith(
+ "waypoint"
+ ): # contains information of x, y values of an edge
+ if flow is not None:
+ x = float(curr_el.get("x"))
+ y = float(curr_el.get("y"))
+ if flow not in flow_info:
+ flow_info[flow] = []
+ flow_info[flow].append((x, y))
+ elif tag.endswith(
+ "label"
+ ): # label of a node, mostly at the end of a shape object
+ bpmn_element = None
+ elif tag.endswith(
+ "bounds"
+ ): # contains information of width, height, x, y of a node
+ if bpmn_element is not None:
+ x = float(curr_el.get("x"))
+ y = float(curr_el.get("y"))
+ width = float(curr_el.get("width"))
+ height = float(curr_el.get("height"))
+ nodes_bounds[bpmn_element] = {
+ "x": x,
+ "y": y,
+ "width": width,
+ "height": height,
+ }
+
+ for child in curr_el:
+ bpmn_graph = parse_element(
+ bpmn_graph,
+ counts,
+ child,
+ list(parents) + [child],
+ incoming_dict,
+ outgoing_dict,
+ nodes_dict,
+ nodes_bounds,
+ flow_info,
+ process=process,
+ node=node,
+ bpmn_element=bpmn_element,
+ flow=flow,
+ rec_depth=rec_depth + 1,
+ )
+ # afterprocessing when the xml tree has been recursively parsed already
+ if rec_depth == 0:
+ # bpmn_graph.set_process_id(process)
+ for seq_flow_id in incoming_dict:
+ if incoming_dict[seq_flow_id][0] in nodes_dict:
+ incoming_dict[seq_flow_id] = (
+ nodes_dict[incoming_dict[seq_flow_id][0]],
+ incoming_dict[seq_flow_id][1],
+ incoming_dict[seq_flow_id][2],
+ incoming_dict[seq_flow_id][3],
+ incoming_dict[seq_flow_id][4],
+ )
+ for seq_flow_id in outgoing_dict:
+ if outgoing_dict[seq_flow_id][0] in nodes_dict:
+ outgoing_dict[seq_flow_id] = (
+ nodes_dict[outgoing_dict[seq_flow_id][0]], outgoing_dict[seq_flow_id][1], outgoing_dict[seq_flow_id][2],
+ outgoing_dict[seq_flow_id][3], outgoing_dict[seq_flow_id][4])
+
+ # also supports flows without waypoints
+ flows_without_waypoints = set(flow_info).union(
+ set(outgoing_dict).intersection(set(incoming_dict))
+ )
+ for flow_id in flows_without_waypoints:
+ flow_info[flow_id] = []
+
+ for flow_id in flow_info:
+ if flow_id in outgoing_dict and flow_id in incoming_dict:
+ flow = None
+ flow_type = outgoing_dict[flow_id][2]
+
+ if flow_type.endswith("messageflow"):
+ collaboration_id = None
+ for par in outgoing_dict[flow_id][4]:
+ par_tag = str(par.tag).lower()
+ if par_tag.endswith("collaboration"):
+ collaboration_id = par.get("id")
+ flow = BPMN.MessageFlow(
+ outgoing_dict[flow_id][0],
+ incoming_dict[flow_id][0],
+ id=flow_id,
+ name=outgoing_dict[flow_id][3],
+ process=collaboration_id,
+ )
+ elif flow_type.endswith("association"):
+ flow = BPMN.Association(
+ outgoing_dict[flow_id][0],
+ incoming_dict[flow_id][0],
+ id=flow_id,
+ name=outgoing_dict[flow_id][3],
+ process=outgoing_dict[flow_id][1],
+ )
+ else:
+ flow = BPMN.SequenceFlow(
+ outgoing_dict[flow_id][0],
+ incoming_dict[flow_id][0],
+ id=flow_id,
+ name=outgoing_dict[flow_id][3],
+ process=outgoing_dict[flow_id][1],
+ )
+
+ if flow is not None:
+ bpmn_graph.add_flow(flow)
+ layout.get(flow).del_waypoints()
+ for waypoint in flow_info[flow_id]:
+ layout.get(flow).add_waypoint(waypoint)
+
+ for node_id in nodes_bounds:
+ if node_id in nodes_dict:
+ bounds = nodes_bounds[node_id]
+ node = nodes_dict[node_id]
+ layout.get(node).set_x(bounds["x"])
+ layout.get(node).set_y(bounds["y"])
+ layout.get(node).set_width(bounds["width"])
+ layout.get(node).set_height(bounds["height"])
+ return bpmn_graph
+
+
+def import_xml_tree_from_root(root):
+ """
+ Imports a BPMN graph from (the root of) an XML tree
+
+ Parameters
+ -------------
+ root
+ Root of the tree
+
+ Returns
+ -------------
+ bpmn_graph
+ BPMN graph
+ """
+ bpmn_graph = BPMN()
+ counts = Counts()
+ incoming_dict = {}
+ outgoing_dict = {}
+ nodes_dict = {}
+ nodes_bounds = {}
+ flow_info = {}
+
+ return parse_element(
+ bpmn_graph,
+ counts,
+ root,
+ [],
+ incoming_dict,
+ outgoing_dict,
+ nodes_dict,
+ nodes_bounds,
+ flow_info,
+ )
+
+
+def apply(path, parameters=None):
+ """
+ Imports a BPMN diagram from a file
+
+ Parameters
+ -------------
+ path
+ Path to the file
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ bpmn_graph
+ BPMN graph
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, None
+ )
+
+ from lxml import etree, objectify
+
+ parser = etree.XMLParser(remove_comments=True, encoding=encoding)
+
+ F = open(path, "rb")
+ xml_tree = objectify.parse(F, parser=parser)
+ F.close()
+
+ return import_xml_tree_from_root(xml_tree.getroot())
+
+
+def import_from_string(bpmn_string, parameters=None):
+ """
+ Imports a BPMN diagram from a string
+
+ Parameters
+ -------------
+ path
+ Path to the file
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ bpmn_graph
+ BPMN graph
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ if type(bpmn_string) is str:
+ bpmn_string = bpmn_string.encode(encoding)
+
+ from lxml import etree, objectify
+
+ parser = etree.XMLParser(remove_comments=True)
+ root = objectify.fromstring(bpmn_string, parser=parser)
+
+ return import_xml_tree_from_root(root)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae789b2def377c20e20d99dacb72345e47fe645c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.layout import variants, layouter
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/layouter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/layouter.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb5605f90f1882b6afb99b3a3ba04c7d23b9300a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/layouter.py
@@ -0,0 +1,57 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.bpmn.layout.variants import graphviz, graphviz_new
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ GRAPHVIZ = graphviz
+ GRAPHVIZ_NEW = graphviz_new
+
+
+DEFAULT_VARIANT = Variants.GRAPHVIZ_NEW
+
+
+def apply(bpmn_graph, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Layouts a BPMN graph (inserting the positions of the nodes and the layouting of the edges)
+
+ Parameters
+ -------------
+ bpmn_graph
+ BPMN graph
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.GRAPHVIZ
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ bpmn_graph
+ BPMN graph with layout information
+ """
+ return exec_utils.get_variant(variant).apply(
+ bpmn_graph, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c1d102a7734a9cb3a8e0f8c1b3435b0e12c02c8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.layout.variants import graphviz, graphviz_new
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/graphviz.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/graphviz.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d64743126d3ca976bdaeb8e3060d6a46a28b51f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/graphviz.py
@@ -0,0 +1,499 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import uuid
+from collections import Counter
+from copy import deepcopy
+from enum import Enum
+
+from pm4py.objects.bpmn.obj import BPMN
+from pm4py.objects.bpmn.util.sorting import get_sorted_nodes_edges
+from pm4py.util import exec_utils
+import tempfile
+
+
+class EndpointDirection(Enum):
+ RIGHT = "right"
+ LEFT = "left"
+ TOP = "top"
+ BOTTOM = "bottom"
+
+
+class Parameters(Enum):
+ TASK_WH = "task_wh"
+ SCREEN_SIZE_X = "screen_size_x"
+ SCREEN_SIZE_Y = "screen_size_y"
+ SCALING_FACTOR = "scaling_factor"
+
+
+def get_right_edge_coord(layout, node, p, partial_counter, total_counter):
+ y_factor = partial_counter[EndpointDirection.RIGHT] / (
+ total_counter[EndpointDirection.RIGHT] + 1.0
+ )
+ new_x = p[0] + layout.get(node).get_width()
+ new_y = p[1] + round(layout.get(node).get_height() * y_factor)
+ return (new_x, new_y)
+
+
+def get_left_edge_coord(layout, node, p, partial_counter, total_counter):
+ y_factor = partial_counter[EndpointDirection.LEFT] / (
+ total_counter[EndpointDirection.LEFT] + 1.0
+ )
+ new_x = p[0]
+ new_y = p[1] + round(layout.get(node).get_height() * y_factor)
+ return (new_x, new_y)
+
+
+def get_top_edge_coord(layout, node, p, partial_counter, total_counter):
+ x_factor = partial_counter[EndpointDirection.TOP] / (
+ total_counter[EndpointDirection.TOP] + 1.0
+ )
+ new_x = p[0] + round(layout.get(node).get_width() * x_factor)
+ new_y = p[1]
+ return (new_x, new_y)
+
+
+def get_bottom_edge_coord(layout, node, p, partial_counter, total_counter):
+ x_factor = partial_counter[EndpointDirection.BOTTOM] / (
+ total_counter[EndpointDirection.BOTTOM] + 1.0
+ )
+ new_x = p[0] + round(layout.get(node).get_width() * x_factor)
+ new_y = p[1] + layout.get(node).get_height()
+ return (new_x, new_y)
+
+
+def apply(bpmn_graph, parameters=None):
+ """
+ Layouts a BPMN graph (inserting the positions of the nodes and the layouting of the edges)
+
+ Parameters
+ -------------
+ bpmn_graph
+ BPMN graph
+ parameters
+ Parameters of the algorithm:
+ - Parameters.SCREEN_SIZE_X => target size of the screen in pixels (default 1920.0)
+ - Parameters.SCREEN_SIZE_Y => target size of the screen in pixels (default 1080.0)
+ - Parameters.SCALING_FACTOR => scaling factor of the layouting (defualt 2.5)
+
+ Returns
+ -------------
+ bpmn_graph
+ BPMN graph with layout information
+ """
+ from graphviz import Digraph
+ from pm4py.visualization.common import save as gsave
+ from pm4py.visualization.common import svg_pos_parser
+
+ if parameters is None:
+ parameters = {}
+
+ screen_size_x = exec_utils.get_param_value(
+ Parameters.SCREEN_SIZE_X, parameters, 1920.0
+ )
+ screen_size_y = exec_utils.get_param_value(
+ Parameters.SCREEN_SIZE_Y, parameters, 1080.0
+ )
+ scaling_factor = exec_utils.get_param_value(
+ Parameters.SCALING_FACTOR, parameters, 2.5
+ )
+
+ nodes = bpmn_graph.get_nodes()
+ flows = bpmn_graph.get_flows()
+ layout = bpmn_graph.get_layout()
+
+ filename_gv = tempfile.NamedTemporaryFile(suffix=".gv")
+ filename_gv.close()
+ filename_svg = tempfile.NamedTemporaryFile(suffix=".svg")
+ filename_svg.close()
+ viz = Digraph(
+ bpmn_graph.get_name(), filename=filename_gv.name, engine="dot"
+ )
+ viz.format = "svg"
+ viz.graph_attr["rankdir"] = "LR"
+
+ graph_nodes, graph_edges = get_sorted_nodes_edges(bpmn_graph)
+
+ nodes_dict = {}
+ inv_nodes_dict = {}
+ for n in graph_nodes:
+ node_uuid = str(uuid.uuid4()).replace("-", "")
+ nodes_dict[n] = node_uuid
+ inv_nodes_dict[node_uuid] = n
+ viz.node(node_uuid, label=" ", shape="box")
+
+ for tup in graph_edges:
+ viz.edge(nodes_dict[tup[0]], nodes_dict[tup[1]])
+
+ gsave.save(viz, filename_svg.name)
+
+ nodes_p, edges_p = svg_pos_parser.apply(filename_svg.name)
+
+ nodes_pos = {}
+ for node in nodes_p:
+ nodes_pos[inv_nodes_dict[node]] = nodes_p[node]["polygon"]
+
+ endpoints_wh = exec_utils.get_param_value(
+ Parameters.TASK_WH, parameters, 30
+ )
+ task_wh = exec_utils.get_param_value(Parameters.TASK_WH, parameters, 60)
+
+ # add node positions to BPMN nodes
+ for n in graph_nodes:
+ node_pos = nodes_pos[n][0]
+
+ pos_x = float(node_pos[0])
+ pos_y = float(node_pos[1])
+ layout.get(n).set_x(pos_x)
+ layout.get(n).set_y(pos_y)
+ if isinstance(n, BPMN.Task):
+ this_width = min(
+ round(2 * task_wh),
+ round(2 * (len(n.get_name()) + 7) * task_wh / 22.0),
+ )
+ layout.get(n).set_width(this_width)
+ layout.get(n).set_height(task_wh)
+ elif isinstance(n, BPMN.StartEvent) or isinstance(n, BPMN.EndEvent):
+ layout.get(n).set_width(endpoints_wh)
+ layout.get(n).set_height(endpoints_wh)
+ else:
+ layout.get(n).set_width(task_wh)
+ layout.get(n).set_height(task_wh)
+
+ max_x = max(1, max(abs(layout.get(node).get_x()) for node in nodes))
+ max_y = max(1, max(abs(layout.get(node).get_y()) for node in nodes))
+ different_x = len(set(layout.get(node).get_x() for node in nodes))
+ different_y = len(set(layout.get(node).get_y() for node in nodes))
+
+ stretch_fact_x = scaling_factor * 1.25 * screen_size_x / max_x
+ stretch_fact_y = scaling_factor * screen_size_y / max_y
+
+ for node in nodes:
+ layout.get(node).set_x(
+ round(layout.get(node).get_x() * stretch_fact_x)
+ )
+ layout.get(node).set_y(
+ round(layout.get(node).get_y() * stretch_fact_y)
+ )
+
+ min_x = min(layout.get(node).get_x() for node in nodes)
+ min_y = min(layout.get(node).get_y() for node in nodes)
+
+ for node in nodes:
+ x_coord = layout.get(node).get_x() - min_x
+ y_coord = layout.get(node).get_y() - min_y
+ layout.get(node).set_x(x_coord)
+ layout.get(node).set_y(y_coord)
+
+ outgoing_edges = dict()
+ ingoing_edges = dict()
+ sources_dict = dict()
+ targets_dict = dict()
+
+ for flow in flows:
+ source = flow.get_source()
+ target = flow.get_target()
+
+ x_src = layout.get(source).get_x()
+ x_trg = layout.get(target).get_x()
+ y_src = layout.get(source).get_y()
+ y_trg = layout.get(target).get_y()
+
+ sources_dict[(x_src, y_src)] = source
+ targets_dict[(x_trg, y_trg)] = target
+
+ diff_x = abs(x_trg - x_src)
+ diff_y = abs(y_src - y_trg)
+
+ if (x_src, y_src) not in outgoing_edges:
+ outgoing_edges[(x_src, y_src)] = {}
+ outgoing_edges[(x_src, y_src)][(x_trg, y_trg)] = {
+ EndpointDirection.RIGHT: 0.0,
+ EndpointDirection.LEFT: 0.0,
+ EndpointDirection.TOP: 0.0,
+ EndpointDirection.BOTTOM: 0.0,
+ }
+ if (x_trg, y_trg) not in ingoing_edges:
+ ingoing_edges[(x_trg, y_trg)] = {}
+ ingoing_edges[(x_trg, y_trg)][(x_src, y_src)] = {
+ EndpointDirection.RIGHT: 0.0,
+ EndpointDirection.LEFT: 0.0,
+ EndpointDirection.TOP: 0.0,
+ EndpointDirection.BOTTOM: 0.0,
+ }
+
+ if x_trg > x_src:
+ outgoing_edges[(x_src, y_src)][(x_trg, y_trg)][
+ EndpointDirection.RIGHT
+ ] = diff_x / (diff_x + diff_y)
+ ingoing_edges[(x_trg, y_trg)][(x_src, y_src)][
+ EndpointDirection.LEFT
+ ] = diff_x / (diff_x + diff_y)
+ else:
+ outgoing_edges[(x_src, y_src)][(x_trg, y_trg)][
+ EndpointDirection.LEFT
+ ] = diff_x / (diff_x + diff_y)
+ ingoing_edges[(x_trg, y_trg)][(x_src, y_src)][
+ EndpointDirection.RIGHT
+ ] = diff_x / (diff_x + diff_y)
+
+ if y_src > y_trg:
+ outgoing_edges[(x_src, y_src)][(x_trg, y_trg)][
+ EndpointDirection.TOP
+ ] = diff_y / (diff_x + diff_y)
+ ingoing_edges[(x_trg, y_trg)][(x_src, y_src)][
+ EndpointDirection.BOTTOM
+ ] = diff_y / (diff_x + diff_y)
+ else:
+ outgoing_edges[(x_src, y_src)][(x_trg, y_trg)][
+ EndpointDirection.BOTTOM
+ ] = diff_y / (diff_x + diff_y)
+ ingoing_edges[(x_trg, y_trg)][(x_src, y_src)][
+ EndpointDirection.TOP
+ ] = diff_y / (diff_x + diff_y)
+
+ # normalization
+ outgoing_edges0 = deepcopy(outgoing_edges)
+ ingoing_edges0 = deepcopy(ingoing_edges)
+
+ for p1 in outgoing_edges:
+ sum_right = 0.0
+ sum_left = 0.0
+ sum_top = 0.0
+ sum_bottom = 0.0
+ for p2 in outgoing_edges[p1]:
+ sum_right += outgoing_edges0[p1][p2][EndpointDirection.RIGHT]
+ sum_left += outgoing_edges0[p1][p2][EndpointDirection.LEFT]
+ sum_top += outgoing_edges0[p1][p2][EndpointDirection.TOP]
+ sum_bottom += outgoing_edges0[p1][p2][EndpointDirection.BOTTOM]
+ if p1 in ingoing_edges:
+ for p2 in ingoing_edges[p1]:
+ sum_right += ingoing_edges0[p1][p2][EndpointDirection.RIGHT]
+ sum_left += ingoing_edges0[p1][p2][EndpointDirection.LEFT]
+ sum_top += ingoing_edges0[p1][p2][EndpointDirection.TOP]
+ sum_bottom += ingoing_edges0[p1][p2][EndpointDirection.BOTTOM]
+ for p2 in outgoing_edges[p1]:
+ if sum_right > 0:
+ outgoing_edges[p1][p2][EndpointDirection.RIGHT] = (
+ outgoing_edges[p1][p2][EndpointDirection.RIGHT] ** 2
+ / sum_right
+ )
+ if sum_left > 0:
+ outgoing_edges[p1][p2][EndpointDirection.LEFT] = (
+ outgoing_edges[p1][p2][EndpointDirection.LEFT] ** 2
+ / sum_left
+ )
+ if sum_top > 0:
+ outgoing_edges[p1][p2][EndpointDirection.TOP] = (
+ outgoing_edges[p1][p2][EndpointDirection.TOP] ** 2
+ / sum_top
+ )
+ if sum_bottom > 0:
+ outgoing_edges[p1][p2][EndpointDirection.BOTTOM] = (
+ outgoing_edges[p1][p2][EndpointDirection.BOTTOM] ** 2
+ / sum_bottom
+ )
+ for p1 in ingoing_edges:
+ sum_right = 0.0
+ sum_left = 0.0
+ sum_top = 0.0
+ sum_bottom = 0.0
+ for p2 in ingoing_edges[p1]:
+ sum_right += ingoing_edges0[p1][p2][EndpointDirection.RIGHT]
+ sum_left += ingoing_edges0[p1][p2][EndpointDirection.LEFT]
+ sum_top += ingoing_edges0[p1][p2][EndpointDirection.TOP]
+ sum_bottom += ingoing_edges0[p1][p2][EndpointDirection.BOTTOM]
+ if p1 in outgoing_edges:
+ for p2 in outgoing_edges[p1]:
+ sum_right += outgoing_edges0[p1][p2][EndpointDirection.RIGHT]
+ sum_left += outgoing_edges0[p1][p2][EndpointDirection.LEFT]
+ sum_top += outgoing_edges0[p1][p2][EndpointDirection.TOP]
+ sum_bottom += outgoing_edges0[p1][p2][EndpointDirection.BOTTOM]
+ for p2 in ingoing_edges[p1]:
+ if sum_right > 0:
+ ingoing_edges[p1][p2][EndpointDirection.RIGHT] = (
+ ingoing_edges[p1][p2][EndpointDirection.RIGHT] ** 2
+ / sum_right
+ )
+ if sum_left > 0:
+ ingoing_edges[p1][p2][EndpointDirection.LEFT] = (
+ ingoing_edges[p1][p2][EndpointDirection.LEFT] ** 2
+ / sum_left
+ )
+ if sum_top > 0:
+ ingoing_edges[p1][p2][EndpointDirection.TOP] = (
+ ingoing_edges[p1][p2][EndpointDirection.TOP] ** 2 / sum_top
+ )
+ if sum_bottom > 0:
+ ingoing_edges[p1][p2][EndpointDirection.BOTTOM] = (
+ ingoing_edges[p1][p2][EndpointDirection.BOTTOM] ** 2
+ / sum_bottom
+ )
+
+ # keep best direction
+ for p1 in outgoing_edges:
+ for p2 in outgoing_edges[p1]:
+ vals = sorted(
+ [(x, y) for x, y in outgoing_edges[p1][p2].items()],
+ key=lambda x: x[1],
+ reverse=True,
+ )
+ outgoing_edges[p1][p2] = vals[0][0]
+ for p1 in ingoing_edges:
+ for p2 in ingoing_edges[p1]:
+ vals = sorted(
+ [(x, y) for x, y in ingoing_edges[p1][p2].items()],
+ key=lambda x: x[1],
+ reverse=True,
+ )
+ ingoing_edges[p1][p2] = vals[0][0]
+
+ total_counter = dict()
+ partial_counter = dict()
+ for p1 in outgoing_edges:
+ if p1 not in total_counter:
+ total_counter[p1] = Counter()
+ for p2 in outgoing_edges[p1]:
+ dir = outgoing_edges[p1][p2]
+ total_counter[p1][dir] += 1
+ for p1 in ingoing_edges:
+ if p1 not in total_counter:
+ total_counter[p1] = Counter()
+ for p2 in ingoing_edges[p1]:
+ dir = ingoing_edges[p1][p2]
+ total_counter[p1][dir] += 1
+
+ outgoing_edges_dirs = deepcopy(outgoing_edges)
+ ingoing_edges_dirs = deepcopy(ingoing_edges)
+
+ # decide exiting/entering point for edges
+ for p1 in outgoing_edges:
+ node = sources_dict[p1]
+ if p1 not in partial_counter:
+ partial_counter[p1] = Counter()
+ sorted_outgoing_edges = sorted(
+ outgoing_edges[p1], key=lambda x: x, reverse=False
+ )
+ for p2 in sorted_outgoing_edges:
+ dir = outgoing_edges[p1][p2]
+ partial_counter[p1][dir] += 1
+ if dir == EndpointDirection.RIGHT:
+ outgoing_edges[p1][p2] = get_right_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+ elif dir == EndpointDirection.LEFT:
+ outgoing_edges[p1][p2] = get_left_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+ elif dir == EndpointDirection.TOP:
+ outgoing_edges[p1][p2] = get_top_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+ elif dir == EndpointDirection.BOTTOM:
+ outgoing_edges[p1][p2] = get_bottom_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+ for p1 in ingoing_edges:
+ node = targets_dict[p1]
+ if p1 not in partial_counter:
+ partial_counter[p1] = Counter()
+ sorted_ingoing_edges = sorted(
+ ingoing_edges[p1], key=lambda x: x, reverse=False
+ )
+ for p2 in sorted_ingoing_edges:
+ dir = ingoing_edges[p1][p2]
+ partial_counter[p1][dir] += 1
+ if dir == EndpointDirection.RIGHT:
+ ingoing_edges[p1][p2] = get_right_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+ elif dir == EndpointDirection.LEFT:
+ ingoing_edges[p1][p2] = get_left_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+ elif dir == EndpointDirection.TOP:
+ ingoing_edges[p1][p2] = get_top_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+ elif dir == EndpointDirection.BOTTOM:
+ ingoing_edges[p1][p2] = get_bottom_edge_coord(
+ layout, node, p1, partial_counter[p1], total_counter[p1]
+ )
+
+ # order the left-entering ingoing edges better
+ for p1 in ingoing_edges:
+ vals = [(x, y) for x, y in ingoing_edges[p1].items() if y[0] == p1[0]]
+ if len(vals) > 1:
+ vals_x = [x[0] for x in vals]
+ vals_y = [x[1] for x in vals]
+ vals_x = sorted(vals_x)
+ vals_y = sorted(vals_y)
+ for i in range(len(vals_x)):
+ ingoing_edges[p1][vals_x[i]] = vals_y[i]
+
+ # set waypoints for edges
+ for flow in flows:
+ source = flow.get_source()
+ target = flow.get_target()
+
+ flow.del_waypoints()
+
+ x_src = layout.get(source).get_x()
+ x_trg = layout.get(target).get_x()
+ y_src = layout.get(source).get_y()
+ y_trg = layout.get(target).get_y()
+ p1 = (x_src, y_src)
+ p2 = (x_trg, y_trg)
+
+ source_x = outgoing_edges[p1][p2][0]
+ source_y = outgoing_edges[p1][p2][1]
+ target_x = ingoing_edges[p2][p1][0]
+ target_y = ingoing_edges[p2][p1][1]
+ dir_source = outgoing_edges_dirs[p1][p2]
+ dir_target = ingoing_edges_dirs[p2][p1]
+
+ middle_x = (source_x + target_x) / 2.0
+ middle_y = (source_y + target_y) / 2.0
+
+ flow.add_waypoint((source_x, source_y))
+ if dir_source in [EndpointDirection.LEFT, EndpointDirection.RIGHT]:
+ if dir_target in [EndpointDirection.LEFT, EndpointDirection.RIGHT]:
+ flow.add_waypoint((middle_x, source_y))
+ flow.add_waypoint((middle_x, target_y))
+ elif dir_target in [
+ EndpointDirection.TOP,
+ EndpointDirection.BOTTOM,
+ ]:
+ flow.add_waypoint((target_x, source_y))
+ elif dir_source in [EndpointDirection.TOP, EndpointDirection.BOTTOM]:
+ if dir_target in [EndpointDirection.TOP, EndpointDirection.BOTTOM]:
+ flow.add_waypoint((source_x, middle_y))
+ flow.add_waypoint((target_x, middle_y))
+ elif dir_target in [
+ EndpointDirection.LEFT,
+ EndpointDirection.RIGHT,
+ ]:
+ flow.add_waypoint((source_x, target_y))
+
+ flow.add_waypoint((target_x, target_y))
+
+ return bpmn_graph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/graphviz_new.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/graphviz_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9bf46a80d3c06453a990be79e98e7bfa8a1130e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/variants/graphviz_new.py
@@ -0,0 +1,137 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.obj import BPMN
+from typing import Optional, Dict, Any, Tuple, List
+from copy import copy
+import tempfile
+
+
+def _get_node_center(layout, node) -> Tuple[float, float]:
+ """Get the center point of a node."""
+ node_layout = layout.get(node)
+ x = node_layout.get_x() + node_layout.get_width() / 2
+ y = node_layout.get_y() + node_layout.get_height() / 2
+ return (x, y)
+
+
+def _get_node_boundary_point(layout, node, target_point: Tuple[float, float]) -> Tuple[float, float]:
+ """
+ Calculate the intersection point on the node boundary
+ towards a target point.
+ """
+ node_layout = layout.get(node)
+ x = node_layout.get_x()
+ y = node_layout.get_y()
+ w = node_layout.get_width()
+ h = node_layout.get_height()
+
+ cx, cy = x + w / 2, y + h / 2
+ tx, ty = target_point
+
+ dx = tx - cx
+ dy = ty - cy
+
+ if dx == 0 and dy == 0:
+ return (cx, y) # Default to top edge
+
+ # Calculate intersection with rectangle boundary
+ if dx == 0:
+ return (cx, y if dy < 0 else y + h)
+ if dy == 0:
+ return (x if dx < 0 else x + w, cy)
+
+ # Check intersection with each edge
+ scale_x = (w / 2) / abs(dx)
+ scale_y = (h / 2) / abs(dy)
+ scale = min(scale_x, scale_y)
+
+ return (cx + dx * scale, cy + dy * scale)
+
+
+def apply(
+ bpmn_graph: BPMN, parameters: Optional[Dict[Any, Any]] = None
+) -> BPMN:
+ """
+ Layouts the BPMN graph using node positioning and edge waypoints from Graphviz SVG.
+ Ensures edges connect properly to node boundaries.
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.visualization.bpmn.variants import classic as bpmn_visualizer
+ from pm4py.visualization.common import svg_pos_parser
+
+ layout = bpmn_graph.get_layout()
+
+ filename_svg = tempfile.NamedTemporaryFile(suffix=".svg", delete=False)
+ filename_svg.close()
+
+ vis_parameters = copy(parameters)
+ vis_parameters["format"] = "svg"
+ vis_parameters["include_name_in_events"] = False
+ vis_parameters["endpoints_shape"] = "box"
+
+ gviz = bpmn_visualizer.apply(bpmn_graph, parameters=vis_parameters)
+ bpmn_visualizer.save(gviz, filename_svg.name)
+
+ nodes_p, edges_p = svg_pos_parser.apply(filename_svg.name)
+
+ # First pass: layout all nodes
+ for node in list(bpmn_graph.get_nodes()):
+ node_id = str(id(node))
+ if node_id in nodes_p:
+ node_info = nodes_p[node_id]
+ if node_info["polygon"] is not None:
+ min_x = min(p[0] for p in node_info["polygon"])
+ max_x = max(p[0] for p in node_info["polygon"])
+ min_y = min(p[1] for p in node_info["polygon"])
+ max_y = max(p[1] for p in node_info["polygon"])
+
+ layout.get(node).set_width(max_x - min_x)
+ layout.get(node).set_height(max_y - min_y)
+ layout.get(node).set_x(min_x)
+ layout.get(node).set_y(min_y)
+
+ # Second pass: layout edges with proper connection points
+ for flow in list(bpmn_graph.get_flows()):
+ flow_id = (str(id(flow.source)), str(id(flow.target)))
+ if flow_id in edges_p:
+ flow_info = edges_p[flow_id]
+ if flow_info["waypoints"] is not None and len(flow_info["waypoints"]) >= 2:
+ flow.del_waypoints()
+
+ waypoints = list(flow_info["waypoints"])
+
+ # Adjust start point to source node boundary
+ if len(waypoints) > 1:
+ start_boundary = _get_node_boundary_point(layout, flow.source, waypoints[1])
+ waypoints[0] = start_boundary
+
+ # Adjust end point to target node boundary
+ if len(waypoints) > 1:
+ end_boundary = _get_node_boundary_point(layout, flow.target, waypoints[-2])
+ waypoints[-1] = end_boundary
+
+ for wayp in waypoints:
+ flow.add_waypoint(wayp)
+
+ return bpmn_graph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca5a4fff0a98b3107617e3158c140e268f761cce
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/obj.py
@@ -0,0 +1,894 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import uuid
+from enum import Enum
+from collections import Counter
+from pm4py.util import nx_utils
+
+
+DEFAULT_PROCESS = str(uuid.uuid4())
+
+
+class Marking(Counter):
+ pass
+
+ # required = Counter()
+
+ def __hash__(self):
+ r = 0
+ for p in self.items():
+ r += 31 * hash(p[0]) * p[1]
+ return r
+
+ def __eq__(self, other):
+ if not self.keys() == other.keys():
+ return False
+ for p in self.keys():
+ if other.get(p) != self.get(p):
+ return False
+ return True
+
+ def __le__(self, other):
+ if not self.keys() <= other.keys():
+ return False
+ for p in self.keys():
+ if sum(other.get(p)) < sum(self.get(p)):
+ return False
+ return True
+
+ def __add__(self, other):
+ m = Marking()
+ for p in self.items():
+ m[p[0]] = p[1]
+ for p in other.items():
+ m[p[0]] += p[1]
+ return m
+
+ def __sub__(self, other):
+ m = Marking()
+ for p in self.items():
+ m[p[0]] = p[1]
+ for p in other.items():
+ m[p[0]] -= p[1]
+ if m[p[0]] == 0:
+ del m[p[0]]
+ return m
+
+ def __repr__(self):
+ # return str([str(p.name) + ":" + str(self.get(p)) for p in self.keys()])
+ # The previous representation had a bug, it took into account the order
+ # of the places with tokens
+ return str(
+ [
+ str(p.id) + ":" + str(self.get(p))
+ for p in sorted(list(self.keys()), key=lambda x: x.id)
+ ]
+ )
+
+ def __deepcopy__(self, memodict={}):
+ marking = Marking()
+ memodict[id(self)] = marking
+ for node in self:
+ node_occ = self[node]
+ new_node = (
+ memodict[id(node)]
+ if id(node) in memodict
+ else BPMN.BPMNNode(node.id, node.name)
+ )
+ marking[new_node] = node_occ
+ return marking
+
+
+class BPMNNodeLayout(object):
+ def __init__(self):
+ self.__x = 0
+ self.__y = 0
+ self.__width = 100
+ self.__height = 100
+
+ def set_x(self, x):
+ self.__x = x
+
+ def set_y(self, y):
+ self.__y = y
+
+ def get_x(self):
+ return self.__x
+
+ def get_y(self):
+ return self.__y
+
+ def get_width(self):
+ return self.__width
+
+ def set_width(self, width):
+ self.__width = width
+
+ def get_height(self):
+ return self.__height
+
+ def set_height(self, height):
+ self.__height = height
+
+
+class BPMNEdgeLayout(object):
+ def __init__(self):
+ self.__waypoints = [(0, 0), (0, 0)]
+
+ def add_waypoint(self, waypoint):
+ self.__waypoints.append(waypoint)
+
+ def del_waypoints(self):
+ self.__waypoints = list()
+
+ def get_waypoints(self):
+ return self.__waypoints
+
+
+class BPMNLayout(object):
+ def __init__(self):
+ self.layout_dict = {}
+
+ def get(self, n):
+ if n not in self.layout_dict:
+ if isinstance(n, BPMN.BPMNNode):
+ self.layout_dict[n] = BPMNNodeLayout()
+ elif isinstance(n, BPMN.Flow):
+ self.layout_dict[n] = BPMNEdgeLayout()
+ return self.layout_dict[n]
+
+
+class BPMN(object):
+ class BPMNNode(object):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ self.__id = ("id" + str(uuid.uuid4())) if id == "" else id
+ self.__name = name
+ self.__in_arcs = list() if in_arcs is None else in_arcs
+ self.__out_arcs = list() if out_arcs is None else out_arcs
+ self.__process = DEFAULT_PROCESS if process is None else process
+ self.__layout = BPMNLayout()
+
+ def get_id(self):
+ return self.__id
+
+ def get_name(self):
+ return self.__name
+
+ def set_name(self, name):
+ self.__name = name
+
+ def get_in_arcs(self):
+ return self.__in_arcs
+
+ def get_out_arcs(self):
+ return self.__out_arcs
+
+ def add_in_arc(self, in_arc):
+ if in_arc not in self.__in_arcs:
+ self.__in_arcs.append(in_arc)
+
+ def add_out_arc(self, out_arc):
+ if out_arc not in self.__out_arcs:
+ self.__out_arcs.append(out_arc)
+
+ def remove_in_arc(self, in_arc):
+ self.__in_arcs.remove(in_arc)
+
+ def remove_out_arc(self, out_arc):
+ self.__out_arcs.remove(out_arc)
+
+ def get_process(self):
+ return self.__process
+
+ def set_process(self, process):
+ self.__process = process
+
+ def set_x(self, x):
+ return self.__layout.get(self).set_x(x)
+
+ def set_y(self, y):
+ return self.__layout.get(self).set_y(y)
+
+ def get_x(self):
+ return self.__layout.get(self).get_x()
+
+ def get_y(self):
+ return self.__layout.get(self).get_y()
+
+ def get_width(self):
+ return self.__layout.get(self).get_width()
+
+ def set_width(self, width):
+ return self.__layout.get(self).set_width(width)
+
+ def get_height(self):
+ return self.__layout.get(self).get_height()
+
+ def set_height(self, height):
+ return self.__layout.get(self).set_height(height)
+
+ def get_layout(self):
+ return self.__layout
+
+ def set_layout(self, layout):
+ self.__layout = layout
+
+ def __hash__(self):
+ return hash(self.id)
+
+ def __eq__(self, other):
+ # keep the ID for now in places
+ return hash(self) == hash(other)
+
+ def __repr__(self):
+ return str(self.__id + "@" + self.__name)
+
+ def __str__(self):
+ return self.__repr__()
+
+ name = property(get_name)
+ id = property(get_id)
+ in_arcs = property(get_in_arcs)
+ out_arcs = property(get_out_arcs)
+ process = property(get_process, set_process)
+
+ class Collaboration(BPMNNode):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.BPMNNode.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class Participant(BPMNNode):
+ def __init__(
+ self,
+ id="",
+ name="",
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ process_ref=None,
+ ):
+ self.process_ref = process_ref
+ BPMN.BPMNNode.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class TextAnnotation(BPMNNode):
+ def __init__(
+ self,
+ id="",
+ name="",
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ text=None,
+ ):
+ self.text = text
+ BPMN.BPMNNode.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class Event(BPMNNode):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.BPMNNode.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class StartEvent(Event):
+ def __init__(
+ self,
+ id="",
+ isInterrupting=False,
+ name="",
+ parallelMultiple=False,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ BPMN.Event.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+ self.__isInterrupting = isInterrupting
+ self.__parallelMultiple = parallelMultiple
+
+ def get_isInterrupting(self):
+ return self.__isInterrupting
+
+ def get_parallelMultiple(self):
+ return self.__parallelMultiple
+
+ class NormalStartEvent(StartEvent):
+ def __init__(
+ self,
+ id="",
+ isInterrupting=False,
+ name="",
+ parallelMultiple=False,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ BPMN.StartEvent.__init__(
+ self,
+ id,
+ isInterrupting,
+ name,
+ parallelMultiple,
+ in_arcs,
+ out_arcs,
+ process=process,
+ )
+
+ class MessageStartEvent(StartEvent):
+ def __init__(
+ self,
+ id="",
+ isInterrupting=False,
+ name="",
+ parallelMultiple=False,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ BPMN.StartEvent.__init__(
+ self,
+ id,
+ isInterrupting,
+ name,
+ parallelMultiple,
+ in_arcs,
+ out_arcs,
+ process=process,
+ )
+
+ class IntermediateCatchEvent(Event):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.Event.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class MessageIntermediateCatchEvent(IntermediateCatchEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.IntermediateCatchEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class ErrorIntermediateCatchEvent(IntermediateCatchEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.IntermediateCatchEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class CancelIntermediateCatchEvent(IntermediateCatchEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.IntermediateCatchEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class BoundaryEvent(Event):
+ def __init__(
+ self,
+ id="",
+ name="",
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ activity=None,
+ ):
+ self.__activity = activity
+ BPMN.Event.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ def get_activity(self):
+ return self.__activity
+
+ class MessageBoundaryEvent(BoundaryEvent):
+ def __init__(
+ self,
+ id="",
+ name="",
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ activity=None,
+ ):
+ BPMN.BoundaryEvent.__init__(
+ self,
+ id,
+ name,
+ in_arcs,
+ out_arcs,
+ process=process,
+ activity=activity,
+ )
+
+ class ErrorBoundaryEvent(BoundaryEvent):
+ def __init__(
+ self,
+ id="",
+ name="",
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ activity=None,
+ ):
+ BPMN.BoundaryEvent.__init__(
+ self,
+ id,
+ name,
+ in_arcs,
+ out_arcs,
+ process=process,
+ activity=activity,
+ )
+
+ class CancelBoundaryEvent(BoundaryEvent):
+ def __init__(
+ self,
+ id="",
+ name="",
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ activity=None,
+ ):
+ BPMN.BoundaryEvent.__init__(
+ self,
+ id,
+ name,
+ in_arcs,
+ out_arcs,
+ process=process,
+ activity=activity,
+ )
+
+ class IntermediateThrowEvent(Event):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.Event.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class MessageIntermediateThrowEvent(IntermediateThrowEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.IntermediateThrowEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class NormalIntermediateThrowEvent(IntermediateThrowEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.IntermediateThrowEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class EndEvent(Event):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.Event.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class NormalEndEvent(EndEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.EndEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class MessageEndEvent(EndEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.EndEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class TerminateEndEvent(EndEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.EndEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class ErrorEndEvent(EndEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.EndEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class CancelEndEvent(EndEvent):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.EndEvent.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class Activity(BPMNNode):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.BPMNNode.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class Task(Activity):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.Activity.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class UserTask(Task):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.Task.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class SendTask(Task):
+ def __init__(
+ self, id="", name="", in_arcs=None, out_arcs=None, process=None
+ ):
+ BPMN.Task.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ class SubProcess(Activity):
+ def __init__(
+ self,
+ id="",
+ name="",
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ depth=None,
+ ):
+ self.__depth = depth
+ BPMN.Activity.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+
+ def get_depth(self):
+ return self.__depth
+
+ class Gateway(BPMNNode):
+ class Direction(Enum):
+ UNSPECIFIED = "Unspecified"
+ DIVERGING = "Diverging"
+ CONVERGING = "Converging"
+
+ def __init__(
+ self,
+ id="",
+ name="",
+ gateway_direction=Direction.UNSPECIFIED,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ BPMN.BPMNNode.__init__(
+ self, id, name, in_arcs, out_arcs, process=process
+ )
+ self.__gateway_direction = gateway_direction
+
+ def get_gateway_direction(self):
+ return self.__gateway_direction
+
+ def set_gateway_direction(self, direction):
+ self.__gateway_direction = direction
+
+ class ParallelGateway(Gateway):
+ def __init__(
+ self,
+ id="",
+ name="",
+ gateway_direction=None,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ gateway_direction = (
+ gateway_direction
+ if gateway_direction is not None
+ else BPMN.Gateway.Direction.UNSPECIFIED
+ )
+ BPMN.Gateway.__init__(
+ self,
+ id,
+ name,
+ gateway_direction,
+ in_arcs,
+ out_arcs,
+ process=process,
+ )
+
+ class ExclusiveGateway(Gateway):
+ def __init__(
+ self,
+ id="",
+ name="",
+ gateway_direction=None,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ gateway_direction = (
+ gateway_direction
+ if gateway_direction is not None
+ else BPMN.Gateway.Direction.UNSPECIFIED
+ )
+ BPMN.Gateway.__init__(
+ self,
+ id,
+ name,
+ gateway_direction,
+ in_arcs,
+ out_arcs,
+ process=process,
+ )
+
+ class InclusiveGateway(Gateway):
+ def __init__(
+ self,
+ id="",
+ name="",
+ gateway_direction=None,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ gateway_direction = (
+ gateway_direction
+ if gateway_direction is not None
+ else BPMN.Gateway.Direction.UNSPECIFIED
+ )
+ BPMN.Gateway.__init__(
+ self,
+ id,
+ name,
+ gateway_direction,
+ in_arcs,
+ out_arcs,
+ process=process,
+ )
+
+ class EventBasedGateway(Gateway):
+ def __init__(
+ self,
+ id="",
+ name="",
+ gateway_direction=None,
+ in_arcs=None,
+ out_arcs=None,
+ process=None,
+ ):
+ gateway_direction = (
+ gateway_direction
+ if gateway_direction is not None
+ else BPMN.Gateway.Direction.UNSPECIFIED
+ )
+ BPMN.Gateway.__init__(
+ self,
+ id,
+ name,
+ gateway_direction,
+ in_arcs,
+ out_arcs,
+ process=process,
+ )
+
+ class Flow(object):
+ def __init__(self, source, target, id="", name="", process=None):
+ self.__id = uuid.uuid4() if id == "" else id
+ self.__name = name
+ self.__source = source
+ source.add_out_arc(self)
+ self.__target = target
+ target.add_in_arc(self)
+ self.__process = DEFAULT_PROCESS if process is None else process
+ self.__layout = BPMNLayout()
+
+ def get_id(self):
+ return self.__id
+
+ def get_name(self):
+ return self.__name
+
+ def get_source(self):
+ return self.__source
+
+ def get_target(self):
+ return self.__target
+
+ def get_process(self):
+ return self.__process
+
+ def set_process(self, process):
+ self.__process = process
+
+ def add_waypoint(self, waypoint):
+ return self.__layout.get(self).add_waypoint(waypoint)
+
+ def del_waypoints(self):
+ return self.__layout.get(self).del_waypoints()
+
+ def get_waypoints(self):
+ return self.__layout.get(self).get_waypoints()
+
+ def get_layout(self):
+ return self.__layout
+
+ def set_layout(self, layout):
+ self.__layout = layout
+
+ def __repr__(self):
+ u_id = (
+ str(self.__source.get_id())
+ + "@"
+ + str(self.__source.get_name())
+ )
+ v_id = (
+ str(self.__target.get_id())
+ + "@"
+ + str(self.__target.get_name())
+ )
+ return u_id + " -> " + v_id
+
+ def __str__(self):
+ return self.__repr__()
+
+ source = property(get_source)
+ target = property(get_target)
+
+ class SequenceFlow(Flow):
+ def __init__(self, source, target, id="", name="", process=None):
+ BPMN.Flow.__init__(
+ self, source, target, id=id, name=name, process=process
+ )
+
+ class MessageFlow(Flow):
+ def __init__(self, source, target, id="", name="", process=None):
+ BPMN.Flow.__init__(
+ self, source, target, id=id, name=name, process=process
+ )
+
+ class Association(Flow):
+ def __init__(self, source, target, id="", name="", process=None):
+ BPMN.Flow.__init__(
+ self, source, target, id=id, name=name, process=process
+ )
+
+ def __init__(self, process_id=None, name="", nodes=None, flows=None):
+ self.__process_id = (
+ str(uuid.uuid4()) if process_id is None else process_id
+ )
+
+ self.__name = name
+ self.__graph = nx_utils.MultiDiGraph()
+ self.__nodes = set() if nodes is None else nodes
+ self.__flows = set() if flows is None else flows
+ self.__layout = BPMNLayout()
+
+ if nodes is not None:
+ for node in nodes:
+ node.set_layout(self.get_layout())
+ self.__graph.add_node(node)
+ if flows is not None:
+ for flow in flows:
+ flow.set_layout(self.get_layout())
+ self.__graph.add_edge(flow.get_source(), flow.get_target())
+
+ def get_process_id(self):
+ return self.__process_id
+
+ def set_process_id(self, process_id):
+ self.__process_id = process_id
+
+ def get_nodes(self):
+ return self.__nodes
+
+ def get_flows(self):
+ return self.__flows
+
+ def get_graph(self):
+ return self.__graph
+
+ def get_name(self):
+ return self.__name
+
+ def set_name(self, name: str):
+ self.__name = name
+
+ def add_node(self, node):
+ node.set_layout(self.get_layout())
+ self.__nodes.add(node)
+ self.__graph.add_node(node)
+
+ def remove_node(self, node):
+ if node in self.__nodes:
+ self.__nodes.remove(node)
+ self.__graph.remove_node(node)
+
+ def remove_flow(self, flow):
+ source = flow.get_source()
+ target = flow.get_target()
+ if source in self.__nodes:
+ source.remove_out_arc(flow)
+ if target in self.__nodes:
+ target.remove_in_arc(flow)
+ self.__flows.remove(flow)
+ self.__graph.remove_edge(source, target)
+
+ def add_flow(self, flow):
+ if not isinstance(flow, BPMN.Flow):
+ raise Exception()
+ flow.set_layout(self.get_layout())
+ source = flow.get_source()
+ target = flow.get_target()
+ if source not in self.__nodes:
+ self.add_node(source)
+ if target not in self.__nodes:
+ self.add_node(target)
+ self.__flows.add(flow)
+ self.__graph.add_edge(
+ source, target, id=flow.get_id(), name=flow.get_name()
+ )
+ source.add_out_arc(flow)
+ target.add_in_arc(flow)
+
+ def get_layout(self):
+ return self.__layout
+
+ def set_layout(self, layout):
+ self.__layout = layout
+ for n in self.__nodes:
+ n.set_layout(layout)
+ for e in self.__flows:
+ e.set_layout(layout)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..717dc8cd885d31dd0839a3350aecf0880c7523d9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/semantics.py
@@ -0,0 +1,265 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+from pm4py.objects.bpmn.util.bpmn_utils import *
+from pm4py.objects.bpmn.obj import BPMN
+from itertools import combinations, chain
+import operator
+
+
+def is_enabled(node, bpmn, m):
+ if node not in bpmn.get_nodes():
+ return False
+ elif (
+ isinstance(node, (BPMN.ParallelGateway, BPMN.InclusiveGateway))
+ and node.get_gateway_direction() == BPMN.Gateway.Direction.CONVERGING
+ ):
+ if m[node] < len(node.get_in_arcs()):
+ return False
+ else:
+ if m[node] < 1:
+ return False
+ return True
+
+
+def execute(node, bpmn, m):
+ if not is_enabled(node, bpmn, m):
+ return None
+
+ return weak_execute(node, m)
+
+
+def try_to_execute(node, bpmn, m):
+ if not is_enabled(node, bpmn, m):
+ return None
+ else:
+ return execute(node, bpmn, m)
+
+
+def add_vector(a, b):
+ return list(map(operator.add, a, b))
+
+
+def sub_vector(a, b):
+ return list(map(operator.sub, a, b))
+
+
+def power_set(iterable, min=1):
+ s = list(iterable)
+ return chain.from_iterable(
+ combinations(s, r) for r in range(min, len(s) + 1)
+ )
+
+
+def weak_execute(node, m, bpmn_graph):
+ """
+ Execute a transition even if it is not fully enabled
+ Returns multiple possible markings if the node is a gate
+ """
+
+ # this first if is a workaround. env events inside subprocesses will be handled explicitly
+ # tokens flow out to the first element outside the subprocess. the
+ # activated boundary events become deactivated
+ if (
+ isinstance(node, (BPMN.NormalEndEvent, BPMN.TerminateEndEvent))
+ and node.get_process() != bpmn_graph.get_process_id()
+ ):
+ m_out = copy.copy(m)
+ # reset marking at current node
+ del m_out[node]
+
+ sub_process_node = get_node_by_id(node.get_process(), bpmn_graph)
+
+ # delete markings inside subprocess and from other enabled message
+ # transitions
+ for key in get_all_nodes_inside_process(
+ node.get_process(), bpmn_graph
+ ):
+ if key in m_out:
+ del m_out[key]
+ for key in get_boundary_events_of_activity(
+ node.get_process(), bpmn_graph
+ ):
+ if key in m_out and key != node:
+ del m_out[key]
+
+ # add marking at outgoing flow
+ if len(sub_process_node.get_out_arcs()) > 0:
+ target_node = sub_process_node.get_out_arcs()[0].target
+ execute_token_flow(target_node, m_out, bpmn_graph)
+
+ return [m_out]
+
+ elif isinstance(node, (BPMN.Event, BPMN.Activity)) or (
+ isinstance(node, BPMN.Gateway)
+ and node.get_gateway_direction() == BPMN.Gateway.Direction.CONVERGING
+ ):
+ m_out = copy.copy(m)
+ # reset marking at current node
+ del m_out[node]
+
+ # add marking at outgoing flow
+ if len(node.get_out_arcs()) > 0:
+ target_node = node.get_out_arcs()[0].target
+ execute_token_flow(target_node, m_out, bpmn_graph)
+
+ # external subprocess cancellation
+ if isinstance(node, BPMN.MessageBoundaryEvent):
+ # delete markings inside subprocess and from other enabled message
+ # transitions
+ for key in get_all_nodes_inside_process(
+ node.get_activity(), bpmn_graph
+ ):
+ if key in m_out:
+ del m_out[key]
+ for key in get_boundary_events_of_activity(
+ node.get_activity(), bpmn_graph
+ ):
+ if key in m_out and key != node:
+ del m_out[key]
+
+ return [m_out]
+
+ elif isinstance(node, BPMN.Gateway):
+ m_outs = []
+ if node.get_gateway_direction() == BPMN.Gateway.Direction.DIVERGING:
+ if isinstance(node, BPMN.ParallelGateway):
+ m_out = copy.copy(m)
+ del m_out[node]
+ for out_flow in node.get_out_arcs():
+ execute_token_flow(out_flow.target, m_out, bpmn_graph)
+ m_outs.append(m_out)
+ elif isinstance(node, BPMN.ExclusiveGateway):
+ for out_flow in node.get_out_arcs():
+ m_out = copy.copy(m)
+ del m_out[node]
+ execute_token_flow(out_flow.target, m_out, bpmn_graph)
+ m_outs.append(m_out)
+ elif isinstance(node, BPMN.InclusiveGateway):
+ for out_flows in power_set(node.get_out_arcs()):
+ for out_flow in out_flows:
+ m_out = copy.copy(m)
+ del m_out[node]
+ execute_token_flow(out_flow.target, m_out, bpmn_graph)
+ m_outs.append(m_out)
+ return m_outs
+
+
+def execute_token_flow(target, marking, bpmn_graph):
+ # next node is a subprocess --> add tokens in its start events
+ if isinstance(target, BPMN.SubProcess):
+ start_events = get_start_events_of_subprocess(
+ target.get_id(), bpmn_graph
+ )
+ for start_event in start_events:
+ marking[start_event] += 1
+ # handle external boundary events
+ for boundary_event in get_external_boundary_events_of_activity(
+ target.get_id(), bpmn_graph
+ ):
+ marking[boundary_event] += 1
+ elif isinstance(target, BPMN.EndEvent):
+ # end event globally
+ if target.get_process() == bpmn_graph.get_process_id():
+ if isinstance(target, BPMN.TerminateEndEvent):
+ keys_to_delete = [key for key in marking if key != target]
+ for key in keys_to_delete:
+ del marking[key]
+ marking[target] += 1
+ # end event is inside subprocess
+ else:
+ sub_process_node = get_node_by_id(target.get_process(), bpmn_graph)
+ # end event is connected to boundary transition
+ for boundary_event in get_boundary_events_of_activity(
+ sub_process_node.get_id(), bpmn_graph
+ ):
+ # TODO: also type of event could be checked, e.g. error end and
+ # boundary event
+ if (boundary_event.name == target.name):
+ # add token to boundary event
+ marking[boundary_event] += 1
+ # reset all tokens inside subprocess and on other boundary
+ # events
+ for key in get_all_nodes_inside_process(
+ target.get_process(), bpmn_graph
+ ):
+ if key in marking:
+ del marking[key]
+ for key in get_boundary_events_of_activity(
+ sub_process_node.get_id(), bpmn_graph
+ ):
+ if key in marking and key != boundary_event:
+ del marking[key]
+ return
+ # internal subprocess termination event
+ if isinstance(target, BPMN.TerminateEndEvent):
+ keys_to_delete = [
+ key
+ for key in marking
+ if key != target
+ and key
+ in get_all_nodes_inside_process(
+ target.get_process(), bpmn_graph
+ )
+ + get_boundary_events_of_activity(
+ sub_process_node.get_id(), bpmn_graph
+ )
+ ]
+ for key in keys_to_delete:
+ del marking[key]
+ # add marking at outgoing flow
+ if len(sub_process_node.get_out_arcs()) > 0:
+ target_node = sub_process_node.get_out_arcs()[0].target
+ execute_token_flow(target_node, marking, bpmn_graph)
+ return
+ # instead add token to end event, workaround to make sure that you
+ # can fire a message event even after the last event inside
+ # subprocess
+ marking[target] += 1
+ # just normal token flow to next node
+ else:
+ marking[target] += 1
+
+
+def enabled_nodes(bpmn, m):
+ """
+ Returns a set of enabled transitions in a Petri net and given marking
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param m: marking of the pn
+
+ Returns
+ -------
+ :return: set of enabled transitions
+ """
+ enabled = set()
+ for node in bpmn.get_nodes():
+ if is_enabled(node, bpmn, m):
+ enabled.add(node)
+ if (
+ isinstance(node, BPMN.EndEvent)
+ and node.get_process() == bpmn.get_process_id()
+ ): # if there is a token in an end event, we are done and there is no enabled node anymore
+ return set()
+ return enabled
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..78722cd045edb8e9d075d6912cbc3e7c1691484f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.util import reduction, sorting, bpmn_utils
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/bpmn_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/bpmn_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..37fa23f25857dd35f7071b74334710c975ef9ac3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/bpmn_utils.py
@@ -0,0 +1,215 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.obj import BPMN, Marking
+
+
+def get_node_by_id(id, bpmn_graph):
+ """
+ Returns the node with specified id
+
+ Parameters
+ ------------
+ id
+ id string
+ bpmn_graph
+ BPMN graph
+
+ Returns
+ ------------
+ node that matches the id
+ """
+ for node in bpmn_graph.get_nodes():
+ if node.get_id() == id:
+ return node
+ return None
+
+
+def get_global_start_events(bpmn_graph):
+ start_events = []
+ for node in bpmn_graph.get_nodes():
+ if isinstance(node, BPMN.StartEvent):
+ if node.get_process() == bpmn_graph.get_process_id():
+ start_events.append(node)
+ return start_events
+
+
+def get_initial_marking(bpmn_graph):
+ m = Marking()
+ for event in get_global_start_events(bpmn_graph):
+ m[event] = 1
+ return m
+
+
+def get_boundary_events_of_activity(activity_id, bpmn_graph):
+ boundary_events = []
+ for node in bpmn_graph.get_nodes():
+ if isinstance(node, BPMN.BoundaryEvent):
+ node_activity_id = node.get_activity()
+ if node_activity_id == activity_id:
+ boundary_events.append(node)
+ return boundary_events
+
+
+def get_external_boundary_events_of_activity(activity_id, bpmn_graph):
+ boundary_events = []
+ for node in bpmn_graph.get_nodes():
+ if isinstance(node, BPMN.MessageBoundaryEvent):
+ node_activity_id = node.get_activity()
+ if node_activity_id == activity_id:
+ boundary_events.append(node)
+ return boundary_events
+
+
+# TODO: Include nodes that are in deeper level, too
+def get_all_nodes_inside_process(process_id, bpmn_graph, deep=True):
+ nodes = []
+ for node in bpmn_graph.get_nodes():
+ if deep:
+ if process_id in get_processes_deep(node, bpmn_graph):
+ nodes.append(node)
+ else:
+ if node.get_process() == process_id:
+ nodes.append(node)
+ return nodes
+
+
+# return the direct children of a subprocess
+def get_all_direct_child_subprocesses(
+ process_id, bpmn_graph, include_normal=False
+):
+ nodes = set()
+ for node in bpmn_graph.get_nodes():
+ if (
+ isinstance(node, BPMN.SubProcess)
+ and node.get_process() == process_id
+ ):
+ if not include_normal:
+ boundary_events = get_boundary_events_of_activity(
+ node.get_id(), bpmn_graph
+ )
+ # termination events inside subprocess
+ termination_events = (
+ get_termination_events_of_subprocess_for_pnet(
+ node.get_id(), bpmn_graph
+ )
+ )
+ if len(boundary_events) > 0 or len(termination_events) > 0:
+ nodes.add(node)
+ else:
+ nodes.add(node)
+ return nodes
+
+
+# return the direct and indirect children of a subprocess
+def get_all_child_subprocesses(process_id, bpmn_graph, include_normal=False):
+ sub_processes = set()
+ for child in get_all_direct_child_subprocesses(
+ process_id, bpmn_graph, include_normal
+ ):
+ sub_processes.add(child)
+ sub_processes = sub_processes.union(
+ get_all_child_subprocesses(
+ child.get_id(), bpmn_graph, include_normal
+ )
+ )
+ return sub_processes
+
+
+def get_processes_deep(node, bpmn_graph):
+ if node.get_process() == bpmn_graph.get_process_id():
+ return [bpmn_graph.get_process_id()]
+ else:
+ return [node.get_process()] + get_processes_deep(
+ get_node_by_id(node.get_process(), bpmn_graph), bpmn_graph
+ )
+
+
+def get_subprocesses_sorted_by_depth(bpmn_graph):
+ return sorted(
+ [
+ node
+ for node in bpmn_graph.get_nodes()
+ if isinstance(node, BPMN.SubProcess)
+ ],
+ key=lambda x: x.get_depth(),
+ reverse=True,
+ )
+
+
+def get_termination_events_of_subprocess(activity_id, bpmn_graph):
+ events = []
+ for node in bpmn_graph.get_nodes():
+ if node.get_process() == activity_id and isinstance(
+ node, BPMN.TerminateEndEvent
+ ):
+ events.append(node)
+ return events
+
+
+def get_termination_events_of_subprocess_for_pnet(activity_id, bpmn_graph):
+ events = []
+ for node in bpmn_graph.get_nodes():
+ if node.get_process() == activity_id and isinstance(
+ node, (BPMN.IntermediateCatchEvent, BPMN.IntermediateThrowEvent)
+ ):
+ cond = False
+ for boundary_event in get_boundary_events_of_activity(
+ activity_id, bpmn_graph
+ ):
+ if boundary_event.get_name() == node.get_name():
+ cond = True
+ if not cond:
+ events.append(node)
+ return events
+
+
+def get_start_events_of_subprocess(activity_id, bpmn_graph):
+ events = []
+ for node in bpmn_graph.get_nodes():
+ if node.get_process() == activity_id and isinstance(
+ node, BPMN.StartEvent
+ ):
+ events.append(node)
+ return events
+
+
+def get_end_events_of_subprocess(activity_id, bpmn_graph):
+ events = []
+ for node in bpmn_graph.get_nodes():
+ if node.get_process() == activity_id and isinstance(
+ node, BPMN.EndEvent
+ ):
+ events.append(node)
+ return events
+
+
+def bpmn_graph_end_events_as_throw_events(bpmn_graph):
+ events = []
+ for node in bpmn_graph.get_nodes():
+ # subprocess end event
+ if (
+ node.get_process() != bpmn_graph.get_process_id()
+ and isinstance(node, BPMN.EndEvent)
+ and not isinstance(node, BPMN.NormalEndEvent)
+ ):
+ events.append(node)
+ return events
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/label_replacing.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/label_replacing.py
new file mode 100644
index 0000000000000000000000000000000000000000..524f1ed9538ea82664db2a3e129d67676d292ef0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/label_replacing.py
@@ -0,0 +1,39 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.bpmn.obj import BPMN
+from typing import Optional, Dict, Any
+from copy import deepcopy
+
+
+def apply(bpmn_graph: BPMN, string_dictio: Dict[str, str], parameters: Optional[Dict[Any, Any]] = None) -> BPMN:
+ if parameters is None:
+ parameters = {}
+
+ bpmn_graph = deepcopy(bpmn_graph)
+
+ for node in bpmn_graph.get_nodes():
+ if isinstance(node, BPMN.Task):
+ name = node.get_name()
+ if name in string_dictio:
+ node.set_name(string_dictio[name])
+
+ return bpmn_graph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/reduction.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..95ace577dff7910bda5efcd33fa10bcaa6627f66
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/reduction.py
@@ -0,0 +1,309 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.bpmn.obj import BPMN
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ COLLAPSE_GATEWAYS = "collapse_gateways"
+
+
+# Gateway classes for which two consecutive same-type gateways can be
+# merged without changing the language of the model. XOR and AND are
+# associative (``XOR(a, XOR(b, c)) = XOR(a, b, c)`` and likewise for
+# AND), so flattening a nested same-type split/join preserves the set of
+# accepted traces. Inclusive (OR) gateways are intentionally excluded to
+# keep the merge provably language preserving.
+_MERGEABLE_GATEWAYS = (BPMN.ExclusiveGateway, BPMN.ParallelGateway)
+
+
+def _edge_maps(bpmn_graph):
+ """Return ``(outgoing, incoming)`` flow maps keyed by node.
+
+ Both maps associate a node with the *set* of sequence flows leaving
+ (resp. entering) it. They are rebuilt from scratch whenever the graph
+ is mutated so callers never act on stale adjacency.
+ """
+ outgoing = {}
+ incoming = {}
+ for flow in bpmn_graph.get_flows():
+ source = flow.get_source()
+ target = flow.get_target()
+ outgoing.setdefault(source, set()).add(flow)
+ incoming.setdefault(target, set()).add(flow)
+ return outgoing, incoming
+
+
+def reduce_xor_gateways(bpmn_graph, parameters=None):
+ """
+ Reduces the number of XOR gateways in the diagram
+
+ Parameters
+ ------------
+ bpmn_graph
+ BPMN graph
+ parameters
+ Parameters
+
+ Returns
+ ------------
+ bpmn_graph
+ (possibly reduced) BPMN graph
+ """
+ if parameters is None:
+ parameters = {}
+
+ changed = True
+ while changed:
+ changed = False
+ outgoing_edges = None
+ incoming_edges = None
+ outgoing_edges = {}
+ incoming_edges = {}
+
+ for flow in bpmn_graph.get_flows():
+ source = flow.get_source()
+ target = flow.get_target()
+
+ if source not in outgoing_edges:
+ outgoing_edges[source] = set()
+ outgoing_edges[source].add(flow)
+
+ if target not in incoming_edges:
+ incoming_edges[target] = set()
+ incoming_edges[target].add(flow)
+
+ nodes = list(bpmn_graph.get_nodes())
+ for node in nodes:
+ if isinstance(node, BPMN.ExclusiveGateway):
+ if (
+ node in outgoing_edges
+ and node in incoming_edges
+ and len(outgoing_edges[node]) == 1
+ and len(incoming_edges[node]) == 1
+ ):
+ changed = True
+ source_node = None
+ target_node = None
+ for flow in incoming_edges[node]:
+ source_node = flow.get_source()
+ if flow in bpmn_graph.get_flows():
+ bpmn_graph.remove_flow(flow)
+ for flow in outgoing_edges[node]:
+ target_node = flow.get_target()
+ if flow in bpmn_graph.get_flows():
+ bpmn_graph.remove_flow(flow)
+ if node in bpmn_graph.get_nodes():
+ bpmn_graph.remove_node(node)
+ bpmn_graph.add_flow(
+ BPMN.SequenceFlow(source_node, target_node)
+ )
+ break
+
+ return bpmn_graph
+
+
+def remove_trivial_gateways(bpmn_graph, parameters=None):
+ """Remove gateways with exactly one incoming and one outgoing flow.
+
+ A gateway with a single input and a single output neither branches
+ nor synchronises anything, so it can be spliced out and its
+ predecessor connected straight to its successor. This holds for every
+ gateway type (XOR, AND and OR alike), hence the reduction is always
+ language preserving.
+ """
+ if parameters is None:
+ parameters = {}
+
+ changed = True
+ while changed:
+ changed = False
+ outgoing, incoming = _edge_maps(bpmn_graph)
+ for node in list(bpmn_graph.get_nodes()):
+ if not isinstance(node, BPMN.Gateway):
+ continue
+ ins = incoming.get(node, set())
+ outs = outgoing.get(node, set())
+ if len(ins) != 1 or len(outs) != 1:
+ continue
+ in_flow = next(iter(ins))
+ out_flow = next(iter(outs))
+ source = in_flow.get_source()
+ target = out_flow.get_target()
+ bpmn_graph.remove_flow(in_flow)
+ bpmn_graph.remove_flow(out_flow)
+ bpmn_graph.remove_node(node)
+ # Do not introduce a self-loop if the gateway sat on a
+ # one-node cycle; just drop it in that degenerate case.
+ if source is not target:
+ bpmn_graph.add_flow(BPMN.SequenceFlow(source, target))
+ changed = True
+ break
+
+ return bpmn_graph
+
+
+def collapse_split_gateways(bpmn_graph, parameters=None):
+ """Merge a split gateway into a same-type successor split gateway.
+
+ When a split gateway ``g`` has an outgoing flow to another split
+ gateway ``s`` of the same type and ``s`` has no other predecessor
+ than ``g``, the nesting ``g -> s`` is flattened: ``g`` absorbs every
+ outgoing branch of ``s`` and ``s`` is removed. This mirrors the
+ consecutive-split collapse performed by the reference Split Miner
+ implementation and is restricted to XOR/AND gateways so it stays
+ language preserving.
+ """
+ if parameters is None:
+ parameters = {}
+
+ changed = True
+ while changed:
+ changed = False
+ outgoing, incoming = _edge_maps(bpmn_graph)
+ for g in list(bpmn_graph.get_nodes()):
+ if not isinstance(g, _MERGEABLE_GATEWAYS):
+ continue
+ merged = False
+ for out_flow in list(outgoing.get(g, set())):
+ succ = out_flow.get_target()
+ if type(succ) is not type(g):
+ continue
+ succ_in = incoming.get(succ, set())
+ # the successor split must be fed exclusively by g
+ if any(f.get_source() is not g for f in succ_in):
+ continue
+ # g absorbs the successor's outgoing branches
+ for sf in list(outgoing.get(succ, set())):
+ tgt = sf.get_target()
+ bpmn_graph.remove_flow(sf)
+ if tgt is not g:
+ bpmn_graph.add_flow(BPMN.SequenceFlow(g, tgt))
+ for sf in list(succ_in):
+ bpmn_graph.remove_flow(sf)
+ bpmn_graph.remove_node(succ)
+ merged = True
+ changed = True
+ break
+ if merged:
+ break
+
+ return bpmn_graph
+
+
+def collapse_join_gateways(bpmn_graph, parameters=None):
+ """Merge a join gateway into a same-type predecessor join gateway.
+
+ Dual of :func:`collapse_split_gateways`. When a join gateway ``g`` is
+ fed by another join gateway ``p`` of the same type and ``p``'s only
+ successor is ``g``, the nesting ``p -> g`` is flattened: ``g`` absorbs
+ every incoming flow of ``p`` and ``p`` is removed. Restricted to
+ XOR/AND gateways to remain language preserving.
+ """
+ if parameters is None:
+ parameters = {}
+
+ changed = True
+ while changed:
+ changed = False
+ outgoing, incoming = _edge_maps(bpmn_graph)
+ for g in list(bpmn_graph.get_nodes()):
+ if not isinstance(g, _MERGEABLE_GATEWAYS):
+ continue
+ merged = False
+ for in_flow in list(incoming.get(g, set())):
+ pred = in_flow.get_source()
+ if type(pred) is not type(g):
+ continue
+ pred_out = outgoing.get(pred, set())
+ # the predecessor join must feed only g
+ if any(f.get_target() is not g for f in pred_out):
+ continue
+ # g absorbs the predecessor's incoming flows
+ for pf in list(incoming.get(pred, set())):
+ src = pf.get_source()
+ bpmn_graph.remove_flow(pf)
+ if src is not g:
+ bpmn_graph.add_flow(BPMN.SequenceFlow(src, g))
+ for pf in list(pred_out):
+ bpmn_graph.remove_flow(pf)
+ bpmn_graph.remove_node(pred)
+ merged = True
+ changed = True
+ break
+ if merged:
+ break
+
+ return bpmn_graph
+
+
+def collapse_gateways(bpmn_graph, parameters=None):
+ """Flatten nested same-type gateways and drop trivial ones.
+
+ Splits and joins are collapsed in alternation (split, join, split,
+ join) because collapsing one side can expose new opportunities on the
+ other; a final pass removes any single-in/single-out gateway left
+ behind. All steps preserve the language of the model.
+ """
+ if parameters is None:
+ parameters = {}
+
+ collapse_split_gateways(bpmn_graph, parameters=parameters)
+ collapse_join_gateways(bpmn_graph, parameters=parameters)
+ collapse_split_gateways(bpmn_graph, parameters=parameters)
+ collapse_join_gateways(bpmn_graph, parameters=parameters)
+ remove_trivial_gateways(bpmn_graph, parameters=parameters)
+ return bpmn_graph
+
+
+def apply(bpmn_graph, parameters=None):
+ """
+ Reduce the complexity of a BPMN graph by removing useless elements
+
+ Parameters
+ ------------
+ bpmn_graph
+ BPMN graph
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.COLLAPSE_GATEWAYS: when set to ``True``, also flatten
+ nested same-type (XOR/AND) split and join gateways. Disabled by
+ default so existing callers keep the conservative behaviour.
+
+ Returns
+ ------------
+ bpmn_graph
+ (possibly reduced) BPMN graph
+ """
+ if parameters is None:
+ parameters = {}
+
+ bpmn_graph = reduce_xor_gateways(bpmn_graph, parameters=parameters)
+
+ if exec_utils.get_param_value(
+ Parameters.COLLAPSE_GATEWAYS, parameters, False
+ ):
+ bpmn_graph = collapse_gateways(bpmn_graph, parameters=parameters)
+
+ return bpmn_graph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/sorting.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/sorting.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2daa8309e38fdcc677872d08a69688f5b12a355
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/util/sorting.py
@@ -0,0 +1,80 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Iterable, List, Tuple
+from pm4py.objects.bpmn.obj import BPMN
+
+
+def bfs_bpmn(
+ nodes: Iterable[BPMN.Event], edges: Iterable[Tuple[BPMN.Event, BPMN.Event]]
+):
+ start_nodes: List[BPMN.Event] = [
+ n for n in nodes if isinstance(n, BPMN.StartEvent)
+ ]
+ level = 0
+ bfs = {n: level for n in start_nodes}
+ while True:
+ level += 1
+ to_visit = list(
+ e[1]
+ for e in edges
+ if e[0] in bfs
+ and e[1] not in bfs
+ and not isinstance(e[1], BPMN.EndEvent)
+ )
+ if not to_visit:
+ break
+ for n in to_visit:
+ bfs[n] = level
+ other_nodes = [n for n in nodes if n not in bfs]
+ level += 1
+ for n in other_nodes:
+ bfs[n] = level
+ return bfs
+
+
+def get_sorted_nodes_edges(
+ bpmn_graph: BPMN,
+) -> Tuple[List[BPMN.Event], List[Tuple[BPMN.Event, BPMN.Event]]]:
+ """
+ Assure an ordering as-constant-as-possible
+
+ Parameters
+ --------------
+ bpmn_graph
+ BPMN graph
+
+ Returns
+ --------------
+ nodes
+ List of nodes of the BPMN graph
+ edges
+ List of edges of the BPMN graph
+ """
+ graph = bpmn_graph.get_graph()
+ graph_nodes: List[BPMN.Event] = list(graph.nodes(data=False))
+ graph_edges: List[Tuple[BPMN.Event, BPMN.Event]] = list(
+ graph.edges(data=False)
+ )
+ bfs = bfs_bpmn(graph_nodes, graph_edges)
+ graph_nodes = sorted(graph_nodes, key=lambda x: bfs[x])
+ graph_edges = sorted(graph_edges, key=lambda x: (bfs[x[0]], bfs[x[1]]))
+ return graph_nodes, graph_edges
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..88fa3af5754c6c06482a9c01ea54a12f80ddf0e3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/__init__.py
@@ -0,0 +1,33 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion import (
+ bpmn,
+ heuristics_net,
+ genetic_matrix,
+ process_tree,
+ wf_net,
+ log,
+ dfg,
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dda60a5026e5f0bbdd7cca84aa5ddd75953ba3be
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.bpmn import converter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a57393b6349e4f6ac98b3d14512f66b5d4cb4a1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/converter.py
@@ -0,0 +1,39 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.conversion.bpmn.variants import to_petri_net
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ TO_PETRI_NET = to_petri_net
+
+
+DEFAULT_VARIANT = Variants.TO_PETRI_NET
+
+
+def apply(obj, variant=DEFAULT_VARIANT, parameters=None):
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).apply(obj, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cf8267f8945886cc0b119a0522cb13bff095bb5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.bpmn.variants import to_petri_net
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/variants/to_petri_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/variants/to_petri_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb8c22e6a1c7c0604707ac7a231c48c08ba3a416
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/bpmn/variants/to_petri_net.py
@@ -0,0 +1,316 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import uuid
+from enum import Enum
+
+from pm4py.objects.petri_net.utils import reduction
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.bpmn.obj import BPMN
+from pm4py.objects.petri_net.utils.petri_utils import remove_place
+from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to
+from pm4py.util import exec_utils, nx_utils
+
+
+class Parameters(Enum):
+ USE_ID = "use_id"
+ ENABLE_REDUCTION = "enable_reduction"
+ RETURN_FLOW_TRANS_MAP = "return_flow_trans_map"
+
+
+def build_digraph_from_petri_net(net):
+ """
+ Builds a directed graph from a Petri net
+ (for the purpose to add invisibles between inclusive gateways)
+
+ Parameters
+ -------------
+ net
+ Petri net
+
+ Returns
+ -------------
+ digraph
+ Digraph
+ """
+ graph = nx_utils.DiGraph()
+ for place in net.places:
+ graph.add_node(place.name)
+ for trans in net.transitions:
+ in_places = [x.source for x in list(trans.in_arcs)]
+ out_places = [x.target for x in list(trans.out_arcs)]
+ for pl1 in in_places:
+ for pl2 in out_places:
+ graph.add_edge(pl1.name, pl2.name)
+ return graph
+
+
+def apply(bpmn_graph, parameters=None):
+ """
+ Converts a BPMN graph to an accepting Petri net.
+
+ Parameters
+ ----------
+ bpmn_graph
+ BPMN graph
+ parameters
+ Parameters of the algorithm:
+
+ - Parameters.USE_ID => (default: False) uses the IDs of the objects instead of their labels in the conversion
+ - Parameters.ENABLE_REDUCTION => reduces the invisible transitions
+ - Parameters.RETURN_FLOW_TRANS_MAP => returns additional information on the conversion: (iv) the places of the obtained Petri net that are corresponding to each BPMN flow. (v) the transitions of the Petri net related to the nodes of the BPMN diagram.
+
+ Returns
+ -----------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.objects.bpmn.obj import BPMN
+
+ use_id = exec_utils.get_param_value(Parameters.USE_ID, parameters, False)
+ return_flow_trans_map = exec_utils.get_param_value(
+ Parameters.RETURN_FLOW_TRANS_MAP, parameters, False
+ )
+ enable_reduction = exec_utils.get_param_value(
+ Parameters.ENABLE_REDUCTION, parameters, True
+ )
+
+ if return_flow_trans_map:
+ enable_reduction = False
+
+ net = PetriNet("")
+ source_place = PetriNet.Place("source")
+ net.places.add(source_place)
+ sink_place = PetriNet.Place("sink")
+ net.places.add(sink_place)
+ im = Marking()
+ fm = Marking()
+ im[source_place] = 1
+ fm[sink_place] = 1
+
+ # keep this correspondence for adding invisible transitions for OR-gateways
+ inclusive_gateway_exit = set()
+ inclusive_gateway_entry = set()
+
+ flow_place = {}
+ source_count = {}
+ target_count = {}
+ for flow in bpmn_graph.get_flows():
+ if isinstance(flow, BPMN.SequenceFlow):
+ source = flow.get_source()
+ target = flow.get_target()
+ place = PetriNet.Place(str(flow.get_id()))
+ net.places.add(place)
+ flow_place[flow] = place
+ if source not in source_count:
+ source_count[source] = 0
+ if target not in target_count:
+ target_count[target] = 0
+ source_count[source] = source_count[source] + 1
+ target_count[target] = target_count[target] + 1
+
+ for flow in bpmn_graph.get_flows():
+ if isinstance(flow, BPMN.SequenceFlow):
+ source = flow.get_source()
+ target = flow.get_target()
+ place = PetriNet.Place(str(flow.get_id()))
+ if (
+ isinstance(source, BPMN.InclusiveGateway)
+ and source_count[source] > 1
+ ):
+ inclusive_gateway_exit.add(place.name)
+ elif (
+ isinstance(target, BPMN.InclusiveGateway)
+ and target_count[target] > 1
+ ):
+ inclusive_gateway_entry.add(place.name)
+
+ # remove possible places that are both in inclusive_gateway_exit and inclusive_gateway_entry,
+ # because we do not need to add invisibles in this situation
+ incl_gat_set_inters = inclusive_gateway_entry.intersection(
+ inclusive_gateway_exit
+ )
+ inclusive_gateway_exit = inclusive_gateway_exit.difference(
+ incl_gat_set_inters
+ )
+ inclusive_gateway_entry = inclusive_gateway_entry.difference(
+ incl_gat_set_inters
+ )
+
+ nodes_entering = {}
+ nodes_exiting = {}
+ trans_map = {}
+
+ for node in bpmn_graph.get_nodes():
+ if (
+ isinstance(node, BPMN.Task)
+ or isinstance(node, BPMN.StartEvent)
+ or isinstance(node, BPMN.EndEvent)
+ or isinstance(node, BPMN.ExclusiveGateway)
+ or isinstance(node, BPMN.ParallelGateway)
+ or isinstance(node, BPMN.InclusiveGateway)
+ ):
+ if node not in source_count:
+ source_count[node] = 0
+ if node not in target_count:
+ target_count[node] = 0
+
+ entry_place = PetriNet.Place("ent_" + str(node.get_id()))
+ net.places.add(entry_place)
+ exiting_place = PetriNet.Place("exi_" + str(node.get_id()))
+ net.places.add(exiting_place)
+ if use_id:
+ label = str(node.get_id())
+ else:
+ label = (
+ str(node.get_name())
+ if isinstance(node, BPMN.Task)
+ else None
+ )
+ if not label:
+ label = None
+ transition = PetriNet.Transition(
+ name=str(node.get_id()), label=label
+ )
+ net.transitions.add(transition)
+ trans_map[node] = [transition]
+ add_arc_from_to(entry_place, transition, net)
+ add_arc_from_to(transition, exiting_place, net)
+
+ if isinstance(node, BPMN.ParallelGateway) or isinstance(
+ node, BPMN.InclusiveGateway
+ ):
+ if source_count[node] > 1:
+ exiting_object = PetriNet.Transition(
+ str(uuid.uuid4()), None
+ )
+ net.transitions.add(exiting_object)
+ add_arc_from_to(exiting_place, exiting_object, net)
+ trans_map[node].append(exiting_object)
+ else:
+ exiting_object = exiting_place
+
+ if target_count[node] > 1:
+ entering_object = PetriNet.Transition(
+ str(uuid.uuid4()), None
+ )
+ net.transitions.add(entering_object)
+ add_arc_from_to(entering_object, entry_place, net)
+ trans_map[node].append(entering_object)
+ else:
+ entering_object = entry_place
+ nodes_entering[node] = entering_object
+ nodes_exiting[node] = exiting_object
+ else:
+ nodes_entering[node] = entry_place
+ nodes_exiting[node] = exiting_place
+
+ if isinstance(node, BPMN.StartEvent):
+ start_transition = PetriNet.Transition(str(uuid.uuid4()), None)
+ net.transitions.add(start_transition)
+ add_arc_from_to(source_place, start_transition, net)
+ add_arc_from_to(start_transition, entry_place, net)
+ trans_map[node].append(start_transition)
+ elif isinstance(node, BPMN.EndEvent):
+ end_transition = PetriNet.Transition(str(uuid.uuid4()), None)
+ net.transitions.add(end_transition)
+ add_arc_from_to(exiting_place, end_transition, net)
+ add_arc_from_to(end_transition, sink_place, net)
+ trans_map[node].append(end_transition)
+
+ for flow in bpmn_graph.get_flows():
+ if isinstance(flow, BPMN.SequenceFlow):
+ if (
+ flow.get_source() in nodes_exiting
+ and flow.get_target() in nodes_entering
+ ):
+ source_object = nodes_exiting[flow.get_source()]
+ target_object = nodes_entering[flow.get_target()]
+
+ if isinstance(source_object, PetriNet.Place):
+ inv1 = PetriNet.Transition(f"sfl_{flow.get_id()}", None)
+ net.transitions.add(inv1)
+ add_arc_from_to(source_object, inv1, net)
+ source_object = inv1
+ trans_map[flow.source].append(inv1)
+
+ if isinstance(target_object, PetriNet.Place):
+ inv2 = PetriNet.Transition(f"tfl_{flow.get_id()}", None)
+ net.transitions.add(inv2)
+ add_arc_from_to(inv2, target_object, net)
+ target_object = inv2
+ trans_map[flow.target].append(inv2)
+
+ add_arc_from_to(source_object, flow_place[flow], net)
+ add_arc_from_to(flow_place[flow], target_object, net)
+
+ if inclusive_gateway_exit and inclusive_gateway_entry:
+ # do the following steps if there are inclusive gateways:
+ # - calculate the shortest paths
+ # - add an invisible transition between couples of corresponding places
+ # this ensures soundness and the correct translation of the BPMN
+ inv_places = {x.name: x for x in net.places}
+ digraph = build_digraph_from_petri_net(net)
+ all_shortest_paths = dict(nx_utils.all_pairs_dijkstra(digraph))
+ keys = list(all_shortest_paths.keys())
+
+ for pl1 in inclusive_gateway_exit:
+ if pl1 in keys:
+ output_places = sorted(
+ [
+ (x, len(y))
+ for x, y in all_shortest_paths[pl1][1].items()
+ if x in inclusive_gateway_entry
+ ],
+ key=lambda x: x[1],
+ )
+ if output_places:
+ inv_trans = PetriNet.Transition(str(uuid.uuid4()), None)
+ net.transitions.add(inv_trans)
+ add_arc_from_to(inv_places[pl1], inv_trans, net)
+ add_arc_from_to(
+ inv_trans, inv_places[output_places[0][0]], net
+ )
+
+ if enable_reduction:
+ reduction.apply_simple_reduction(net)
+
+ for place in list(net.places):
+ if (
+ len(place.in_arcs) == 0
+ and len(place.out_arcs) == 0
+ and place not in im
+ and place not in fm
+ ):
+ remove_place(net, place)
+
+ if return_flow_trans_map:
+ return net, im, fm, flow_place, trans_map
+
+ return net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f34e5d53f614643b8df0d08c98b25b13d7c1ad9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.dfg import converter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..9828d3d1fb086881eb98e54fc23afd08c61cb659
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/converter.py
@@ -0,0 +1,43 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.dfg.variants import (
+ to_petri_net_activity_defines_place,
+ to_petri_net_invisibles_no_duplicates,
+)
+from enum import Enum
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ VERSION_TO_PETRI_NET_ACTIVITY_DEFINES_PLACE = (
+ to_petri_net_activity_defines_place
+ )
+ VERSION_TO_PETRI_NET_INVISIBLES_NO_DUPLICATES = (
+ to_petri_net_invisibles_no_duplicates
+ )
+
+
+DEFAULT_VARIANT = Variants.VERSION_TO_PETRI_NET_ACTIVITY_DEFINES_PLACE
+
+
+def apply(dfg, parameters=None, variant=DEFAULT_VARIANT):
+ return exec_utils.get_variant(variant).apply(dfg, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3382fe8e80b948e079c974cfdaafb1a42b1375d0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.dfg.variants import (
+ to_petri_net_activity_defines_place,
+ to_petri_net_invisibles_no_duplicates,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/to_petri_net_activity_defines_place.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/to_petri_net_activity_defines_place.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e5b8aa569e8a33096fb4a5f9f16561e0cb0e6cb
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/to_petri_net_activity_defines_place.py
@@ -0,0 +1,110 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.dfg.utils import dfg_utils
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.petri_net.utils import petri_utils as pn_util
+from enum import Enum
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ START_ACTIVITIES = "start_activities"
+ END_ACTIVITIES = "end_activities"
+
+
+PARAM_KEY_START_ACTIVITIES = Parameters.START_ACTIVITIES
+PARAM_KEY_END_ACTIVITIES = Parameters.END_ACTIVITIES
+
+
+def apply(dfg, parameters=None):
+ """
+ Applies the DFG mining on a given object (if it is a Pandas dataframe or a log, the DFG is calculated)
+
+ Parameters
+ -------------
+ dfg
+ Object (DFG) (if it is a Pandas dataframe or a log, the DFG is calculated)
+ parameters
+ Parameters
+ """
+ if parameters is None:
+ parameters = {}
+
+ dfg = dfg
+ start_activities = exec_utils.get_param_value(
+ Parameters.START_ACTIVITIES,
+ parameters,
+ dfg_utils.infer_start_activities(dfg),
+ )
+ end_activities = exec_utils.get_param_value(
+ Parameters.END_ACTIVITIES,
+ parameters,
+ dfg_utils.infer_end_activities(dfg),
+ )
+ activities = dfg_utils.get_activities_from_dfg(dfg)
+
+ net = PetriNet("")
+ im = Marking()
+ fm = Marking()
+
+ source = PetriNet.Place("source")
+ net.places.add(source)
+ im[source] = 1
+ sink = PetriNet.Place("sink")
+ net.places.add(sink)
+ fm[sink] = 1
+
+ places_corr = {}
+ index = 0
+
+ for act in activities:
+ places_corr[act] = PetriNet.Place(act)
+ net.places.add(places_corr[act])
+
+ for act in start_activities:
+ if act in places_corr:
+ index = index + 1
+ trans = PetriNet.Transition(act + "_" + str(index), act)
+ net.transitions.add(trans)
+ pn_util.add_arc_from_to(source, trans, net)
+ pn_util.add_arc_from_to(trans, places_corr[act], net)
+
+ for act in end_activities:
+ if act in places_corr:
+ index = index + 1
+ inv_trans = PetriNet.Transition(act + "_" + str(index), None)
+ net.transitions.add(inv_trans)
+ pn_util.add_arc_from_to(places_corr[act], inv_trans, net)
+ pn_util.add_arc_from_to(inv_trans, sink, net)
+
+ for el in dfg.keys():
+ act1 = el[0]
+ act2 = el[1]
+
+ index = index + 1
+ trans = PetriNet.Transition(act2 + "_" + str(index), act2)
+ net.transitions.add(trans)
+
+ pn_util.add_arc_from_to(places_corr[act1], trans, net)
+ pn_util.add_arc_from_to(trans, places_corr[act2], net)
+
+ return net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/to_petri_net_invisibles_no_duplicates.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/to_petri_net_invisibles_no_duplicates.py
new file mode 100644
index 0000000000000000000000000000000000000000..518a406cfa2779dbbc6758a2d7f164e378cd1a89
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/dfg/variants/to_petri_net_invisibles_no_duplicates.py
@@ -0,0 +1,124 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from copy import copy
+from enum import Enum
+from typing import Optional, Dict, Any, Tuple
+
+from pm4py.objects.dfg.utils import dfg_utils
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.petri_net.utils import petri_utils
+from pm4py.util import exec_utils, constants
+
+
+class Parameters(Enum):
+ START_ACTIVITIES = "start_activities"
+ END_ACTIVITIES = "end_activities"
+ PARAM_ARTIFICIAL_START_ACTIVITY = constants.PARAM_ARTIFICIAL_START_ACTIVITY
+ PARAM_ARTIFICIAL_END_ACTIVITY = constants.PARAM_ARTIFICIAL_END_ACTIVITY
+
+
+def apply(
+ dfg: Dict[Tuple[str, str], int],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Applies the DFG mining on a given object (if it is a Pandas dataframe or a log, the DFG is calculated)
+
+ Parameters
+ -------------
+ dfg
+ Object (DFG) (if it is a Pandas dataframe or a log, the DFG is calculated)
+ parameters
+ Parameters:
+ - Parameters.START_ACTIVITIES: the start activities of the DFG
+ - Parameters.END_ACTIVITIES: the end activities of the DFG
+
+ Returns
+ -------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ """
+ if parameters is None:
+ parameters = {}
+
+ start_activities = exec_utils.get_param_value(
+ Parameters.START_ACTIVITIES,
+ parameters,
+ {x: 1 for x in dfg_utils.infer_start_activities(dfg)},
+ )
+ end_activities = exec_utils.get_param_value(
+ Parameters.END_ACTIVITIES,
+ parameters,
+ {x: 1 for x in dfg_utils.infer_end_activities(dfg)},
+ )
+ artificial_start_activity = exec_utils.get_param_value(
+ Parameters.PARAM_ARTIFICIAL_START_ACTIVITY,
+ parameters,
+ constants.DEFAULT_ARTIFICIAL_START_ACTIVITY,
+ )
+ artificial_end_activity = exec_utils.get_param_value(
+ Parameters.PARAM_ARTIFICIAL_END_ACTIVITY,
+ parameters,
+ constants.DEFAULT_ARTIFICIAL_END_ACTIVITY,
+ )
+
+ enriched_dfg = copy(dfg)
+ for act in start_activities:
+ enriched_dfg[(artificial_start_activity, act)] = start_activities[act]
+ for act in end_activities:
+ enriched_dfg[(act, artificial_end_activity)] = end_activities[act]
+ activities = set(x[1] for x in enriched_dfg).union(
+ set(x[0] for x in enriched_dfg)
+ )
+ net = PetriNet("")
+ im = Marking()
+ fm = Marking()
+ left_places = {}
+ transes = {}
+ right_places = {}
+ for act in activities:
+ pl1 = PetriNet.Place("source_" + act)
+ pl2 = PetriNet.Place("sink_" + act)
+ trans = PetriNet.Transition("trans_" + act, act)
+ if act in [artificial_start_activity, artificial_end_activity]:
+ trans.label = None
+ net.places.add(pl1)
+ net.places.add(pl2)
+ net.transitions.add(trans)
+ petri_utils.add_arc_from_to(pl1, trans, net)
+ petri_utils.add_arc_from_to(trans, pl2, net)
+ left_places[act] = pl1
+ right_places[act] = pl2
+ transes[act] = trans
+ for arc in enriched_dfg:
+ hidden = PetriNet.Transition(arc[0] + "_" + arc[1], None)
+ net.transitions.add(hidden)
+ petri_utils.add_arc_from_to(right_places[arc[0]], hidden, net)
+ petri_utils.add_arc_from_to(hidden, left_places[arc[1]], net)
+ im[left_places[artificial_start_activity]] = 1
+ fm[right_places[artificial_end_activity]] = 1
+
+ return net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9da6692bfd570e2a6be6ccbb257a51c5477fe8bf
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/__init__.py
@@ -0,0 +1,28 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+# Author: Maximilian Josef Frank (https://orcid.org/0000-0002-0714-7748)
+
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.genetic_matrix import converter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb4c85f5630e57fc72e83af01b519db01d2ef289
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/converter.py
@@ -0,0 +1,50 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+# Author: Maximilian Josef Frank (https://orcid.org/0000-0002-0714-7748)
+
+from pm4py.objects.conversion.genetic_matrix.variants import to_petri_net
+from enum import Enum
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ TO_PETRI_NET = to_petri_net
+
+
+def apply(genetic_matrix, parameters=None, variant=Variants.TO_PETRI_NET):
+ """
+ Converts a GeneticMatrix to a different type of object
+
+ Parameters
+ --------------
+ genetic_matrix
+ Genetic matrix
+ parameters
+ Possible parameters of the algorithm
+ variant
+ Variant of the algorithm:
+ - Variants.TO_PETRI_NET
+ """
+ return exec_utils.get_variant(variant).apply(
+ genetic_matrix, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e43d123e7979daa9b03195289961b0cfc7f5b321
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/variants/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+# Author: Maximilian Josef Frank (https://orcid.org/0000-0002-0714-7748)
+
+from pm4py.objects.conversion.genetic_matrix.variants import to_petri_net
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/variants/to_petri_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/variants/to_petri_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..b20518e58c9eb2c74eeeb2a0e2e98c1c4772f54e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/genetic_matrix/variants/to_petri_net.py
@@ -0,0 +1,148 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+# Author: Maximilian Josef Frank (https://orcid.org/0000-0002-0714-7748)
+
+from collections import defaultdict
+import copy
+import itertools
+
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.petri_net.utils import petri_utils
+
+
+def apply(genetic_matrix, parameters=None):
+ """
+ Converts a Genetic matrix to a Petri net
+
+ Reference paper:
+ Maximilian Josef Frank. "Optimising and Implementing the Genetic Miner in PM4Py" (2026).
+
+ Parameters
+ --------------
+ genetic_matrix
+ Genetic matrix
+ parameters
+ (Unused) Possible parameters of the algorithm
+
+ Returns
+ --------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ """
+ # import here to resolve circular import dependencies
+ from pm4py.algo.discovery.genetic.util import get_src_sink_sets_for_wfnet, iset
+ I = genetic_matrix.input_map
+ O = genetic_matrix.output_map
+ T = genetic_matrix.transitions
+ # @src 5.3. Sophisticated Mapping, Def. 7; https://doi.org/10.1007/11494744_5
+ # original, but insanely inefficient (for |A|=23, |P(A)|=8388608):
+ # X = {(Ti, To) ∈ P(A) × P(A) | ∀t∈Ti To ∈ O(t) ∧ ∀t∈To Ti ∈ I(t)}
+ # equivalent and more efficient (for |A|=23, |I(∀t)×O(∀t)|=24×16=384):
+ # X = {(Ti, To) ∈ I(∀t) × O(∀t) | ∀t∈Ti To ∈ O(t) ∧ ∀t∈To Ti ∈ I(t)}
+ X = list(filter( # if no list(), X gets consumed as stream
+ lambda Tio: # = (Ti, To)
+ all(Tio[1] in O[t] for t in Tio[0]) and
+ all(Tio[0] in I[t] for t in Tio[1]),
+ # holds s. Def 4, constraint 3+4; https://doi.org/10.1007/11494744_5
+ itertools.product(
+ iset.flat(I.values()),
+ iset.flat(O.values())
+ )
+ ))
+ Xs = list(itertools.chain( # Xs = non-sophisticated / silent-transition places
+ [ (Si,iset([t])) for Ti,t in zip(I.values(), I.keys()) for Si in Ti],
+ [ (iset([t]),So) for t,To in zip(O.keys(), O.values()) for So in To]
+ ))
+ # remove places in Xs which are fully covered by X
+ Xs = [ Tio for Tio in Xs if not any(
+ Tio[0] <= Ti and Tio[1] <= To for Ti,To in X
+ )]
+ # remove Xs (silent transitions from non-simple matrix) from X (see later)
+ def is_transitively_not_sophisticated(Tio, places):
+ """If place `Tio` is not in sophisticated mapping (i.e. place in `Xs`), all adjacent places (i.e. with same input/output transition) are replaced by non-sophisticated places and their silent transitions."""
+ return any(
+ len(Ti & Tio[0]) or len(To & Tio[1]) # & = intersect
+ for Ti,To in places
+ )
+ check = copy.copy(X)
+ while check:
+ Tio = check.pop(0)
+ if is_transitively_not_sophisticated(Tio, Xs):
+ Xs.append(Tio)
+ X.remove(Tio)
+ for Tio2 in X:
+ if Tio2 not in check and is_transitively_not_sophisticated(Tio2, Xs):
+ check.append(Tio2)
+ # build PetriNet
+ io = [PetriNet.Place('i'), PetriNet.Place('o')]
+ net = PetriNet(
+ places = [PetriNet.Place(p) for p in map(str, X)] + io,
+ transitions = [PetriNet.Transition(t,label=t) for t in T]
+ )
+ # original: F = {(i,t) | t∈T ∧ •t=∅} ∪ {(t,o) | t∈T ∧ t•=∅} ∪ …
+ T_noI, T_noO = get_src_sink_sets_for_wfnet(I, O, T)
+ arcs_pt = [ ('i', t) for t in T_noI ] + [
+ ((Ti,To), t) for (Ti,To),t in itertools.product(X, T) if t in To
+ ]
+ arcs_tp = [ (t, 'o') for t in T_noO ] + [
+ (t, (Ti,To)) for t,(Ti,To) in itertools.product(T, X) if t in Ti
+ ]
+ # convert to instances
+ getPlace = lambda name: next(filter(lambda p: p.name == name, net.places), None)
+ getTransition = lambda name: next(filter(lambda t: t.name == name, net.transitions), None)
+ arcs_pt = [(getPlace(str(p)), getTransition(t)) for p,t in arcs_pt]
+ arcs_tp = [(getTransition(t), getPlace(str(p))) for t,p in arcs_tp]
+ # add instance arcs
+ for i,o in itertools.chain(arcs_pt, arcs_tp):
+ petri_utils.add_arc_from_to(i, o, net)
+ # if causal matrix not simple (Def. 8; https://doi.org/10.1007/11494744_5):
+ # @src 5.2. Naive Mapping, Def. 6; https://doi.org/10.1007/11494744_5
+ # add incoming/outgoing silent places
+ Ti = set(itertools.chain(*(Ti for Ti,_ in Xs)))
+ To = set(itertools.chain(*(To for _,To in Xs)))
+ Ps_o = { name : PetriNet.Place("o"+str(name)) # output of prev non-silent T
+ for name in [ (t,s) for t in Ti for s in O[t] ]
+ }
+ Ps_i = { name : PetriNet.Place("i"+str(name)) # input of next non-silent T
+ for name in [ (t,s) for t in To for s in I[t] ]
+ }
+ net.places.extend(itertools.chain(Ps_o.values(), Ps_i.values()))
+ Ts = defaultdict(lambda: PetriNet.Transition(name="", label=None)) # name="",label=None → silent
+ # add arcs
+ for (t1,So),p in Ps_o.items():
+ petri_utils.add_arc_from_to(getTransition(t1), p, net)
+ for t2 in So: # connect silent T
+ petri_utils.add_arc_from_to(p, Ts[t1,t2], net)
+ for (t2,Si),p in Ps_i.items():
+ petri_utils.add_arc_from_to(p, getTransition(t2), net)
+ for t1 in Si: # connect silent T
+ petri_utils.add_arc_from_to(Ts[t1,t2], p, net)
+ net.transitions.extend(Ts.values())
+ # add markings
+ markings = [Marking() for _ in io]
+ for m,p in zip(markings, io):
+ m[p] = 1
+ return (net, *markings)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..02e3e77af6c2556023adafaaa80abe13231a6f41
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.heuristics_net import converter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..d046c38a014171a898ed2fb0d5d4a3ae01620081
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/converter.py
@@ -0,0 +1,47 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.heuristics_net.variants import to_petri_net
+from enum import Enum
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ TO_PETRI_NET = to_petri_net
+
+
+def apply(heu_net, parameters=None, variant=Variants.TO_PETRI_NET):
+ """
+ Converts an Heuristics Net to a different type of object
+
+ Parameters
+ --------------
+ heu_net
+ Heuristics net
+ parameters
+ Possible parameters of the algorithm
+ variant
+ Variant of the algorithm:
+ - Variants.TO_PETRI_NET
+ """
+ return exec_utils.get_variant(variant).apply(
+ heu_net, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..35951fbac8fb7b4c57efe5b98f3ee54f1a5d452f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.heuristics_net.variants import to_petri_net
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/variants/to_petri_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/variants/to_petri_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa01e31ca5c148d6a500e6d41be898f9f1eec50b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/heuristics_net/variants/to_petri_net.py
@@ -0,0 +1,332 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to, remove_transition
+from pm4py.util import nx_utils
+
+
+def remove_rendundant_invisible_transitions(net):
+ """
+ Remove redundant transitions from Petri net
+
+ Parameters
+ -----------
+ net
+ Petri net
+
+ Returns
+ -----------
+ net
+ Cleaned net
+ """
+ trans = [x for x in list(net.transitions) if not x.label]
+ i = 0
+ while i < len(trans):
+ if trans[i] in net.transitions:
+ preset_i = set(x.source for x in trans[i].in_arcs)
+ postset_i = set(x.target for x in trans[i].out_arcs)
+ j = 0
+ while j < len(trans):
+ if not j == i:
+ preset_j = set(x.source for x in trans[j].in_arcs)
+ postset_j = set(x.target for x in trans[j].out_arcs)
+ if len(preset_j) == len(preset_i) and len(postset_j) < len(postset_i):
+ if (
+ len(preset_j.intersection(preset_i)) == len(preset_j)
+ and len(postset_j.intersection(postset_i)) == len(postset_j)
+ ):
+ remove_transition(net, trans[j])
+ del trans[j]
+ continue
+ j = j + 1
+ i = i + 1
+ return net
+
+
+def find_bindings(and_measures):
+ """
+ Find the bindings given the AND measures.
+
+ NOTE: and_measures_in/out is stored asymmetrically (only one direction
+ for each unordered pair). We build an undirected graph and take maximal cliques.
+ """
+ G = nx_utils.Graph()
+
+ # FIX 1: build the graph correctly (and don't mis-add n1 instead of n2)
+ for n1, rels in and_measures.items():
+ G.add_node(n1)
+ for n2 in rels:
+ G.add_node(n2)
+ G.add_edge(n1, n2)
+
+ return list(nx_utils.find_cliques(G))
+
+
+def apply(heu_net, parameters=None):
+ """
+ Converts an Heuristics Net to a Petri net
+
+ Parameters
+ --------------
+ heu_net
+ Heuristics net
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ """
+ if parameters is None:
+ parameters = {}
+
+ net = PetriNet("")
+ im = Marking()
+ fm = Marking()
+
+ source_places = []
+ sink_places = []
+ hid_trans_count = 0
+
+ # Create one source/sink place per (possibly merged) start/end set (kept as in original)
+ for index, sa_list in enumerate(heu_net.start_activities):
+ source = PetriNet.Place("source" + str(index))
+ source_places.append(source)
+ net.places.add(source)
+ im[source] = 1
+
+ for index, ea_list in enumerate(heu_net.end_activities):
+ sink = PetriNet.Place("sink" + str(index))
+ sink_places.append(sink)
+ net.places.add(sink)
+ fm[sink] = 1
+
+ act_trans = {}
+ who_is_entering = {}
+ who_is_exiting = {}
+
+ # Build transitions and predecessor/successor relations
+ for act1_name in heu_net.nodes:
+ act1 = heu_net.nodes[act1_name]
+
+ if act1_name not in act_trans:
+ act_trans[act1_name] = PetriNet.Transition(act1_name, act1_name)
+ net.transitions.add(act_trans[act1_name])
+ who_is_entering[act1_name] = set()
+ who_is_exiting[act1_name] = set()
+
+ for index, sa_list in enumerate(heu_net.start_activities):
+ if act1_name in sa_list:
+ who_is_entering[act1_name].add((None, index))
+
+ for index, ea_list in enumerate(heu_net.end_activities):
+ if act1_name in ea_list:
+ who_is_exiting[act1_name].add((None, index))
+
+ for act2 in act1.output_connections:
+ act2_name = act2.node_name
+
+ if act2_name not in act_trans:
+ act_trans[act2_name] = PetriNet.Transition(act2_name, act2_name)
+ net.transitions.add(act_trans[act2_name])
+ who_is_entering[act2_name] = set()
+ who_is_exiting[act2_name] = set()
+
+ for index, sa_list in enumerate(heu_net.start_activities):
+ if act2_name in sa_list:
+ who_is_entering[act2_name].add((None, index))
+
+ for index, ea_list in enumerate(heu_net.end_activities):
+ if act2_name in ea_list:
+ who_is_exiting[act2_name].add((None, index))
+
+ who_is_entering[act2_name].add((act1_name, None))
+ who_is_exiting[act1_name].add((act2_name, None))
+
+ # -------------------------
+ # Build "entering" structure
+ # -------------------------
+ places_entering = {}
+
+ for act in who_is_entering:
+ places_entering[act] = {}
+
+ entering = list(who_is_entering[act])
+ entering_preds = sorted([x for x in entering if x[0] is not None], key=lambda x: x[0])
+ entering_sources = [x for x in entering if x[0] is None]
+
+ # FIX 3: master_place must exist also when there are multiple sources only (merged nets)
+ # Additionally, if there is at least one predecessor, we need a place before the activity transition.
+ master_place = None
+ if entering_preds or len(entering) > 1:
+ master_place = PetriNet.Place("pre_" + act)
+ net.places.add(master_place)
+ add_arc_from_to(master_place, act_trans[act], net)
+
+ # --- AND-joins (based on cliques) ---
+ # FIX 2: do NOT rely on `if pred in and_measures_in` because the structure is asymmetric.
+ cliques = find_bindings(heu_net.nodes[act].and_measures_in)
+ pred_names = [p[0] for p in entering_preds]
+ pred_names_set = set(pred_names)
+
+ and_members = set()
+ for clique in cliques:
+ clique = [n for n in clique if n in pred_names_set]
+ if len(clique) < 2:
+ continue
+ and_members.update(clique)
+
+ hid_trans_count += 1
+ hid_trans = PetriNet.Transition("hid_" + str(hid_trans_count), None)
+ net.transitions.add(hid_trans)
+
+ add_arc_from_to(hid_trans, master_place, net)
+
+ for pred in clique:
+ key = (pred, None)
+ if key not in places_entering[act]:
+ s_place = PetriNet.Place(f"splace_in_{act}_{pred}")
+ net.places.add(s_place)
+ places_entering[act][key] = s_place
+ add_arc_from_to(places_entering[act][key], hid_trans, net)
+
+ # --- Remaining predecessors (OR-join / simple sequence) ---
+ for pred_tuple in entering_preds:
+ pred_name = pred_tuple[0]
+ if pred_name in and_members:
+ continue
+
+ if len(entering) == 1:
+ # Single predecessor only: connect directly to the master place
+ places_entering[act][pred_tuple] = master_place
+ else:
+ # Multiple incoming alternatives: keep an explicit s_place + hid transition (as in original)
+ key = pred_tuple
+ if key not in places_entering[act]:
+ s_place = PetriNet.Place(f"splace_in_{act}_{pred_name}")
+ net.places.add(s_place)
+ places_entering[act][key] = s_place
+
+ hid_trans_count += 1
+ hid_trans = PetriNet.Transition("hid_" + str(hid_trans_count), None)
+ net.transitions.add(hid_trans)
+
+ add_arc_from_to(places_entering[act][key], hid_trans, net)
+ add_arc_from_to(hid_trans, master_place, net)
+
+ # --- Sources ---
+ for src_tuple in entering_sources:
+ src_idx = src_tuple[1]
+ if len(entering) == 1:
+ add_arc_from_to(source_places[src_idx], act_trans[act], net)
+ else:
+ hid_trans_count += 1
+ hid_trans = PetriNet.Transition("hid_" + str(hid_trans_count), None)
+ net.transitions.add(hid_trans)
+
+ add_arc_from_to(source_places[src_idx], hid_trans, net)
+ add_arc_from_to(hid_trans, master_place, net)
+
+ # ------------------------
+ # Build "exiting" structure
+ # ------------------------
+ for act in who_is_exiting:
+ exiting = list(who_is_exiting[act])
+ exiting_succs = sorted([x for x in exiting if x[0] is not None], key=lambda x: x[0])
+ exiting_sinks = [x for x in exiting if x[0] is None]
+
+ # Simple case: only one successor
+ if len(exiting) == 1 and exiting_succs:
+ succ = exiting_succs[0][0]
+ if (act, None) in places_entering.get(succ, {}):
+ add_arc_from_to(act_trans[act], places_entering[succ][(act, None)], net)
+ continue
+
+ # Simple case: only one sink
+ if len(exiting) == 1 and exiting_sinks:
+ sink_idx = exiting_sinks[0][1]
+ add_arc_from_to(act_trans[act], sink_places[sink_idx], net)
+ continue
+
+ # FIX 3: int_place must exist also when there are multiple sinks only (merged nets)
+ int_place = PetriNet.Place("intplace_" + str(act))
+ net.places.add(int_place)
+ add_arc_from_to(act_trans[act], int_place, net)
+
+ # AND-splits (based on cliques)
+ cliques = find_bindings(heu_net.nodes[act].and_measures_out)
+ succ_names = [x[0] for x in exiting_succs]
+ succ_names_set = set(succ_names)
+
+ and_members = set()
+ for clique in cliques:
+ clique = [n for n in clique if n in succ_names_set]
+ if len(clique) < 2:
+ continue
+ and_members.update(clique)
+
+ hid_trans_count += 1
+ hid_trans = PetriNet.Transition("hid_" + str(hid_trans_count), None)
+ net.transitions.add(hid_trans)
+
+ add_arc_from_to(int_place, hid_trans, net)
+
+ for succ in clique:
+ if (act, None) in places_entering.get(succ, {}):
+ add_arc_from_to(hid_trans, places_entering[succ][(act, None)], net)
+
+ # Remaining successors (OR-split)
+ for succ_tuple in exiting_succs:
+ succ = succ_tuple[0]
+ if succ in and_members:
+ continue
+ if (act, None) in places_entering.get(succ, {}):
+ hid_trans_count += 1
+ hid_trans = PetriNet.Transition("hid_" + str(hid_trans_count), None)
+ net.transitions.add(hid_trans)
+
+ add_arc_from_to(int_place, hid_trans, net)
+ add_arc_from_to(hid_trans, places_entering[succ][(act, None)], net)
+
+ # Sinks
+ for sink_tuple in exiting_sinks:
+ sink_idx = sink_tuple[1]
+
+ hid_trans_count += 1
+ hid_trans = PetriNet.Transition("hid_" + str(hid_trans_count), None)
+ net.transitions.add(hid_trans)
+
+ add_arc_from_to(int_place, hid_trans, net)
+ add_arc_from_to(hid_trans, sink_places[sink_idx], net)
+
+ # Cleanup + reductions
+ net = remove_rendundant_invisible_transitions(net)
+
+ from pm4py.objects.petri_net.utils import reduction
+ reduction.apply_simple_reduction(net)
+
+ return net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a6dbc709cf3a11990dfe4b8f0660a9898e9bea7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.log import variants, converter, constants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/constants.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..c55ca2d4c807138644a33ac995a2a1a820584577
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/constants.py
@@ -0,0 +1,32 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+TO_TRACE_LOG = "to_event_log"
+TO_EVENT_LOG = "to_event_log"
+TO_EVENT_STREAM = "to_event_stream"
+TO_DATAFRAME = "to_dataframe"
+FROM_DATAFRAME = "from_dataframe"
+
+DF_TO_EVENT_LOG_1V = "df_to_event_log_1v"
+DF_TO_EVENT_LOG_NV = "df_to_event_log_nv"
+
+DEEPCOPY = "deepcopy"
+STREAM_POSTPROCESSING = "stream_postprocessing"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..a20e271f012cb27a40cc4b05043e9c41835721ed
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/converter.py
@@ -0,0 +1,47 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.conversion.log.variants import (
+ to_event_stream,
+ to_event_log,
+ to_data_frame,
+ to_nx,
+)
+
+
+class Variants(Enum):
+ TO_EVENT_LOG = to_event_log
+ TO_EVENT_STREAM = to_event_stream
+ TO_DATA_FRAME = to_data_frame
+ TO_NX = to_nx
+
+
+TO_EVENT_LOG = Variants.TO_EVENT_LOG
+TO_EVENT_STREAM = Variants.TO_EVENT_STREAM
+TO_DATA_FRAME = Variants.TO_DATA_FRAME
+
+
+def apply(log, parameters=None, variant=None):
+ if variant is None:
+ variant = Variants.TO_EVENT_LOG
+ return variant.value.apply(log, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c643ea34c71a44a1ec6b19704b13aae50f7d2748
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/__init__.py
@@ -0,0 +1,29 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.log.variants import (
+ to_data_frame,
+ to_event_stream,
+ to_event_log,
+ df_to_event_log_1v,
+ df_to_event_log_nv,
+ to_nx,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/df_to_event_log_1v.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/df_to_event_log_1v.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1548d5a4842b4fa11eab0807ca1e9e4fc4765a6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/df_to_event_log_1v.py
@@ -0,0 +1,65 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.util import xes_constants as xes
+from pm4py.util import constants as pm4_constants
+
+
+def apply(df, parameters=None):
+ """
+ Convert a dataframe into a log containing 1 case per variant (only control-flow
+ perspective is considered)
+
+ Parameters
+ -------------
+ df
+ Dataframe
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ log
+ Event log
+ """
+ from pm4py.statistics.traces.generic.pandas import case_statistics
+
+ if parameters is None:
+ parameters = {}
+ variant_stats = case_statistics.get_variant_statistics(
+ df, parameters=parameters
+ )
+ activity_key = (
+ parameters[pm4_constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if pm4_constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+ log = EventLog()
+ for vd in variant_stats:
+ variant = vd["variant"]
+ trace = Trace()
+ for activity in variant:
+ event = Event()
+ event[activity_key] = activity
+ trace.append(event)
+ log.append(trace)
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/df_to_event_log_nv.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/df_to_event_log_nv.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c626432a161d9a5470f2c313152fc2c050fd982
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/df_to_event_log_nv.py
@@ -0,0 +1,88 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.util import xes_constants as xes
+from pm4py.util import constants as pm4_constants
+
+RETURN_VARIANTS = "return_variants"
+
+
+def apply(df, parameters=None):
+ """
+ Convert a dataframe into a log containing N case per variant (only control-flow
+ perspective is considered)
+
+ Parameters
+ -------------
+ df
+ Dataframe
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ log
+ Event log
+ """
+ from pm4py.statistics.traces.generic.pandas import case_statistics
+
+ if parameters is None:
+ parameters = {}
+
+ return_variants = (
+ parameters[RETURN_VARIANTS] if RETURN_VARIANTS in parameters else False
+ )
+
+ case_glue = (
+ parameters[pm4_constants.PARAMETER_CONSTANT_CASEID_KEY]
+ if pm4_constants.PARAMETER_CONSTANT_CASEID_KEY in parameters
+ else pm4_constants.CASE_CONCEPT_NAME
+ )
+ activity_key = (
+ parameters[pm4_constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if pm4_constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+
+ variant_stats = case_statistics.get_variant_statistics(
+ df, parameters=parameters
+ )
+
+ log = EventLog()
+ all_variants_log = {}
+ for vd in variant_stats:
+ variant = vd["variant"]
+ variant_count = vd[case_glue]
+ trace = Trace()
+ for activity in variant:
+ event = Event()
+ event[activity_key] = activity
+ trace.append(event)
+ all_variants_log[vd["variant"]] = []
+ for i in range(variant_count):
+ log.append(trace)
+ all_variants_log[vd["variant"]].append(len(log) - 1)
+
+ if return_variants:
+ return log, all_variants_log
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_data_frame.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_data_frame.py
new file mode 100644
index 0000000000000000000000000000000000000000..23e3e4af90dfbf67c7bfbbfa35f2daf3fd9771ef
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_data_frame.py
@@ -0,0 +1,84 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.conversion.log.variants import to_event_stream
+from pm4py.objects.log import obj as log_instance
+from pm4py.objects.conversion.log import constants
+from copy import copy
+from pm4py.util import constants as pm4_constants
+from pm4py.util import pandas_utils, exec_utils
+import pandas as pd
+import importlib.util
+
+
+class Parameters(Enum):
+ DEEP_COPY = constants.DEEPCOPY
+ STREAM_POST_PROCESSING = constants.STREAM_POSTPROCESSING
+ CASE_ATTRIBUTE_PREFIX = "case_attribute_prefix"
+ RETURN_PL_LAZYFRAME = "return_pl_lazyframe"
+
+
+def apply(log, parameters=None):
+ """
+ Converts a provided event log object into a Pandas dataframe. As a basis, an EventStream object is used.
+ In case an EventLog object is given, it is first converted to an EventStream object.
+ Within the conversion, the order is not changed, i.e., the order imposed by the iterator is used.
+
+ Parameters
+ -----------
+
+ log :class:`pm4py.log.log.EventLog`
+ Event log object, can either be an EventLog object, EventStream Object or Pandas dataframe
+
+ parameters :class:`dict`
+ Parameters of the algorithm (currently, this converter is parameter free)
+
+ Returns
+ -----------
+ df
+ Pandas dataframe
+ """
+ if parameters is None:
+ parameters = dict()
+ if pandas_utils.check_is_pandas_dataframe(log):
+ return log
+
+ return_pl_lazyframe = exec_utils.get_param_value(Parameters.RETURN_PL_LAZYFRAME, parameters, False)
+
+ if type(log) is log_instance.EventLog:
+ new_parameters = copy(parameters)
+ new_parameters["deepcopy"] = False
+ log = to_event_stream.apply(log, parameters=new_parameters)
+
+ transf_log = [dict(x) for x in log]
+
+ if return_pl_lazyframe:
+ import polars as pl
+ df = pl.DataFrame(transf_log).lazy()
+ else:
+ df = pandas_utils.instantiate_dataframe(transf_log)
+ df.attrs = copy(log.properties)
+ if pm4_constants.PARAMETER_CONSTANT_CASEID_KEY in df.attrs:
+ del df.attrs[pm4_constants.PARAMETER_CONSTANT_CASEID_KEY]
+
+ return df
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_event_log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_event_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..98ee17e85d84292fade4ae466ea219530b6b1024
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_event_log.py
@@ -0,0 +1,135 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from copy import copy
+from copy import deepcopy
+from enum import Enum
+
+from pm4py.objects.conversion.log import constants
+from pm4py.objects.conversion.log.variants import to_event_stream
+from pm4py.objects.log import obj as log_instance
+from pm4py.util import xes_constants as xes
+from pm4py.util import exec_utils, constants as pmconstants, pandas_utils
+import pandas as pd
+
+
+class Parameters(Enum):
+ DEEP_COPY = constants.DEEPCOPY
+ STREAM_POST_PROCESSING = constants.STREAM_POSTPROCESSING
+ CASE_ATTRIBUTE_PREFIX = "case_attribute_prefix"
+ CASE_ID_KEY = pmconstants.PARAMETER_CONSTANT_CASEID_KEY
+
+
+def apply(log, parameters=None):
+ if parameters is None:
+ parameters = {}
+
+ if type(log) is log_instance.Trace or type(log) is log_instance.EventLog:
+ return log
+
+ enable_deepcopy = exec_utils.get_param_value(
+ Parameters.DEEP_COPY, parameters, False
+ )
+ glue = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, pmconstants.CASE_CONCEPT_NAME
+ )
+ case_pref = exec_utils.get_param_value(
+ Parameters.CASE_ATTRIBUTE_PREFIX, parameters, "case:"
+ )
+
+ if pandas_utils.check_is_pandas_dataframe(log):
+ log = to_event_stream.apply(log, parameters=parameters)
+
+ if isinstance(log, log_instance.EventStream) and (
+ not isinstance(log, log_instance.EventLog)
+ ):
+ return __transform_event_stream_to_event_log(
+ log,
+ case_glue=glue,
+ include_case_attributes=True,
+ case_attribute_prefix=case_pref,
+ enable_deepcopy=enable_deepcopy,
+ )
+
+ return log
+
+
+def __transform_event_stream_to_event_log(
+ log,
+ case_glue=Parameters.CASE_ID_KEY.value,
+ include_case_attributes=True,
+ case_attribute_prefix=Parameters.CASE_ATTRIBUTE_PREFIX.value,
+ enable_deepcopy=False,
+):
+ """
+ Converts the event stream to an event log
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ An event stream
+ case_glue:
+ Case identifier. Default is 'case:concept:name'
+ include_case_attributes:
+ Default is True
+ case_attribute_prefix:
+ Default is 'case:'
+ enable_deepcopy
+ Enables deepcopy (avoid references between input and output objects)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ An event log
+ """
+ if enable_deepcopy:
+ log = deepcopy(log)
+
+ traces = {}
+ for orig_event in log:
+ event = copy(orig_event)
+ glue = event[case_glue]
+ if glue not in traces:
+ trace_attr = {}
+ if include_case_attributes:
+ for k in event.keys():
+ if k.startswith(case_attribute_prefix):
+ trace_attr[k.replace(case_attribute_prefix, "")] = (
+ event[k]
+ )
+ if xes.DEFAULT_TRACEID_KEY not in trace_attr:
+ trace_attr[xes.DEFAULT_TRACEID_KEY] = glue
+ traces[glue] = log_instance.Trace(attributes=trace_attr)
+
+ if include_case_attributes:
+ for k in list(event.keys()):
+ if k.startswith(case_attribute_prefix):
+ del event[k]
+
+ traces[glue].append(event)
+ return log_instance.EventLog(
+ traces.values(),
+ attributes=log.attributes,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ extensions=log.extensions,
+ properties=log.properties,
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_event_stream.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_event_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..d23e19be88e46bf2ea2750e1aa0a1ed2caac5930
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_event_stream.py
@@ -0,0 +1,337 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import math
+from copy import deepcopy, copy
+from enum import Enum
+
+import pandas as pd
+
+from pm4py.objects.conversion.log import constants
+from pm4py.objects.log import obj as log_instance
+from pm4py.objects.log.obj import EventLog, Event, XESExtension
+from pm4py.util import constants as pmutil
+from pm4py.util import exec_utils, pandas_utils, xes_constants
+import pandas
+import math
+
+
+class Parameters(Enum):
+ DEEP_COPY = constants.DEEPCOPY
+ STREAM_POST_PROCESSING = constants.STREAM_POSTPROCESSING
+ CASE_ATTRIBUTE_PREFIX = "case_attribute_prefix"
+ INCLUDE_CASE_ATTRIBUTES = "include_case_attributes"
+ COMPRESS = "compress"
+ EXTENSIONS = "extensions"
+
+
+def __postprocess_stream(list_events):
+ """
+ Postprocess the list of events of the stream in order to make sure
+ that there are no NaN/NaT values
+
+ Parameters
+ -------------
+ list_events
+ List of events
+
+ Returns
+ -------------
+ list_events
+ Postprocessed stream
+ """
+ NaTType = pandas._libs.tslibs.nattype.NaTType
+
+ for event in list_events:
+ keys_to_delete = [
+ k for k, v in event.items()
+ if type(v) is NaTType or
+ ((type(v) is float or type(v) is int) and math.isnan(v)) or
+ v is None
+ ]
+
+ for k in keys_to_delete:
+ del event[k]
+
+ return list_events
+
+
+def __compress(list_events):
+ """
+ Compress a list of events,
+ using one instantiation for the same key/value.
+
+ Parameters
+ --------------
+ list_events
+ List of events of the stream
+
+ Returns
+ --------------
+ :param list_events:
+ :return:
+ """
+ compress_dict = {}
+ i = 0
+ while i < len(list_events):
+ # create a new event where keys and values are compressed
+ comp_ev = {}
+ for k, v in list_events[i].items():
+ # check if the key has already been instantiated.
+ # in that case, use the current instantiation.
+ if k not in compress_dict:
+ compress_dict[k] = k
+ else:
+ k = compress_dict[k]
+ # check if the value has already been instantiated.
+ # in that case, use the current instantiation
+ if v not in compress_dict:
+ compress_dict[v] = v
+ else:
+ v = compress_dict[v]
+ # saves the compressed keys and values in the dictionary
+ comp_ev[k] = v
+ list_events[i] = comp_ev
+ i = i + 1
+ return list_events
+
+
+def apply(log, parameters=None):
+ """
+ Converts the event log to an event stream
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ An Event log
+ include_case_attributes:
+ Default is True
+ case_attribute_prefix:
+ Default is 'case:'
+ enable_deepcopy
+ Enables deepcopy (avoid references between input and output objects)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ An Event stream
+ """
+ if parameters is None:
+ parameters = {}
+
+ stream_post_processing = exec_utils.get_param_value(
+ Parameters.STREAM_POST_PROCESSING, parameters, False
+ )
+ case_pref = exec_utils.get_param_value(
+ Parameters.CASE_ATTRIBUTE_PREFIX, parameters, "case:"
+ )
+ enable_deepcopy = exec_utils.get_param_value(
+ Parameters.DEEP_COPY, parameters, True
+ )
+ include_case_attributes = exec_utils.get_param_value(
+ Parameters.INCLUDE_CASE_ATTRIBUTES, parameters, True
+ )
+ compress = exec_utils.get_param_value(
+ Parameters.COMPRESS, parameters, False
+ )
+ extensions = exec_utils.get_param_value(
+ Parameters.EXTENSIONS, parameters, None
+ )
+
+ if pandas_utils.check_is_pandas_dataframe(log):
+ return __transform_dataframe_to_event_stream(
+ log,
+ stream_post_processing=stream_post_processing,
+ compress=compress,
+ extensions=extensions,
+ )
+
+ if isinstance(log, EventLog):
+ return __transform_event_log_to_event_stream(
+ log,
+ include_case_attributes=include_case_attributes,
+ case_attribute_prefix=case_pref,
+ enable_deepcopy=enable_deepcopy,
+ )
+
+ return log
+
+
+def __detect_extensions(df):
+ extensions = set()
+ if isinstance(df, pd.DataFrame):
+ for col in df.columns:
+ for single_key in col.split(":"):
+ for ext in XESExtension:
+ if single_key == ext.prefix:
+ extensions.add(ext)
+ return extensions
+
+
+def __transform_dataframe_to_event_stream(
+ dataframe, stream_post_processing=False, compress=True, extensions=None
+):
+ """
+ Transforms a dataframe to an event stream
+
+ Parameters
+ ------------------
+ dataframe
+ Pandas dataframe
+ stream_post_processing
+ Boolean value that enables the post processing to remove NaN / NaT values
+ compress
+ Compresses the stream in order to reduce the memory utilization after the conversion
+ extensions
+ Provided extensions (to be included in the log)
+
+ Returns
+ ------------------
+ stream
+ Event stream
+ """
+ if extensions is None:
+ extensions = __detect_extensions(dataframe)
+ list_events = pandas_utils.to_dict_records(dataframe)
+ if stream_post_processing:
+ list_events = __postprocess_stream(list_events)
+ if compress:
+ list_events = __compress(list_events)
+ for i in range(len(list_events)):
+ list_events[i] = Event(list_events[i])
+ if hasattr(dataframe, "attrs"):
+ properties = copy(dataframe.attrs)
+ if pmutil.PARAMETER_CONSTANT_CASEID_KEY in properties:
+ del properties[pmutil.PARAMETER_CONSTANT_CASEID_KEY]
+ else:
+ properties = {}
+ stream = log_instance.EventStream(
+ list_events, attributes={"origin": "csv"}, properties=properties
+ )
+ for ex in extensions:
+ stream.extensions[ex.name] = {
+ xes_constants.KEY_PREFIX: ex.prefix,
+ xes_constants.KEY_URI: ex.uri,
+ }
+ return stream
+
+
+def __transform_dataframe_to_event_stream_new(
+ dataframe, stream_post_processing=False, compress=False, extensions=None
+):
+ """
+ Transforms a dataframe to an event stream
+
+ Parameters
+ ------------------
+ dataframe
+ Pandas dataframe
+ stream_post_processing
+ Boolean value that enables the post processing to remove NaN / NaT values
+ compress
+ Compresses the stream in order to reduce the memory utilization after the conversion
+ extensions
+ Provided extensions (to be included in the log)
+
+ Returns
+ ------------------
+ stream
+ Event stream
+ """
+ if extensions is None:
+ extensions = __detect_extensions(dataframe)
+ columns_names = list(dataframe.columns)
+ columns_corr = []
+ for c in columns_names:
+ columns_corr.append(dataframe[c].to_numpy())
+ length = columns_corr[-1].size
+ list_events = []
+ for i in range(length):
+ eve = {}
+ for j in range(len(columns_names)):
+ eve[columns_names[j]] = columns_corr[j][i]
+ list_events.append(eve)
+ if stream_post_processing:
+ list_events = __postprocess_stream(list_events)
+ if compress:
+ list_events = __compress(list_events)
+ for i in range(len(list_events)):
+ list_events[i] = Event(list_events[i])
+ if hasattr(dataframe, "attrs"):
+ properties = copy(dataframe.attrs)
+ if pmutil.PARAMETER_CONSTANT_CASEID_KEY in properties:
+ del properties[pmutil.PARAMETER_CONSTANT_CASEID_KEY]
+ else:
+ properties = {}
+ stream = log_instance.EventStream(
+ list_events, attributes={"origin": "csv"}, properties=properties
+ )
+ for ex in extensions:
+ stream.extensions[ex.name] = {
+ xes_constants.KEY_PREFIX: ex.prefix,
+ xes_constants.KEY_URI: ex.uri,
+ }
+ return stream
+
+
+def __transform_event_log_to_event_stream(
+ log,
+ include_case_attributes=True,
+ case_attribute_prefix=pmutil.CASE_ATTRIBUTE_PREFIX,
+ enable_deepcopy=False,
+):
+ """
+ Converts the event log to an event stream
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ An Event log
+ include_case_attributes:
+ Default is True
+ case_attribute_prefix:
+ Default is 'case:'
+ enable_deepcopy
+ Enables deepcopy (avoid references between input and output objects)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ An Event stream
+ """
+ event_stream = log_instance.EventStream(
+ [],
+ attributes=log.attributes,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ extensions=log.extensions,
+ properties=log.properties,
+ )
+ for index, trace in enumerate(log):
+ for event in trace:
+ new_event = deepcopy(event) if enable_deepcopy else event
+ if include_case_attributes:
+ for key, value in trace.attributes.items():
+ new_event[case_attribute_prefix + key] = value
+ else:
+ new_event[pmutil.CASE_ATTRIBUTE_GLUE] = str(index)
+ event_stream.append(new_event)
+ return event_stream
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_nx.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_nx.py
new file mode 100644
index 0000000000000000000000000000000000000000..9742554d6b4a0bc76c6cd4a7ff493b0c735b286d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/log/variants/to_nx.py
@@ -0,0 +1,156 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from enum import Enum
+from pm4py.objects.log.obj import EventLog, EventStream
+import pandas as pd
+from typing import Optional, Dict, Any, Union
+from pm4py.util import exec_utils, nx_utils
+from pm4py.objects.conversion.log.variants import to_event_log
+
+
+class Parameters(Enum):
+ INCLUDE_DF = "include_df"
+ CASE_ID_ATTRIBUTE = "case_id_attribute"
+ OTHER_CASE_ATTRIBUTES_AS_NODES = "other_case_attributes_as_nodes"
+ EVENT_ATTRIBUTES_AS_NODES = "event_attributes_as_nodes"
+
+
+def apply(
+ log_obj: Union[EventLog, EventStream, pd.DataFrame],
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Converts an event log object to a NetworkX DiGraph object.
+ The nodes of the graph are the events, the cases (and possibly the attributes of the log).
+ The edges are:
+ - Connecting each event to the corresponding case (BELONGS_TO type)
+ - Connecting every event to the directly-following one (DF type, if enabled)
+ - Connecting every case/event to the given attribute values (ATTRIBUTE_EDGE type)
+
+ Parameters
+ ----------------
+ log_obj
+ Log object (EventLog, EventStream, Pandas dataframe)
+ parameters
+ Parameters of the conversion, including:
+ - Parameters.INCLUDE_DF => include the directly-follows graph relation in the graph
+ - Parameters.CASE_ID_ATTRIBUTE => specify which attribute at the case level should be considered the case ID
+ - Parameters.OTHER_CASE_ATTRIBUTES_AS_NODES => specify which attributes at the case level should be inserted in the graph as nodes (other than the caseID) (list, default empty)
+ - Parameters.EVENT_ATTRIBUTES_AS_NODES => specify which attributes at the event level should be inserted in the graph as nodes (list, default empty)
+
+ Returns
+ ----------------
+ nx_digraph
+ NetworkX DiGraph object
+ """
+ if parameters is None:
+ parameters = {}
+
+ include_df = exec_utils.get_param_value(
+ Parameters.INCLUDE_DF, parameters, True
+ )
+ case_id_attribute = exec_utils.get_param_value(
+ Parameters.CASE_ID_ATTRIBUTE, parameters, "concept:name"
+ )
+ other_case_attributes_as_nodes = exec_utils.get_param_value(
+ Parameters.OTHER_CASE_ATTRIBUTES_AS_NODES, parameters, None
+ )
+ event_attributes_as_nodes = exec_utils.get_param_value(
+ Parameters.EVENT_ATTRIBUTES_AS_NODES, parameters, None
+ )
+
+ parameters["stream_postprocessing"] = True
+ log_obj = to_event_log.apply(log_obj, parameters=parameters)
+
+ if event_attributes_as_nodes is None:
+ event_attributes_as_nodes = []
+ if other_case_attributes_as_nodes is None:
+ other_case_attributes_as_nodes = []
+
+ nx_digraph = nx_utils.DiGraph()
+
+ for case in log_obj:
+ case_id = "CASE=" + str(case.attributes[case_id_attribute])
+ dct_case = {"type": "CASE"}
+ for att in case.attributes:
+ dct_case[att] = case.attributes[att]
+ nx_digraph.add_node(case_id, attr=dct_case)
+
+ for index, event in enumerate(case):
+ dct_ev = {"type": "EVENT"}
+ for att in event:
+ dct_ev[att] = event[att]
+
+ ev_id = (
+ "EVENT="
+ + str(case.attributes[case_id_attribute])
+ + "_"
+ + str(index)
+ )
+ nx_digraph.add_node(ev_id, attr=dct_ev)
+ nx_digraph.add_edge(ev_id, case_id, attr={"type": "BELONGS_TO"})
+
+ for ev_att in event_attributes_as_nodes:
+ if ev_att in event:
+ node_id = event[ev_att]
+ if node_id not in nx_digraph.nodes:
+ nx_digraph.add_node(
+ node_id, attr={"type": "ATTRIBUTE_NODE"}
+ )
+ nx_digraph.add_edge(
+ ev_id,
+ node_id,
+ attr={"type": "ATTRIBUTE_EDGE", "name": ev_att},
+ )
+
+ if include_df:
+ for index in range(len(case) - 1):
+ curr_ev = (
+ "EVENT="
+ + str(case.attributes[case_id_attribute])
+ + "_"
+ + str(index)
+ )
+ next_ev = (
+ "EVENT="
+ + str(case.attributes[case_id_attribute])
+ + "_"
+ + str(index + 1)
+ )
+
+ nx_digraph.add_edge(curr_ev, next_ev, attr={"type": "DF"})
+
+ for case_att in other_case_attributes_as_nodes:
+ if case_att in case.attributes:
+ node_id = case.attributes[case_att]
+ if node_id not in nx_digraph.nodes:
+ nx_digraph.add_node(
+ node_id, attr={"type": "ATTRIBUTE_NODE"}
+ )
+ nx_digraph.add_edge(
+ case_id,
+ node_id,
+ attr={"type": "ATTRIBUTE_EDGE", "name": case_att},
+ )
+
+ return nx_digraph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc7303b3a00545a69ea810a4c361c364b7d269ff
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.ocel import converter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..39911692c9fc2823846db4d9e3ff3e8da1124ec3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/converter.py
@@ -0,0 +1,60 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from enum import Enum
+from pm4py.util import exec_utils
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.objects.conversion.ocel.variants import (
+ ocel_to_nx,
+ ocel_features_to_nx,
+)
+
+
+class Variants(Enum):
+ OCEL_TO_NX = ocel_to_nx
+ OCEL_FEATURES_TO_NX = ocel_features_to_nx
+
+
+def apply(
+ ocel: OCEL,
+ variant=Variants.OCEL_TO_NX,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Converts an OCEL to another object.
+
+ Parameters
+ -------------
+ ocel
+ Object-centric event log
+ variant
+ Variant of the algorithm to use, posible values:
+ - Variants.OCEL_TO_NX: graph containing event and object IDS and two type of relations (REL=related objects, DF=directly-follows)
+ - Variants.OCEL_FEATURES_TO_NX: graph containing different types of interconnection at the object level
+ parameters
+ Variant-specific parameters
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).apply(ocel, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6affbd03d8b09f273f87041b9b87660586142cfe
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.ocel.variants import (
+ ocel_to_nx,
+ ocel_features_to_nx,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/ocel_features_to_nx.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/ocel_features_to_nx.py
new file mode 100644
index 0000000000000000000000000000000000000000..9391872fc6fa063da115831e95c3254f83007215
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/ocel_features_to_nx.py
@@ -0,0 +1,111 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from enum import Enum
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.util import exec_utils, nx_utils
+from pm4py.algo.transformation.ocel.graphs import (
+ object_interaction_graph,
+ object_descendants_graph,
+ object_inheritance_graph,
+ object_cobirth_graph,
+ object_codeath_graph,
+)
+
+
+class Parameters(Enum):
+ INCLUDE_OBJ_INTERACTION_GRAPH = "include_obj_interaction_graph"
+ INCLUDE_OBJ_DESCENDANTS_GRAPH = "include_obj_descendants_graph"
+ INCLUDE_OBJ_INHERITANCE_GRAPH = "include_obj_inheritance_graph"
+ INCLUDE_OBJ_COBIRTH_GRAPH = "include_obj_cobirth_graph"
+ INCLUDE_OBJ_CODEATH_GRAPH = "include_obj_codeath_graph"
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Converts the graphs of features extracted from an OCEL to a NetworkX DiGraph object
+
+ Parameters
+ --------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.INCLUDE_OBJ_INTERACTION_GRAPH => includes the object interaction graph in the NX DiGraph
+ - Parameters.INCLUDE_OBJ_DESCENDANTS_GRAPH => includes the object descendants graph in the NX DiGraph
+ - Parameters.INCLUDE_OBJ_INHERITANCE_GRAPH => includes the object inheritance graph in the NX DiGraph
+ - Parameters.INCLUDE_OBJ_COBIRTH_GRAPH => includes the object cobirth graph in the NX DiGraph
+ - Parameters.INCLUDE_OBJ_CODEATH_GRAPH => includes the object codeath graph in the NX DiGraph
+
+ Returns
+ -------------
+ G
+ NetworkX DiGraph
+ """
+ if parameters is None:
+ parameters = {}
+
+ include_obj_interaction_graph = exec_utils.get_param_value(
+ Parameters.INCLUDE_OBJ_INTERACTION_GRAPH, parameters, True
+ )
+ include_obj_descendants_graph = exec_utils.get_param_value(
+ Parameters.INCLUDE_OBJ_DESCENDANTS_GRAPH, parameters, True
+ )
+ include_obj_inheritance_graph = exec_utils.get_param_value(
+ Parameters.INCLUDE_OBJ_INHERITANCE_GRAPH, parameters, True
+ )
+ include_obj_cobirth_graph = exec_utils.get_param_value(
+ Parameters.INCLUDE_OBJ_COBIRTH_GRAPH, parameters, True
+ )
+ include_obj_codeath_graph = exec_utils.get_param_value(
+ Parameters.INCLUDE_OBJ_CODEATH_GRAPH, parameters, True
+ )
+
+ G = nx_utils.DiGraph()
+ if include_obj_interaction_graph:
+ interaction_graph = object_interaction_graph.apply(
+ ocel, parameters=parameters
+ )
+ G.add_edges_from(interaction_graph, attr={"type": "INTERACTION"})
+
+ if include_obj_descendants_graph:
+ descendants_graph = object_descendants_graph.apply(
+ ocel, parameters=parameters
+ )
+ G.add_edges_from(descendants_graph, attr={"type": "DESCENDANTS"})
+
+ if include_obj_inheritance_graph:
+ inheritance_graph = object_inheritance_graph.apply(
+ ocel, parameters=parameters
+ )
+ G.add_edges_from(inheritance_graph, attr={"type": "INHERITANCE"})
+
+ if include_obj_cobirth_graph:
+ cobirth_graph = object_cobirth_graph.apply(ocel, parameters=parameters)
+ G.add_edges_from(cobirth_graph, attr={"type": "COBIRTH"})
+
+ if include_obj_codeath_graph:
+ codeath_graph = object_codeath_graph.apply(ocel, parameters=parameters)
+ G.add_edges_from(codeath_graph, attr={"type": "CODEATH"})
+
+ return G
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/ocel_to_nx.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/ocel_to_nx.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4f9b5501a43aea1a8903136c58f5cdd8191ddba
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/ocel/variants/ocel_to_nx.py
@@ -0,0 +1,135 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from enum import Enum
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.util import exec_utils, nx_utils
+from pm4py.objects.conversion.log.variants import to_event_stream
+from copy import copy
+
+
+class Parameters(Enum):
+ INCLUDE_DF = "include_df"
+ INCLUDE_OBJECT_CHANGES = "include_object_changes"
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Converts an OCEL to a NetworkX MultiDiGraph object.
+ The nodes are the events and objects of the OCEL.
+ The edges are of two different types:
+ - relation edges, connecting an event to its related objects
+ - directly-follows edges, connecting an event to a following event (in the lifecycle of one of the related objects)
+
+ Parameters
+ ---------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.INCLUDE_DF => include the directly-follows relationship
+
+ Returns
+ ---------------
+ G
+ NetworkX MultiDiGraph
+ """
+ if parameters is None:
+ parameters = {}
+
+ include_df = exec_utils.get_param_value(
+ Parameters.INCLUDE_DF, parameters, True
+ )
+ include_object_changes = exec_utils.get_param_value(
+ Parameters.INCLUDE_OBJECT_CHANGES, parameters, True
+ )
+
+ G = nx_utils.MultiDiGraph()
+
+ stream = ocel.events.to_dict(orient="records")
+ stream = to_event_stream.__postprocess_stream(stream)
+ for ev in stream:
+ ev["type"] = "EVENT"
+ G.add_node(ev[ocel.event_id_column], attr=ev)
+
+ stream = ocel.objects.to_dict(orient="records")
+ stream = to_event_stream.__postprocess_stream(stream)
+ for obj in stream:
+ obj["type"] = "OBJECT"
+ G.add_node(obj[ocel.object_id_column], attr=obj)
+
+ rel_cols = {ocel.event_id_column, ocel.object_id_column, ocel.qualifier}
+
+ relations = ocel.relations[list(rel_cols)]
+ stream = relations.to_dict(orient="records")
+ for rel in stream:
+ qualifier = rel[ocel.qualifier]
+ if qualifier is None:
+ qualifier = ""
+ G.add_edge(
+ rel[ocel.event_id_column],
+ rel[ocel.object_id_column],
+ attr={"type": "E2O", "qualifier": qualifier},
+ )
+
+ obj_relations = ocel.o2o[
+ [ocel.object_id_column, ocel.object_id_column + "_2", ocel.qualifier]
+ ]
+ stream = obj_relations.to_dict(orient="records")
+ for rel in stream:
+ qualifier = rel[ocel.qualifier]
+ if qualifier is None:
+ qualifier = ""
+ G.add_edge(
+ rel[ocel.object_id_column],
+ rel[ocel.object_id_column + "_2"],
+ attr={"type": "O2O", "qualifier": qualifier},
+ )
+
+ if include_df:
+ lifecycle = (
+ relations.groupby(ocel.object_id_column)
+ .agg(list)
+ .to_dict()[ocel.event_id_column]
+ )
+ for obj in lifecycle:
+ lif = lifecycle[obj]
+ for i in range(len(lif) - 1):
+ G.add_edge(
+ lif[i], lif[i + 1], attr={"type": "DF", "object": obj}
+ )
+
+ if include_object_changes:
+ object_changes = ocel.object_changes.to_dict(orient="records")
+ for i in range(len(object_changes)):
+ change_id = "@@change##%d" % i
+ change_dict = copy(object_changes[i])
+ change_dict["type"] = "CHANGE"
+ G.add_node(change_id, attr=change_dict)
+ G.add_edge(
+ change_id,
+ object_changes[i][ocel.object_id_column],
+ attr={"type": "CHANGE"},
+ )
+
+ return G
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8c8ca52a4b68ee9e6c1978d4b66efd8f88fa8c1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.powl import *
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..e37522a0b229bacad3d64e90f32335c7e9c606e0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/converter.py
@@ -0,0 +1,55 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.conversion.powl.variants import to_petri_net
+from pm4py.util import exec_utils
+from enum import Enum
+
+
+class Variants(Enum):
+ TO_PETRI_NET = to_petri_net
+
+
+def apply(powl, parameters=None, variant=Variants.TO_PETRI_NET):
+ """
+ Method for converting from POWL to Petri net
+
+ Parameters
+ -----------
+ powl
+ POWL model
+ parameters
+ Parameters of the algorithm
+ variant
+ Chosen variant of the algorithm:
+ - Variants.TO_PETRI_NET
+
+ Returns
+ -----------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ final_marking
+ Final marking
+ """
+ return exec_utils.get_variant(variant).apply(powl, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bc48d18dfa3f82f154a8b0f451ff45d572d2bb5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/__init__.py
@@ -0,0 +1,23 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.conversion.powl.variants import *
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/to_petri_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/to_petri_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..827b9d57145014aa64b249ccf8efef75a438f7dc
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/to_petri_net.py
@@ -0,0 +1,317 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import time
+import uuid
+from itertools import product
+
+import pm4py.objects.conversion.process_tree.variants.to_petri_net as pt_to_pn
+from pm4py.objects.petri_net.obj import Marking
+from pm4py.objects.petri_net.obj import PetriNet
+from pm4py.objects.petri_net.utils.petri_utils import (
+ add_arc_from_to,
+ remove_place,
+)
+from pm4py.objects.powl.obj import (
+ Transition,
+ SilentTransition,
+ StrictPartialOrder,
+ OperatorPOWL,
+ FrequentTransition,
+)
+from pm4py.objects.petri_net.utils import reduction
+from pm4py.objects.process_tree.obj import Operator
+
+
+def recursively_add_tree(
+ powl,
+ net,
+ initial_entity_subtree,
+ final_entity_subtree,
+ counts,
+ rec_depth,
+ force_add_skip=False,
+):
+ """
+ Recursively add the submodels to the Petri net
+
+ Parameters
+ -----------
+ powl
+ POWL model
+ net
+ Petri net
+ initial_entity_subtree
+ Initial entity (place/transition) that should be attached from the subtree
+ final_entity_subtree
+ Final entity (place/transition) that should be attached from the subtree
+ counts
+ Counts object (keeps the number of places, transitions and hidden transitions)
+ rec_depth
+ Recursion depth of the current iteration
+ force_add_skip
+ Boolean value that tells if the addition of a skip is mandatory
+
+ Returns
+ ----------
+ net
+ Updated Petri net
+ counts
+ Updated counts object (keeps the number of places, transitions and hidden transitions)
+ final_place
+ Last place added in this recursion
+ """
+ if type(initial_entity_subtree) is PetriNet.Transition:
+ initial_place = get_new_place(counts)
+ net.places.add(initial_place)
+ add_arc_from_to(initial_entity_subtree, initial_place, net)
+ else:
+ initial_place = initial_entity_subtree
+ if (
+ final_entity_subtree is not None
+ and type(final_entity_subtree) is PetriNet.Place
+ ):
+ final_place = final_entity_subtree
+ else:
+ final_place = get_new_place(counts)
+ net.places.add(final_place)
+ if (
+ final_entity_subtree is not None
+ and type(final_entity_subtree) is PetriNet.Transition
+ ):
+ add_arc_from_to(final_place, final_entity_subtree, net)
+
+ if force_add_skip:
+ invisible = get_new_hidden_trans(counts, type_trans="skip")
+ add_arc_from_to(initial_place, invisible, net)
+ add_arc_from_to(invisible, final_place, net)
+
+ if isinstance(powl, Transition):
+ if isinstance(powl, SilentTransition):
+ petri_trans = get_new_hidden_trans(counts, type_trans="skip")
+ elif isinstance(powl, FrequentTransition):
+ petri_trans = get_transition(
+ counts,
+ powl.label,
+ powl.activity,
+ powl.skippable,
+ powl.selfloop,
+ )
+ else:
+ petri_trans = get_transition(counts, powl.label, powl.label)
+ net.transitions.add(petri_trans)
+ add_arc_from_to(initial_place, petri_trans, net)
+ add_arc_from_to(petri_trans, final_place, net)
+
+ elif isinstance(powl, OperatorPOWL):
+ tree_children = powl.children
+ if powl.operator == Operator.XOR:
+ for subtree in tree_children:
+ net, counts, intermediate_place = recursively_add_tree(
+ subtree,
+ net,
+ initial_place,
+ final_place,
+ counts,
+ rec_depth + 1,
+ )
+ elif powl.operator == Operator.LOOP:
+ new_initial_place = get_new_place(counts)
+ net.places.add(new_initial_place)
+ init_loop_trans = get_new_hidden_trans(
+ counts, type_trans="init_loop"
+ )
+ net.transitions.add(init_loop_trans)
+ add_arc_from_to(initial_place, init_loop_trans, net)
+ add_arc_from_to(init_loop_trans, new_initial_place, net)
+ initial_place = new_initial_place
+ loop_trans = get_new_hidden_trans(counts, type_trans="loop")
+ net.transitions.add(loop_trans)
+
+ exit_node = SilentTransition()
+ do = tree_children[0]
+ redo = tree_children[1]
+
+ net, counts, int1 = recursively_add_tree(
+ do, net, initial_place, None, counts, rec_depth + 1
+ )
+ net, counts, int2 = recursively_add_tree(
+ redo, net, int1, None, counts, rec_depth + 1
+ )
+ net, counts, int3 = recursively_add_tree(
+ exit_node, net, int1, final_place, counts, rec_depth + 1
+ )
+
+ looping_place = int2
+
+ add_arc_from_to(looping_place, loop_trans, net)
+ add_arc_from_to(loop_trans, initial_place, net)
+
+ elif isinstance(powl, StrictPartialOrder):
+ transitive_reduction = powl.order.get_transitive_reduction()
+ tree_children = list(powl.children)
+ tau_split = get_new_hidden_trans(counts, type_trans="tauSplit")
+ net.transitions.add(tau_split)
+ add_arc_from_to(initial_place, tau_split, net)
+ tau_join = get_new_hidden_trans(counts, type_trans="tauJoin")
+ net.transitions.add(tau_join)
+ add_arc_from_to(tau_join, final_place, net)
+
+ init_trans = []
+ final_trans = []
+ start_nodes = transitive_reduction.get_start_nodes()
+ end_nodes = transitive_reduction.get_end_nodes()
+ for subtree in tree_children:
+ i_trans = get_new_hidden_trans(counts, type_trans="init_par")
+ net.transitions.add(i_trans)
+ if subtree in start_nodes:
+ i_place = get_new_place(counts)
+ net.places.add(i_place)
+ add_arc_from_to(tau_split, i_place, net)
+
+ add_arc_from_to(i_place, i_trans, net)
+
+ f_trans = get_new_hidden_trans(counts, type_trans="final_par")
+ net.transitions.add(f_trans)
+ if subtree in end_nodes:
+ f_place = get_new_place(counts)
+ net.places.add(f_place)
+ add_arc_from_to(f_trans, f_place, net)
+ add_arc_from_to(f_place, tau_join, net)
+
+ net, counts, intermediate_place = recursively_add_tree(
+ subtree, net, i_trans, f_trans, counts, rec_depth + 1
+ )
+ init_trans.append(i_trans)
+ final_trans.append(f_trans)
+
+ n = range(len(tree_children))
+ for i, j in product(n, n):
+ if transitive_reduction.is_edge_id(i, j):
+ new_place = get_new_place(counts)
+ net.places.add(new_place)
+ add_arc_from_to(final_trans[i], new_place, net)
+ add_arc_from_to(new_place, init_trans[j], net)
+
+ return net, counts, final_place
+
+
+def apply(powl, parameters=None):
+ """
+ Apply from POWL model to Petri net
+
+ Parameters
+ -----------
+ powl
+ POWL model
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ final_marking
+ Final marking
+ """
+
+ counts = pt_to_pn.Counts()
+ net = PetriNet("imdf_net_" + str(time.time()))
+ initial_marking = Marking()
+ final_marking = Marking()
+ source = get_new_place(counts)
+ source.name = "source"
+ sink = get_new_place(counts)
+ sink.name = "sink"
+ net.places.add(source)
+ net.places.add(sink)
+ initial_marking[source] = 1
+ final_marking[sink] = 1
+ initial_mandatory = True # check_tau_mandatory_at_initial_marking(powl)
+ final_mandatory = True # check_tau_mandatory_at_final_marking(powl)
+ if initial_mandatory:
+ initial_place = get_new_place(counts)
+ net.places.add(initial_place)
+ tau_initial = get_new_hidden_trans(counts, type_trans="tau")
+ net.transitions.add(tau_initial)
+ add_arc_from_to(source, tau_initial, net)
+ add_arc_from_to(tau_initial, initial_place, net)
+ else:
+ initial_place = source
+ if final_mandatory:
+ final_place = get_new_place(counts)
+ net.places.add(final_place)
+ tau_final = get_new_hidden_trans(counts, type_trans="tau")
+ net.transitions.add(tau_final)
+ add_arc_from_to(final_place, tau_final, net)
+ add_arc_from_to(tau_final, sink, net)
+ else:
+ final_place = sink
+
+ net, counts, last_added_place = recursively_add_tree(
+ powl, net, initial_place, final_place, counts, 0
+ )
+
+ reduction.apply_simple_reduction(net)
+
+ places = list(net.places)
+ for place in places:
+ if len(place.out_arcs) == 0 and place not in final_marking:
+ remove_place(net, place)
+ if len(place.in_arcs) == 0 and place not in initial_marking:
+ remove_place(net, place)
+
+ return net, initial_marking, final_marking
+
+
+def get_new_place(counts):
+ """
+ Create a new place in the Petri net
+ """
+ counts.inc_places()
+ return PetriNet.Place("p_" + str(counts.num_places))
+
+
+def get_new_hidden_trans(counts, type_trans="unknown"):
+ """
+ Create a new hidden transition in the Petri net
+ """
+ counts.inc_no_hidden()
+ return PetriNet.Transition(type_trans + "_" + str(counts.num_hidden), None)
+
+
+def get_transition(counts, label, activity, skippable=False, selfloop=False):
+ """
+ Create a transitions with the specified label in the Petri net
+ """
+ counts.inc_no_visible()
+ return PetriNet.Transition(
+ str(uuid.uuid4()),
+ label,
+ properties={
+ "activity": activity,
+ "skippable": skippable,
+ "selfloop": selfloop,
+ },
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/to_process_tree.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/to_process_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..3205bef0aa4d61cae187f868badeebe7dc48f4d2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/powl/variants/to_process_tree.py
@@ -0,0 +1,180 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import networkx as nx
+
+from pm4py.objects.process_tree.obj import ProcessTree, Operator as PTOperator
+from pm4py.objects.powl.obj import POWL, StrictPartialOrder, OperatorPOWL, Transition, SilentTransition
+from typing import Optional, Dict, Any
+from pm4py.util import nx_utils
+from collections import deque
+import warnings
+
+
+def assign_levels_to_toposort(graph):
+ """
+ Internal method
+ """
+ # First, find all nodes with in-degree == 0 to identify start nodes
+ start_nodes = [node for node, degree in graph.in_degree() if degree == 0]
+
+ # Initialize a queue for BFS
+ queue = deque(start_nodes)
+ # Initialize level dictionary to hold the level of each node
+ levels = {node: 0 for node in start_nodes}
+
+ while queue:
+ current_node = queue.popleft()
+ current_level = levels[current_node]
+
+ # For each successor of the current node
+ for successor in graph.successors(current_node):
+ # If the successor has not been assigned a level yet
+ if successor not in levels:
+ # Assign the level as current node's level + 1
+ levels[successor] = current_level + 1
+ # Add the successor to the queue to process its successors later
+ queue.append(successor)
+
+ return levels
+
+
+def apply_recursive(powl: POWL, rec_depth=0) -> ProcessTree:
+ """
+ Internal method
+ """
+ tree = ProcessTree()
+
+ if isinstance(powl, Transition):
+ tree.label = powl.label
+ elif isinstance(powl, OperatorPOWL):
+ tree.operator = powl.operator
+
+ for c in powl.children:
+ tree.children.append(apply_recursive(c, rec_depth + 1))
+ else:
+ # detects the connected components of the POWL partial order
+ # which correspond to parts of the process executed in parallel
+ DG = nx_utils.DiGraph()
+
+ for c in powl.children:
+ DG.add_node(c)
+
+ for n1 in powl.children:
+ for n2 in powl.children:
+ if n1 != n2:
+ if powl.order.is_edge(n1, n2):
+ DG.add_edge(n1, n2)
+
+ DG = nx.transitive_reduction(DG)
+ G = nx.Graph(DG)
+ conn_comp = list(nx_utils.connected_components(G))
+
+ children = []
+
+ for scc in conn_comp:
+ # for every connected component, create the subgraph and get the topological sort
+ subgraph = DG.subgraph(scc)
+
+ # Safety check: the subgraph must be a DAG (no cycles)
+ if not nx.is_directed_acyclic_graph(subgraph):
+ raise Exception("The provided POWL model is invalid!")
+
+ topo_sort = list(nx.topological_sort(subgraph))
+
+ if len(topo_sort) == 1:
+ # take the only node of the topological sort and continue the translation
+ subtree = apply_recursive(topo_sort[0], rec_depth + 1)
+ else:
+ # assign a level using BFS starting from the nodes without any ancestor
+ levels0 = assign_levels_to_toposort(subgraph)
+ max_level = max(v for v in levels0.values())
+ levels = []
+ for i in range(max_level+1):
+ levels.append([])
+ for k, v in levels0.items():
+ levels[v].append(k)
+
+ # check if from every node of the level below you can go to every node of the level after
+ for i in range(len(levels)-1):
+ for n in levels[i]:
+ for m in levels[i+1]:
+ if not G.has_edge(n, m):
+ warnings.warn("This POWL model cannot be converted precisely.")
+
+ # if so, the POWL model can be converted to a process tree.
+ # do that systematically
+ internal_children1 = []
+ for i in range(len(levels)):
+ internal_children2 = []
+ for c in levels[i]:
+ internal_children2.append(apply_recursive(c, rec_depth + 1))
+
+ if len(internal_children2) == 1:
+ internal_children1.append(internal_children2[0])
+ else:
+ subtree2 = ProcessTree(operator=PTOperator.PARALLEL, children=internal_children2)
+ for c2 in subtree2.children:
+ c2.parent = subtree2
+ internal_children1.append(subtree2)
+
+ # create a sequence including potential many parallel operators (one for every BFS level of the
+ # topological sort)
+ subtree = ProcessTree(operator=PTOperator.SEQUENCE, children=internal_children1)
+ for c1 in subtree.children:
+ c1.parent = subtree
+
+ children.append(subtree)
+
+ if len(children) == 1:
+ # if there is only one connected component, return the process tree corresponding to that
+ tree = children[0]
+ else:
+ # create an AND operator
+ tree.operator = PTOperator.PARALLEL
+
+ for child in children:
+ tree.children.append(child)
+
+ for child in tree.children:
+ child.parent = tree
+
+ return tree
+
+
+def apply(powl: POWL, parameters: Optional[Dict[Any, Any]] = None) -> ProcessTree:
+ """
+ Converts a POWL model to a process tree, in the situations in which this is possible
+
+ Parameters
+ ---------------
+ powl
+ POWL model
+
+ Returns
+ ---------------
+ process_tree
+ Process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ return apply_recursive(powl)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..384a1d7f9a8d833c1d6fd29a7a4bf7c38522255a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.process_tree import converter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..156a006e6a62c09b2b4c02521f46412681cd310e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/converter.py
@@ -0,0 +1,63 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.process_tree.variants import to_petri_net
+from pm4py.objects.conversion.process_tree.variants import (
+ to_petri_net_transition_bordered,
+)
+from pm4py.objects.conversion.process_tree.variants import to_bpmn
+from pm4py.objects.conversion.process_tree.variants import to_powl
+from pm4py.util import exec_utils
+from enum import Enum
+
+
+class Variants(Enum):
+ TO_PETRI_NET = to_petri_net
+ TO_PETRI_NET_TRANSITION_BORDERED = to_petri_net_transition_bordered
+ TO_BPMN = to_bpmn
+ TO_POWL = to_powl
+
+
+def apply(tree, parameters=None, variant=Variants.TO_PETRI_NET):
+ """
+ Method for converting from Process Tree to Petri net
+
+ Parameters
+ -----------
+ tree
+ Process tree
+ parameters
+ Parameters of the algorithm
+ variant
+ Chosen variant of the algorithm:
+ - Variants.TO_PETRI_NET
+ - Variants.TO_PETRI_NET_TRANSITION_BORDERED
+
+ Returns
+ -----------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ final_marking
+ Final marking
+ """
+ return exec_utils.get_variant(variant).apply(tree, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ca3cffc9184913c9f919bf67e55180d5559c75f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/__init__.py
@@ -0,0 +1,26 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.process_tree.variants import (
+ to_petri_net,
+ to_petri_net_transition_bordered,
+ to_bpmn,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_bpmn.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_bpmn.py
new file mode 100644
index 0000000000000000000000000000000000000000..a51b34220f0a28eb0bbc1ae69fd081de3aa2fcc8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_bpmn.py
@@ -0,0 +1,331 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+
+from pm4py.objects.process_tree.obj import Operator
+
+
+class Counts(object):
+ """
+ Shared variables among executions
+ """
+
+ def __init__(self):
+ """
+ Constructor
+ """
+ self.num_xor_gateways = 0
+ self.num_para_gateways = 0
+ self.num_tau_trans = 0
+ self.tau_trans = []
+
+ def inc_xor_gateways(self):
+ """
+ Increase the number of xor gateways (split + join)
+ """
+ self.num_xor_gateways += 1
+
+ def inc_tau_trans(self):
+ """
+ Increase the number of tau transitions
+ """
+ self.num_tau_trans += 1
+
+ def inc_para_gateways(self):
+ """
+ Increase the number of xor gateways (split + join)
+ """
+ self.num_para_gateways += 1
+
+ def append_tau(self, tau_id):
+ self.tau_trans.append(tau_id)
+
+
+def add_task(bpmn, counts, label):
+ """
+ Create a task with the specified label in the BPMN
+ """
+ from pm4py.objects.bpmn.obj import BPMN
+
+ task = BPMN.Task(name=label)
+ bpmn.add_node(task)
+ return bpmn, task, counts
+
+
+def add_tau_task(bpmn, counts):
+ """
+ Create a task with the specified label in the BPMN
+ """
+ from pm4py.objects.bpmn.obj import BPMN
+
+ counts.inc_tau_trans()
+ tau_name = "tau_" + str(counts.num_tau_trans)
+ tau_task = BPMN.Task(name=tau_name)
+ bpmn.add_node(tau_task)
+ counts.append_tau(tau_task)
+ return bpmn, tau_task, counts
+
+
+def add_xor_gateway(bpmn, counts):
+ from pm4py.objects.bpmn.obj import BPMN
+
+ counts.inc_xor_gateways()
+ split_name = "xor_" + str(counts.num_xor_gateways) + "_split"
+ join_name = "xor_" + str(counts.num_xor_gateways) + "_join"
+
+ split = BPMN.ExclusiveGateway(
+ name="", gateway_direction=BPMN.Gateway.Direction.DIVERGING
+ )
+ join = BPMN.ExclusiveGateway(
+ name="", gateway_direction=BPMN.Gateway.Direction.CONVERGING
+ )
+ bpmn.add_node(split)
+ bpmn.add_node(join)
+
+ return bpmn, split, join, counts
+
+
+def add_parallel_gateway(bpmn, counts):
+ from pm4py.objects.bpmn.obj import BPMN
+
+ counts.inc_para_gateways()
+ split_name = "parallel_" + str(counts.num_para_gateways) + "_split"
+ join_name = "parallel_" + str(counts.num_para_gateways) + "_join"
+
+ split = BPMN.ParallelGateway(
+ name="", gateway_direction=BPMN.Gateway.Direction.DIVERGING
+ )
+ join = BPMN.ParallelGateway(
+ name="", gateway_direction=BPMN.Gateway.Direction.CONVERGING
+ )
+ bpmn.add_node(split)
+ bpmn.add_node(join)
+ return bpmn, split, join, counts
+
+
+def add_inclusive_gateway(bpmn, counts):
+ from pm4py.objects.bpmn.obj import BPMN
+
+ counts.inc_para_gateways()
+ split_name = "parallel_" + str(counts.num_para_gateways) + "_split"
+ join_name = "parallel_" + str(counts.num_para_gateways) + "_join"
+
+ split = BPMN.InclusiveGateway(
+ name="", gateway_direction=BPMN.Gateway.Direction.DIVERGING
+ )
+ join = BPMN.InclusiveGateway(
+ name="", gateway_direction=BPMN.Gateway.Direction.CONVERGING
+ )
+ bpmn.add_node(split)
+ bpmn.add_node(join)
+ return bpmn, split, join, counts
+
+
+def recursively_add_tree(
+ parent_tree, tree, bpmn, initial_event, final_event, counts, rec_depth
+):
+ from pm4py.objects.bpmn.obj import BPMN
+
+ tree_childs = [child for child in tree.children]
+ initial_connector = None
+ final_connector = None
+
+ if tree.operator is None:
+ trans = tree
+ if trans.label is None:
+ bpmn, task, counts = add_tau_task(bpmn, counts)
+ bpmn.add_flow(BPMN.SequenceFlow(initial_event, task))
+ bpmn.add_flow(BPMN.SequenceFlow(task, final_event))
+ initial_connector = task
+ final_connector = task
+ else:
+ bpmn, task, counts = add_task(bpmn, counts, trans.label)
+ bpmn.add_flow(BPMN.SequenceFlow(initial_event, task))
+ bpmn.add_flow(BPMN.SequenceFlow(task, final_event))
+ initial_connector = task
+ final_connector = task
+
+ elif tree.operator == Operator.XOR:
+ bpmn, split_gateway, join_gateway, counts = add_xor_gateway(
+ bpmn, counts
+ )
+ for subtree in tree_childs:
+ bpmn, counts, x, y = recursively_add_tree(
+ tree,
+ subtree,
+ bpmn,
+ split_gateway,
+ join_gateway,
+ counts,
+ rec_depth + 1,
+ )
+ bpmn.add_flow(BPMN.SequenceFlow(initial_event, split_gateway))
+ bpmn.add_flow(BPMN.SequenceFlow(join_gateway, final_event))
+ initial_connector = split_gateway
+ final_connector = join_gateway
+
+ elif tree.operator == Operator.PARALLEL:
+ bpmn, split_gateway, join_gateway, counts = add_parallel_gateway(
+ bpmn, counts
+ )
+ for subtree in tree_childs:
+ bpmn, counts, x, y = recursively_add_tree(
+ tree,
+ subtree,
+ bpmn,
+ split_gateway,
+ join_gateway,
+ counts,
+ rec_depth + 1,
+ )
+ bpmn.add_flow(BPMN.SequenceFlow(initial_event, split_gateway))
+ bpmn.add_flow(BPMN.SequenceFlow(join_gateway, final_event))
+ initial_connector = split_gateway
+ final_connector = join_gateway
+
+ elif tree.operator == Operator.OR:
+ bpmn, split_gateway, join_gateway, counts = add_inclusive_gateway(
+ bpmn, counts
+ )
+ for subtree in tree_childs:
+ bpmn, counts, x, y = recursively_add_tree(
+ tree,
+ subtree,
+ bpmn,
+ split_gateway,
+ join_gateway,
+ counts,
+ rec_depth + 1,
+ )
+ bpmn.add_flow(BPMN.SequenceFlow(initial_event, split_gateway))
+ bpmn.add_flow(BPMN.SequenceFlow(join_gateway, final_event))
+ initial_connector = split_gateway
+ final_connector = join_gateway
+
+ elif tree.operator == Operator.SEQUENCE:
+ initial_intermediate_task = initial_event
+ bpmn, final_intermediate_task, counts = add_tau_task(bpmn, counts)
+ for i in range(len(tree_childs)):
+ bpmn, counts, initial_connect, final_connect = (
+ recursively_add_tree(
+ tree,
+ tree_childs[i],
+ bpmn,
+ initial_intermediate_task,
+ final_intermediate_task,
+ counts,
+ rec_depth + 1,
+ )
+ )
+ initial_intermediate_task = final_connect
+ if i == 0:
+ initial_connector = initial_connect
+ if i == len(tree_childs) - 2:
+ final_intermediate_task = final_event
+ else:
+ bpmn, final_intermediate_task, counts = add_tau_task(
+ bpmn, counts
+ )
+ final_connector = final_connect
+
+ elif tree.operator == Operator.LOOP:
+ do = tree_childs[0]
+ bpmn, split, join, counts = add_xor_gateway(bpmn, counts)
+ bpmn, counts, i, y = recursively_add_tree(
+ tree, do, bpmn, join, split, counts, rec_depth + 1
+ )
+ for redo in tree_childs[1:]:
+ bpmn, counts, x, y = recursively_add_tree(
+ tree, redo, bpmn, split, join, counts, rec_depth + 1
+ )
+ bpmn.add_flow(BPMN.SequenceFlow(initial_event, join))
+ bpmn.add_flow(BPMN.SequenceFlow(split, final_event))
+ initial_connector = join
+ final_connector = split
+
+ return bpmn, counts, initial_connector, final_connector
+
+
+def delete_tau_transitions(bpmn, counts):
+ from pm4py.objects.bpmn.obj import BPMN
+
+ for tau_tran in counts.tau_trans:
+ in_arcs = tau_tran.get_in_arcs()
+ out_arcs = tau_tran.get_out_arcs()
+ if len(in_arcs) > 1 or len(out_arcs) > 1:
+ raise Exception(
+ "Tau transition has more than one incoming or outgoing edge!"
+ )
+ if in_arcs and out_arcs:
+ out_flow = out_arcs[0]
+ in_flow = in_arcs[0]
+ source = in_flow.get_source()
+ target = out_flow.get_target()
+ bpmn.remove_flow(out_flow)
+ bpmn.remove_flow(in_flow)
+ bpmn.add_flow(BPMN.SequenceFlow(source, target))
+ else:
+ for in_flow in copy.copy(in_arcs):
+ bpmn.remove_flow(in_flow)
+ for out_flow in copy.copy(out_arcs):
+ bpmn.remove_flow(out_flow)
+ bpmn.remove_node(tau_tran)
+
+ return bpmn
+
+
+def apply(tree, parameters=None):
+ """
+ Converts the process tree into a BPMN diagram
+
+ Parameters
+ --------------
+ tree
+ Process tree
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ bpmn_graph
+ BPMN diagram
+ """
+ from pm4py.objects.bpmn.obj import BPMN
+
+ counts = Counts()
+ bpmn = BPMN()
+ start_event = BPMN.StartEvent(name="start", isInterrupting=True)
+ end_event = BPMN.NormalEndEvent(name="end")
+ bpmn.add_node(start_event)
+ bpmn.add_node(end_event)
+ bpmn, counts, _, _ = recursively_add_tree(
+ tree, tree, bpmn, start_event, end_event, counts, 0
+ )
+ bpmn = delete_tau_transitions(bpmn, counts)
+
+ for node in bpmn.get_nodes():
+ node.set_process(bpmn.get_process_id())
+
+ for edge in bpmn.get_flows():
+ edge.set_process(bpmn.get_process_id())
+
+ return bpmn
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_petri_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_petri_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..de93135f03ef8a9db12543366fcfc68e2f6bc39d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_petri_net.py
@@ -0,0 +1,676 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import time
+import uuid
+
+from pm4py.objects.petri_net.obj import Marking
+from pm4py.objects.petri_net.obj import PetriNet
+from pm4py.objects.petri_net.utils.petri_utils import (
+ remove_transition,
+ add_arc_from_to,
+ remove_place,
+)
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.objects.process_tree.obj import Operator
+from pm4py.objects.petri_net.utils import reduction
+
+
+class Counts(object):
+ """
+ Shared variables among executions
+ """
+
+ def __init__(self):
+ """
+ Constructor
+ """
+ self.num_places = 0
+ self.num_hidden = 0
+ self.num_visible_trans = 0
+ self.dict_skips = {}
+ self.dict_loops = {}
+
+ def inc_places(self):
+ """
+ Increase the number of places
+ """
+ self.num_places = self.num_places + 1
+
+ def inc_no_hidden(self):
+ """
+ Increase the number of hidden transitions
+ """
+ self.num_hidden = self.num_hidden + 1
+
+ def inc_no_visible(self):
+ """
+ Increase the number of visible transitions
+ """
+ self.num_visible_trans = self.num_visible_trans + 1
+
+
+def clean_duplicate_transitions(net):
+ """
+ Clean duplicate transitions in a Petri net
+
+ Parameters
+ ------------
+ net
+ Petri net
+
+ Returns
+ ------------
+ net
+ Cleaned Petri net
+ """
+ transitions = list(net.transitions)
+ already_visited_combo = set()
+ for i in range(0, len(transitions)):
+ trans = transitions[i]
+ if trans.label is None:
+ in_arcs = trans.in_arcs
+ out_arcs = trans.out_arcs
+ to_delete = False
+ for in_arc in in_arcs:
+ in_place = in_arc.source
+ for out_arc in out_arcs:
+ out_place = out_arc.target
+ combo = in_place.name + " " + out_place.name
+ if combo in already_visited_combo:
+ to_delete = True
+ break
+ already_visited_combo.add(combo)
+ if to_delete:
+ net = remove_transition(net, trans)
+ return net
+
+
+def get_new_place(counts):
+ """
+ Create a new place in the Petri net
+ """
+ counts.inc_places()
+ return PetriNet.Place("p_" + str(counts.num_places))
+
+
+def get_new_hidden_trans(counts, type_trans="unknown"):
+ """
+ Create a new hidden transition in the Petri net
+ """
+ counts.inc_no_hidden()
+ return PetriNet.Transition(type_trans + "_" + str(counts.num_hidden), None)
+
+
+def get_transition(counts, label):
+ """
+ Create a transitions with the specified label in the Petri net
+ """
+ counts.inc_no_visible()
+ return PetriNet.Transition(str(uuid.uuid4()), label)
+
+
+def get_first_terminal_child_transitions(tree):
+ """
+ Gets the list of transitions belonging to the first terminal child node of the current tree
+
+ Parameters
+ ----------
+ tree
+ Process tree
+
+ Returns
+ ---------
+ transitions_list
+ List of transitions belonging to the first terminal child node
+ """
+ if tree.children:
+ if tree.children[0].operator:
+ return get_first_terminal_child_transitions(tree.children[0])
+ else:
+ if tree.children[0].children:
+ return tree.children[0].children
+ else:
+ return [tree.children[0]]
+ return []
+
+
+def get_last_terminal_child_transitions(tree):
+ """
+ Gets the list of transitions belonging to the last terminal child node of the current tree
+
+ Parameters
+ ----------
+ tree
+ Process tree
+
+ Returns
+ ---------
+ transitions_list
+ List of transitions belonging to the first terminal child node
+ """
+ if tree.children:
+ if tree.children[-1].operator:
+ return get_last_terminal_child_transitions(tree.children[-1])
+ else:
+ if tree.children[-1].children:
+ return tree.children[-1].children
+ else:
+ return [tree.children[-1]]
+ return []
+
+
+def check_loop_to_first_operator(tree):
+ """
+ Checks if loop to first operator
+
+ Parameters
+ ------------
+ tree
+ Process tree
+
+ Returns
+ ------------
+ boolean
+ Check if no loop to the first operator
+ """
+ if tree.operator == Operator.LOOP:
+ return True
+ if tree.children:
+ if tree.children[0].operator == Operator.LOOP:
+ return True
+ else:
+ return check_loop_to_first_operator(tree.children[0])
+ return tree.operator == Operator.LOOP
+
+
+def check_loop_to_last_operator(tree):
+ """
+ Checks if loop to last operator
+
+ Parameters
+ -------------
+ tree
+ Process tree
+
+ Returns
+ -------------
+ boolean
+ Check if no loop to the last operator
+ """
+ if tree.operator == Operator.LOOP:
+ return True
+ if tree.children:
+ if tree.children[-1].operator == Operator.LOOP:
+ return True
+ else:
+ return check_loop_to_last_operator(tree.children[-1])
+ return tree.operator == Operator.LOOP
+
+
+def check_initial_loop(tree):
+ """
+ Check if the tree, on-the-left, starts with a loop
+
+ Parameters
+ ----------
+ tree
+ Process tree
+
+ Returns
+ ----------
+ boolean
+ True if it starts with an initial loop
+ """
+ if tree.children:
+ if tree.children[0].operator:
+ if tree.children[0].operator == Operator.LOOP:
+ return True
+ else:
+ return check_terminal_loop(tree.children[0])
+ return False
+
+
+def check_terminal_loop(tree):
+ """
+ Check if the tree, on-the-right, ends with a loop
+
+ Parameters
+ ----------
+ tree
+ Process tree
+
+ Returns
+ -----------
+ boolean
+ True if it ends with a terminal loop
+ """
+ if tree.children:
+ if tree.children[-1].operator:
+ if tree.children[-1].operator == Operator.LOOP:
+ return True
+ else:
+ return check_terminal_loop(tree.children[-1])
+ return False
+
+
+def check_tau_mandatory_at_initial_marking(tree):
+ """
+ When a conversion to a Petri net is operated, check if is mandatory to add a hidden transition
+ at initial marking
+
+ Parameters
+ ----------
+ tree
+ Process tree
+
+ Returns
+ ----------
+ boolean
+ Boolean that is true if it is mandatory to add a hidden transition connecting the initial marking
+ to the rest of the process
+ """
+ condition1 = check_initial_loop(tree)
+ terminal_transitions = get_first_terminal_child_transitions(tree)
+ condition2 = len(terminal_transitions) > 1
+ condition3 = check_loop_to_first_operator(tree)
+ condition4 = (
+ tree.operator == Operator.XOR or tree.operator == Operator.PARALLEL
+ )
+
+ return condition1 or condition2 or condition3 or condition4
+
+
+def check_tau_mandatory_at_final_marking(tree):
+ """
+ When a conversion to a Petri net is operated, check if is mandatory to add a hidden transition
+ at final marking
+
+ Returns
+ ----------
+ boolean
+ Boolean that is true if it is mandatory to add a hidden transition connecting
+ the rest of the process to the final marking
+ """
+ condition1 = check_terminal_loop(tree)
+ terminal_transitions = get_last_terminal_child_transitions(tree)
+ condition2 = len(terminal_transitions) > 1
+ condition3 = check_loop_to_last_operator(tree)
+ condition4 = (
+ tree.operator == Operator.XOR or tree.operator == Operator.PARALLEL
+ )
+
+ return condition1 or condition2 or condition3 or condition4
+
+
+def recursively_add_tree(
+ parent_tree,
+ tree,
+ net,
+ initial_entity_subtree,
+ final_entity_subtree,
+ counts,
+ rec_depth,
+ force_add_skip=False,
+):
+ """
+ Recursively add the subtrees to the Petri net
+
+ Parameters
+ -----------
+ parent_tree
+ Parent tree
+ tree
+ Current subtree
+ net
+ Petri net
+ initial_entity_subtree
+ Initial entity (place/transition) that should be attached from the subtree
+ final_entity_subtree
+ Final entity (place/transition) that should be attached from the subtree
+ counts
+ Counts object (keeps the number of places, transitions and hidden transitions)
+ rec_depth
+ Recursion depth of the current iteration
+ force_add_skip
+ Boolean value that tells if the addition of a skip is mandatory
+
+ Returns
+ ----------
+ net
+ Updated Petri net
+ counts
+ Updated counts object (keeps the number of places, transitions and hidden transitions)
+ final_place
+ Last place added in this recursion
+ """
+ if type(initial_entity_subtree) is PetriNet.Transition:
+ initial_place = get_new_place(counts)
+ net.places.add(initial_place)
+ add_arc_from_to(initial_entity_subtree, initial_place, net)
+ else:
+ initial_place = initial_entity_subtree
+ if (
+ final_entity_subtree is not None
+ and type(final_entity_subtree) is PetriNet.Place
+ ):
+ final_place = final_entity_subtree
+ else:
+ final_place = get_new_place(counts)
+ net.places.add(final_place)
+ if (
+ final_entity_subtree is not None
+ and type(final_entity_subtree) is PetriNet.Transition
+ ):
+ add_arc_from_to(final_place, final_entity_subtree, net)
+ tree_childs = [child for child in tree.children]
+
+ if force_add_skip:
+ invisible = get_new_hidden_trans(counts, type_trans="skip")
+ add_arc_from_to(initial_place, invisible, net)
+ add_arc_from_to(invisible, final_place, net)
+
+ if tree.operator is None:
+ trans = tree
+ if trans.label is None:
+ petri_trans = get_new_hidden_trans(counts, type_trans="skip")
+ else:
+ petri_trans = get_transition(counts, trans.label)
+ net.transitions.add(petri_trans)
+ add_arc_from_to(initial_place, petri_trans, net)
+ add_arc_from_to(petri_trans, final_place, net)
+
+ if tree.operator == Operator.XOR:
+ for subtree in tree_childs:
+ net, counts, intermediate_place = recursively_add_tree(
+ tree,
+ subtree,
+ net,
+ initial_place,
+ final_place,
+ counts,
+ rec_depth + 1,
+ )
+ elif tree.operator == Operator.OR:
+ new_initial_trans = get_new_hidden_trans(counts, type_trans="tauSplit")
+ net.transitions.add(new_initial_trans)
+ add_arc_from_to(initial_place, new_initial_trans, net)
+ new_final_trans = get_new_hidden_trans(counts, type_trans="tauJoin")
+ net.transitions.add(new_final_trans)
+ add_arc_from_to(new_final_trans, final_place, net)
+ terminal_place = get_new_place(counts)
+ net.places.add(terminal_place)
+ add_arc_from_to(terminal_place, new_final_trans, net)
+ first_place = get_new_place(counts)
+ net.places.add(first_place)
+ add_arc_from_to(new_initial_trans, first_place, net)
+
+ for subtree in tree_childs:
+ subtree_init_place = get_new_place(counts)
+ net.places.add(subtree_init_place)
+ add_arc_from_to(new_initial_trans, subtree_init_place, net)
+ subtree_start_place = get_new_place(counts)
+ net.places.add(subtree_start_place)
+ subtree_end_place = get_new_place(counts)
+ net.places.add(subtree_end_place)
+ trans_start = get_new_hidden_trans(
+ counts, type_trans="inclusiveStart"
+ )
+ trans_later = get_new_hidden_trans(
+ counts, type_trans="inclusiveLater"
+ )
+ trans_skip = get_new_hidden_trans(
+ counts, type_trans="inclusiveSkip"
+ )
+ net.transitions.add(trans_start)
+ net.transitions.add(trans_later)
+ net.transitions.add(trans_skip)
+ add_arc_from_to(first_place, trans_start, net)
+ add_arc_from_to(subtree_init_place, trans_start, net)
+ add_arc_from_to(trans_start, subtree_start_place, net)
+ add_arc_from_to(trans_start, terminal_place, net)
+
+ add_arc_from_to(terminal_place, trans_later, net)
+ add_arc_from_to(subtree_init_place, trans_later, net)
+ add_arc_from_to(trans_later, subtree_start_place, net)
+ add_arc_from_to(trans_later, terminal_place, net)
+
+ add_arc_from_to(terminal_place, trans_skip, net)
+ add_arc_from_to(subtree_init_place, trans_skip, net)
+ add_arc_from_to(trans_skip, terminal_place, net)
+ add_arc_from_to(trans_skip, subtree_end_place, net)
+
+ add_arc_from_to(subtree_end_place, new_final_trans, net)
+
+ net, counts, intermediate_place = recursively_add_tree(
+ tree,
+ subtree,
+ net,
+ subtree_start_place,
+ subtree_end_place,
+ counts,
+ rec_depth + 1,
+ )
+
+ elif tree.operator == Operator.PARALLEL:
+ new_initial_trans = get_new_hidden_trans(counts, type_trans="tauSplit")
+ net.transitions.add(new_initial_trans)
+ add_arc_from_to(initial_place, new_initial_trans, net)
+ new_final_trans = get_new_hidden_trans(counts, type_trans="tauJoin")
+ net.transitions.add(new_final_trans)
+ add_arc_from_to(new_final_trans, final_place, net)
+
+ for subtree in tree_childs:
+ net, counts, intermediate_place = recursively_add_tree(
+ tree,
+ subtree,
+ net,
+ new_initial_trans,
+ new_final_trans,
+ counts,
+ rec_depth + 1,
+ )
+
+ elif tree.operator == Operator.INTERLEAVING:
+ new_initial_trans = get_new_hidden_trans(counts, type_trans="tauSplit")
+ net.transitions.add(new_initial_trans)
+ add_arc_from_to(initial_place, new_initial_trans, net)
+ new_final_trans = get_new_hidden_trans(counts, type_trans="tauJoin")
+ net.transitions.add(new_final_trans)
+ add_arc_from_to(new_final_trans, final_place, net)
+
+ control_place = get_new_place(counts)
+ net.places.add(control_place)
+
+ add_arc_from_to(new_initial_trans, control_place, net)
+ add_arc_from_to(control_place, new_final_trans, net)
+
+ for subtree in tree_childs:
+ placeI = get_new_place(counts)
+ net.places.add(placeI)
+ iTrans = get_new_hidden_trans(counts, type_trans="iTrans")
+ net.transitions.add(iTrans)
+ placeF = get_new_place(counts)
+ net.places.add(placeF)
+ fTrans = get_new_hidden_trans(counts, type_trans="fTrans")
+ net.transitions.add(fTrans)
+
+ add_arc_from_to(new_initial_trans, placeI, net)
+ add_arc_from_to(placeI, iTrans, net)
+ add_arc_from_to(fTrans, placeF, net)
+ add_arc_from_to(placeF, new_final_trans, net)
+
+ add_arc_from_to(control_place, iTrans, net)
+ add_arc_from_to(fTrans, control_place, net)
+
+ net, counts, intermediate_place = recursively_add_tree(
+ tree, subtree, net, iTrans, fTrans, counts, rec_depth + 1
+ )
+
+ elif tree.operator == Operator.SEQUENCE:
+ intermediate_place = initial_place
+ for i in range(len(tree_childs)):
+ final_connection_place = None
+ if i == len(tree_childs) - 1:
+ final_connection_place = final_place
+ net, counts, intermediate_place = recursively_add_tree(
+ tree,
+ tree_childs[i],
+ net,
+ intermediate_place,
+ final_connection_place,
+ counts,
+ rec_depth + 1,
+ )
+ elif tree.operator == Operator.LOOP:
+ # if not parent_tree.operator == Operator.SEQUENCE:
+ new_initial_place = get_new_place(counts)
+ net.places.add(new_initial_place)
+ init_loop_trans = get_new_hidden_trans(counts, type_trans="init_loop")
+ net.transitions.add(init_loop_trans)
+ add_arc_from_to(initial_place, init_loop_trans, net)
+ add_arc_from_to(init_loop_trans, new_initial_place, net)
+ initial_place = new_initial_place
+ loop_trans = get_new_hidden_trans(counts, type_trans="loop")
+ net.transitions.add(loop_trans)
+ if len(tree_childs) == 1:
+ net, counts, intermediate_place = recursively_add_tree(
+ tree,
+ tree_childs[0],
+ net,
+ initial_place,
+ final_place,
+ counts,
+ rec_depth + 1,
+ )
+ add_arc_from_to(final_place, loop_trans, net)
+ add_arc_from_to(loop_trans, initial_place, net)
+ else:
+ net, counts, int1 = recursively_add_tree(
+ tree,
+ tree_childs[0],
+ net,
+ initial_place,
+ None,
+ counts,
+ rec_depth + 1,
+ )
+ int2 = None
+ for i in range(1, len(tree_childs)):
+ net, counts, int2 = recursively_add_tree(
+ tree,
+ tree_childs[i],
+ net,
+ int1,
+ int2,
+ counts,
+ rec_depth + 1,
+ )
+
+ net, counts, int3 = recursively_add_tree(
+ tree,
+ ProcessTree(),
+ net,
+ int1,
+ final_place,
+ counts,
+ rec_depth + 1,
+ )
+
+ looping_place = int2
+
+ add_arc_from_to(looping_place, loop_trans, net)
+ add_arc_from_to(loop_trans, initial_place, net)
+
+ return net, counts, final_place
+
+
+def apply(tree, parameters=None):
+ """
+ Apply from Process Tree to Petri net
+
+ Parameters
+ -----------
+ tree
+ Process tree
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ final_marking
+ Final marking
+ """
+ if parameters is None:
+ parameters = {}
+ del parameters
+
+ counts = Counts()
+ net = PetriNet("imdf_net_" + str(time.time()))
+ initial_marking = Marking()
+ final_marking = Marking()
+ source = get_new_place(counts)
+ source.name = "source"
+ sink = get_new_place(counts)
+ sink.name = "sink"
+ net.places.add(source)
+ net.places.add(sink)
+ initial_marking[source] = 1
+ final_marking[sink] = 1
+ initial_mandatory = check_tau_mandatory_at_initial_marking(tree)
+ final_mandatory = check_tau_mandatory_at_final_marking(tree)
+ if initial_mandatory:
+ initial_place = get_new_place(counts)
+ net.places.add(initial_place)
+ tau_initial = get_new_hidden_trans(counts, type_trans="tau")
+ net.transitions.add(tau_initial)
+ add_arc_from_to(source, tau_initial, net)
+ add_arc_from_to(tau_initial, initial_place, net)
+ else:
+ initial_place = source
+ if final_mandatory:
+ final_place = get_new_place(counts)
+ net.places.add(final_place)
+ tau_final = get_new_hidden_trans(counts, type_trans="tau")
+ net.transitions.add(tau_final)
+ add_arc_from_to(final_place, tau_final, net)
+ add_arc_from_to(tau_final, sink, net)
+ else:
+ final_place = sink
+
+ net, counts, last_added_place = recursively_add_tree(
+ tree, tree, net, initial_place, final_place, counts, 0
+ )
+
+ reduction.apply_simple_reduction(net)
+
+ places = list(net.places)
+ for place in places:
+ if len(place.out_arcs) == 0 and place not in final_marking:
+ remove_place(net, place)
+ if len(place.in_arcs) == 0 and place not in initial_marking:
+ remove_place(net, place)
+
+ return net, initial_marking, final_marking
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_petri_net_transition_bordered.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_petri_net_transition_bordered.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38efa8bd1d4baea0a629e9060ba4a0e7ab97668
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_petri_net_transition_bordered.py
@@ -0,0 +1,133 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net import obj
+from pm4py.objects.petri_net.utils import petri_utils as pn_util
+from pm4py.objects.process_tree.obj import Operator as pt_opt
+
+
+def apply(tree, parameters=None):
+ """
+ Only supports loops with 2 children!
+ :param tree:
+ :return:
+ """
+ net = obj.PetriNet(name=str(tree))
+ if len(tree.children) == 0:
+ pn_util.add_transition(net, label=tree.label, name=str(id(tree)))
+ else:
+ sub_nets = list()
+ for c in tree.children:
+ sub_net, ini, fin = apply(c)
+ sub_nets.append(sub_net)
+ pn_util.merge(net, sub_nets)
+ switch = {
+ pt_opt.SEQUENCE: construct_sequence_pattern,
+ pt_opt.XOR: construct_xor_pattern,
+ pt_opt.PARALLEL: construct_and_pattern,
+ pt_opt.LOOP: construct_loop_pattern,
+ }
+ net, ini, fin = switch[tree.operator](net, sub_nets)
+ if tree.parent is None:
+ p_ini = pn_util.add_place(net)
+ p_fin = pn_util.add_place(net)
+ pn_util.add_arc_from_to(p_ini, _get_src_transition(net), net)
+ pn_util.add_arc_from_to(_get_sink_transition(net), p_fin, net)
+ return net, obj.Marking({p_ini: 1}), obj.Marking({p_fin: 1})
+ return net, obj.Marking(), obj.Marking()
+
+
+def _get_src_transition(sub_net):
+ for t in sub_net.transitions:
+ if len(pn_util.pre_set(t)) == 0:
+ return t
+ return None
+
+
+def _get_sink_transition(sub_net):
+ for t in sub_net.transitions:
+ if len(pn_util.post_set(t)) == 0:
+ return t
+ return None
+
+
+def _add_src_sink_transitions(net, p_s, p_t):
+ src = pn_util.add_transition(net)
+ pn_util.add_arc_from_to(src, p_s, net)
+ sink = pn_util.add_transition(net)
+ pn_util.add_arc_from_to(p_t, sink, net)
+ return net, obj.Marking(), obj.Marking()
+
+
+def construct_sequence_pattern(net, sub_nets):
+ places = [None] * (len(sub_nets) + 1)
+ for i in range(len(sub_nets) + 1):
+ places[i] = pn_util.add_place(net)
+ for i in range(len(sub_nets)):
+ pn_util.add_arc_from_to(
+ places[i], _get_src_transition(sub_nets[i]), net
+ )
+ pn_util.add_arc_from_to(
+ _get_sink_transition(sub_nets[i]), places[i + 1], net
+ )
+ src = pn_util.add_transition(net)
+ pn_util.add_arc_from_to(src, places[0], net)
+ sink = pn_util.add_transition(net)
+ pn_util.add_arc_from_to(places[len(places) - 1], sink, net)
+ return net, obj.Marking(), obj.Marking()
+
+
+def construct_xor_pattern(net, sub_nets):
+ p_s = pn_util.add_place(net)
+ p_o = pn_util.add_place(net)
+ for n in sub_nets:
+ pn_util.add_arc_from_to(p_s, _get_src_transition(n), net)
+ pn_util.add_arc_from_to(_get_sink_transition(n), p_o, net)
+ return _add_src_sink_transitions(net, p_s, p_o)
+
+
+def construct_and_pattern(net, sub_nets):
+ p_s = [None] * len(sub_nets)
+ p_t = [None] * len(sub_nets)
+ for i in range(len(sub_nets)):
+ p_s[i] = pn_util.add_place(net)
+ p_t[i] = pn_util.add_place(net)
+ pn_util.add_arc_from_to(p_s[i], _get_src_transition(sub_nets[i]), net)
+ pn_util.add_arc_from_to(_get_sink_transition(sub_nets[i]), p_t[i], net)
+ src = pn_util.add_transition(net)
+ for p in p_s:
+ pn_util.add_arc_from_to(src, p, net)
+ sink = pn_util.add_transition(net)
+ for p in p_t:
+ pn_util.add_arc_from_to(p, sink, net)
+ return net, obj.Marking(), obj.Marking()
+
+
+def construct_loop_pattern(net, sub_nets):
+ assert len(sub_nets) == 2
+ p_s = pn_util.add_place(net)
+ p_t = pn_util.add_place(net)
+ pn_util.add_arc_from_to(p_s, _get_src_transition(sub_nets[0]), net)
+ pn_util.add_arc_from_to(p_t, _get_src_transition(sub_nets[1]), net)
+ pn_util.add_arc_from_to(_get_sink_transition(sub_nets[0]), p_t, net)
+ pn_util.add_arc_from_to(_get_sink_transition(sub_nets[1]), p_s, net)
+ net, ini, fin = _add_src_sink_transitions(net, p_s, p_t)
+ return net, obj.Marking(), obj.Marking()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_powl.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_powl.py
new file mode 100644
index 0000000000000000000000000000000000000000..da316009b91b7eb54645e87b183a67ec13be14e8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/process_tree/variants/to_powl.py
@@ -0,0 +1,84 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree.obj import ProcessTree, Operator as PTOperator
+from pm4py.objects.powl.obj import (
+ POWL,
+ StrictPartialOrder,
+ OperatorPOWL,
+ Transition,
+ SilentTransition,
+)
+from typing import Optional, Dict, Any
+
+
+def apply_recursive(tree: ProcessTree, rec_depth=0) -> POWL:
+ """
+ Internal method
+ """
+ nodes = []
+
+ for c in tree.children:
+ nodes.append(apply_recursive(c, rec_depth + 1))
+
+ if tree.operator is None:
+ if tree.label is not None:
+ powl = Transition(label=tree.label)
+ else:
+ powl = SilentTransition()
+ elif tree.operator == PTOperator.OR:
+ raise Exception(
+ "conversion of process trees containing OR nodes is not supported!"
+ )
+ elif tree.operator == PTOperator.XOR:
+ powl = OperatorPOWL(PTOperator.XOR, nodes)
+ elif tree.operator == PTOperator.LOOP:
+ powl = OperatorPOWL(PTOperator.LOOP, nodes)
+ else:
+ powl = StrictPartialOrder(nodes=nodes)
+
+ if tree.operator == PTOperator.SEQUENCE:
+ for i in range(len(nodes) - 1):
+ powl.order.add_edge(nodes[i], nodes[i + 1])
+
+ return powl
+
+
+def apply(
+ tree: ProcessTree, parameters: Optional[Dict[Any, Any]] = None
+) -> POWL:
+ """
+ Converts a process tree model to a POWL model
+
+ Parameters
+ ---------------
+ tree
+ Process tree
+
+ Returns
+ ---------------
+ powl_model
+ POWL model
+ """
+ if parameters is None:
+ parameters = {}
+
+ return apply_recursive(tree)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..32225bbd42d65840303b2770c8bf60619b1fe39d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/converter.py
@@ -0,0 +1,57 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.trie.variants import to_petri_net
+from enum import Enum
+from pm4py.util import exec_utils
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.trie.obj import Trie
+from typing import Optional, Dict, Any, Tuple
+
+
+class Variants(Enum):
+ TO_PETRI_NET = to_petri_net
+
+
+def apply(
+ prefix_tree: Trie,
+ variant=Variants.TO_PETRI_NET,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Converts the prefix tree objects using the specified variant
+
+ Parameters
+ ----------------
+ prefix_tree
+ Prefix tree
+ variant
+ Variant of the conversion:
+ - Variants.TO_PETRI_NET => converts the prefix tree object to a Petri net
+ parameters
+ Optional parameters of the method.
+
+ Returns
+ ----------------
+ obj
+ Converted object
+ """
+ return exec_utils.get_variant(variant).apply(prefix_tree, parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/variants/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/variants/to_petri_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/variants/to_petri_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fe4563e9b8def947243ef1737b5feb19f87f454
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/trie/variants/to_petri_net.py
@@ -0,0 +1,93 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import uuid
+from pm4py.objects.petri_net.utils import petri_utils
+from typing import Optional, Dict, Any, Tuple
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.trie.obj import Trie
+
+
+def __add_prefix_tree_node_to_petri(
+ node: Trie, net: PetriNet, prev: PetriNet.Place, sink: PetriNet.Place
+):
+ """
+ Internal method to add a prefix tree node to a Petri net.
+ """
+ trans = PetriNet.Transition(str(uuid.uuid4()), label=node.label)
+ net.transitions.add(trans)
+ petri_utils.add_arc_from_to(prev, trans, net)
+ if node.children:
+ succ_place = PetriNet.Place(str(uuid.uuid4()))
+ net.places.add(succ_place)
+ petri_utils.add_arc_from_to(trans, succ_place, net)
+ for child in node.children:
+ __add_prefix_tree_node_to_petri(child, net, succ_place, sink)
+ if node.final:
+ new_trans = PetriNet.Transition(str(uuid.uuid4()))
+ net.transitions.add(new_trans)
+ petri_utils.add_arc_from_to(succ_place, new_trans, net)
+ petri_utils.add_arc_from_to(new_trans, sink, net)
+ else:
+ petri_utils.add_arc_from_to(trans, sink, net)
+
+
+def apply(
+ prefix_tree: Trie, parameters: Optional[Dict[Any, Any]] = None
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Transforms a prefix tree to an accepting Petri net.
+
+ Parameters
+ -----------------
+ prefix_tree
+ Prefix_tree
+ parameters
+ Optional parameters of the method.
+
+ Returns
+ -----------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ """
+ if parameters is None:
+ parameters = {}
+
+ # create a empty Petri net
+ net = PetriNet("petri")
+ im = Marking()
+ fm = Marking()
+ source = PetriNet.Place(str(uuid.uuid4()))
+ net.places.add(source)
+ sink = PetriNet.Place(str(uuid.uuid4()))
+ net.places.add(sink)
+ im[source] = 1
+ fm[sink] = 1
+
+ __add_prefix_tree_node_to_petri(
+ list(prefix_tree.children)[0], net, source, sink
+ )
+
+ return net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..231eb38e5e5f526094eaf4ec27233361475f1105
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.conversion.wf_net import variants, converter
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..4eca1b3ebc98e4b2e751d8971b89de2c55a8a38b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/converter.py
@@ -0,0 +1,39 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.conversion.wf_net.variants import to_process_tree, to_bpmn
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ TO_PROCESS_TREE = to_process_tree
+ TO_BPMN = to_bpmn
+
+
+DEFAULT_VARIANT = Variants.TO_PROCESS_TREE
+
+
+def apply(net, im, fm, variant=DEFAULT_VARIANT, parameters=None):
+ return exec_utils.get_variant(variant).apply(
+ net, im, fm, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7fe905dc5f2d4e75fdd36448b682de1f4c1f678
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.conversion.wf_net.variants import to_process_tree, to_bpmn
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_bpmn.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_bpmn.py
new file mode 100644
index 0000000000000000000000000000000000000000..13646da7b96cf62a7f6cfa5d2e6d3c9f804d40ef
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_bpmn.py
@@ -0,0 +1,126 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+def apply(net, im, fm, parameters=None):
+ """
+ Converts an accepting Petri net into a BPMN diagram
+
+ Parameters
+ --------------
+ accepting_petri_net
+ Accepting Petri net (list containing net + im + fm)
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ bpmn_graph
+ BPMN diagram
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.objects.bpmn.obj import BPMN
+ from pm4py.objects.bpmn.util import reduction
+
+ bpmn_graph = BPMN()
+
+ entering_dictio = {}
+ exiting_dictio = {}
+
+ for place in net.places:
+ node = BPMN.ExclusiveGateway()
+ bpmn_graph.add_node(node)
+ entering_dictio[place] = node
+ exiting_dictio[place] = node
+
+ for trans in net.transitions:
+ if trans.label is None:
+ if len(trans.in_arcs) > 1:
+ node = BPMN.ParallelGateway(
+ gateway_direction=BPMN.Gateway.Direction.CONVERGING
+ )
+ elif len(trans.out_arcs) > 1:
+ node = BPMN.ParallelGateway(
+ gateway_direction=BPMN.Gateway.Direction.DIVERGING
+ )
+ else:
+ node = BPMN.ExclusiveGateway(
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED
+ )
+ bpmn_graph.add_node(node)
+ entering_dictio[trans] = node
+ exiting_dictio[trans] = node
+ else:
+ if len(trans.in_arcs) > 1:
+ entering_node = BPMN.ParallelGateway(
+ gateway_direction=BPMN.Gateway.Direction.CONVERGING
+ )
+ else:
+ entering_node = BPMN.ExclusiveGateway(
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED
+ )
+
+ if len(trans.out_arcs) > 1:
+ exiting_node = BPMN.ParallelGateway(
+ gateway_direction=BPMN.Gateway.Direction.DIVERGING
+ )
+ else:
+ exiting_node = BPMN.ExclusiveGateway(
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED
+ )
+
+ task = BPMN.Task(name=trans.label)
+ bpmn_graph.add_node(task)
+
+ bpmn_graph.add_flow(BPMN.SequenceFlow(entering_node, task))
+ bpmn_graph.add_flow(BPMN.SequenceFlow(task, exiting_node))
+
+ entering_dictio[trans] = entering_node
+ exiting_dictio[trans] = exiting_node
+
+ for arc in net.arcs:
+ bpmn_graph.add_flow(
+ BPMN.SequenceFlow(
+ exiting_dictio[arc.source], entering_dictio[arc.target]
+ )
+ )
+
+ start_node = BPMN.StartEvent(name="start", isInterrupting=True)
+ end_node = BPMN.NormalEndEvent(name="end")
+ bpmn_graph.add_node(start_node)
+ bpmn_graph.add_node(end_node)
+ for place in im:
+ bpmn_graph.add_flow(
+ BPMN.SequenceFlow(start_node, entering_dictio[place])
+ )
+ for place in fm:
+ bpmn_graph.add_flow(BPMN.SequenceFlow(exiting_dictio[place], end_node))
+
+ bpmn_graph = reduction.apply(bpmn_graph)
+
+ for node in bpmn_graph.get_nodes():
+ node.set_process(bpmn_graph.get_process_id())
+
+ for edge in bpmn_graph.get_flows():
+ edge.set_process(bpmn_graph.get_process_id())
+
+ return bpmn_graph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_powl.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_powl.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3b02b488afcf88e4a15523ba32c212b902667a0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_powl.py
@@ -0,0 +1,695 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+# ========= Imports =========
+from copy import copy
+from itertools import combinations
+from collections import deque
+from typing import List, Set, Union
+
+from pm4py import PetriNet
+from pm4py.objects.petri_net.utils import petri_utils as pn_util
+from pm4py.algo.analysis.workflow_net import algorithm as wf_eval
+from pm4py.objects.powl.BinaryRelation import BinaryRelation
+from pm4py.objects.powl.obj import OperatorPOWL, POWL, Operator, StrictPartialOrder, Transition, SilentTransition
+
+
+# ========= Utility Functions =========
+def id_generator():
+ count = 1
+ while True:
+ yield f"id{count}"
+ count += 1
+
+
+def is_silent(transition) -> bool:
+ return transition.label is None
+
+
+def add_arc_from_to(source: Union[PetriNet.Place, PetriNet.Transition],
+ target: Union[PetriNet.Transition, PetriNet.Place],
+ net: PetriNet):
+ arc = PetriNet.Arc(source, target)
+ net.arcs.add(arc)
+ source.out_arcs.add(arc)
+ target.in_arcs.add(arc)
+
+
+def clone_place(net: PetriNet, place, node_map: dict):
+ cloned_place = PetriNet.Place(f"{place.name}_cloned")
+ net.places.add(cloned_place)
+ node_map[place] = cloned_place
+ return cloned_place
+
+
+def clone_transition(net: PetriNet, transition, node_map: dict):
+ cloned_transition = PetriNet.Transition(f"{transition.name}_cloned", transition.label)
+ net.transitions.add(cloned_transition)
+ node_map[transition] = cloned_transition
+ return cloned_transition
+
+
+def pn_transition_to_powl(transition: PetriNet.Transition) -> Transition:
+ label = transition.label
+ if label:
+ return Transition(label=label)
+ else:
+ return SilentTransition()
+
+
+def locally_identical(p1, p2, transitions):
+ pre1 = pn_util.pre_set(p1) & transitions
+ pre2 = pn_util.pre_set(p2) & transitions
+ post1 = pn_util.post_set(p1) & transitions
+ post2 = pn_util.post_set(p2) & transitions
+ return pre1 == pre2 and post1 == post2
+
+
+# ========= Graph & Subnet Functions =========
+def get_simplified_reachability_graph(net: PetriNet):
+ graph = {node: set() for node in net.transitions}
+ for start_node in graph.keys():
+ reachable = set()
+ queue = deque()
+ queue.append(start_node)
+ while queue:
+ node = queue.popleft()
+ if node not in reachable:
+ reachable.add(node)
+ successors = pn_util.post_set(node)
+ queue.extend(successors)
+ graph[start_node].update(reachable)
+ return graph
+
+
+def get_reachable_transitions_from_place_to_another(start_place: PetriNet.Place,
+ end_place: PetriNet.Place):
+ visited = set()
+ queue = deque()
+ queue.append(start_place)
+ while queue:
+ node = queue.popleft()
+ if node not in visited:
+ visited.add(node)
+ if node == end_place:
+ continue
+ successors = pn_util.post_set(node)
+ queue.extend(successors)
+ visited = {node for node in visited if isinstance(node, PetriNet.Transition)}
+ return visited
+
+
+def clone_subnet(net: PetriNet, subnet_transitions: Set[PetriNet.Transition],
+ start_place: PetriNet.Place, end_place: PetriNet.Place):
+ subnet_net = PetriNet(f"Subnet_{next(id_generator())}")
+ node_map = {}
+
+ # Clone transitions
+ for node in subnet_transitions:
+ clone_transition(subnet_net, node, node_map)
+
+ # Add arcs and remaining places of the subnet
+ for arc in net.arcs:
+ source = arc.source
+ target = arc.target
+ if source in subnet_transitions or target in subnet_transitions:
+ if source in node_map:
+ cloned_source = node_map[source]
+ else:
+ cloned_source = clone_place(subnet_net, source, node_map)
+ if target in node_map:
+ cloned_target = node_map[target]
+ else:
+ cloned_target = clone_place(subnet_net, target, node_map)
+ add_arc_from_to(cloned_source, cloned_target, subnet_net)
+
+ mapped_start_place = node_map[start_place]
+ mapped_end_place = node_map[end_place]
+
+ return subnet_net, mapped_start_place, mapped_end_place
+
+
+def apply_partial_order_projection(net: PetriNet, subnet_transitions: Set[PetriNet.Transition],
+ start_places: Set[PetriNet.Place], end_places: Set[PetriNet.Place]):
+ subnet_net = PetriNet(f"Subnet_{next(id_generator())}")
+ node_map = {}
+
+ # Clone transitions in the subnet
+ for node in subnet_transitions:
+ clone_transition(subnet_net, node, node_map)
+
+ list_start_places = list(start_places)
+ old_start = list_start_places[0]
+ for place in list_start_places[1:]:
+ if not locally_identical(place, old_start, subnet_transitions):
+ raise Exception("Unique local start property is violated!")
+ new_start_place = clone_place(subnet_net, old_start, node_map)
+ node_map[old_start] = new_start_place
+
+ if start_places == end_places:
+ new_end_place = new_start_place
+ else:
+ list_end_places = list(end_places)
+ old_end = list_end_places[0]
+ for place in list_end_places[1:]:
+ if not locally_identical(place, old_end, subnet_transitions):
+ raise Exception("Unique local end property is violated!")
+ new_end_place = clone_place(subnet_net, old_end, node_map)
+ node_map[old_end] = new_end_place
+
+ # Add arcs and remaining places of the subnet
+ for arc in net.arcs:
+ source = arc.source
+ target = arc.target
+ if source in subnet_transitions or target in subnet_transitions:
+ if source in node_map:
+ cloned_source = node_map[source]
+ else:
+ if source in start_places or source in end_places:
+ continue
+ cloned_source = clone_place(subnet_net, source, node_map)
+ if target in node_map:
+ cloned_target = node_map[target]
+ else:
+ if target in start_places or target in end_places:
+ continue
+ cloned_target = clone_place(subnet_net, target, node_map)
+ add_arc_from_to(cloned_source, cloned_target, subnet_net)
+
+ return subnet_net, new_start_place, new_end_place
+
+
+# ========= Mining Functions =========
+def mine_base_case(net: PetriNet):
+ if len(net.transitions) == 1 and len(net.places) == 2 == len(net.arcs):
+ activity = list(net.transitions)[0]
+ powl_transition = pn_transition_to_powl(activity)
+ return powl_transition
+ return None
+
+
+def mine_self_loop(net: PetriNet, start_place: PetriNet.Place, end_place: PetriNet.Place):
+ if start_place == end_place:
+ place = start_place
+ place_copy = clone_place(net, place, {})
+ redo = copy(net.transitions)
+ out_arcs = place.out_arcs
+ for arc in list(out_arcs):
+ target = arc.target
+ pn_util.remove_arc(net, arc)
+ add_arc_from_to(place_copy, target, net)
+ do_transition = PetriNet.Transition(f"silent_do_{place.name}", None)
+ do = {do_transition}
+ net.transitions.add(do_transition)
+ add_arc_from_to(place, do_transition, net)
+ add_arc_from_to(do_transition, place_copy, net)
+ return do, redo, place, place_copy
+
+ return None
+
+
+def mine_loop(net: PetriNet, start_place: PetriNet.Place, end_place: PetriNet.Place):
+ redo_subnet_transitions = get_reachable_transitions_from_place_to_another(end_place, start_place)
+
+ if len(redo_subnet_transitions) == 0:
+ return None, None
+
+ do_subnet_transitions = get_reachable_transitions_from_place_to_another(start_place, end_place)
+
+ if len(do_subnet_transitions) == 0:
+ raise Exception("This should not be possible!")
+
+ if do_subnet_transitions & redo_subnet_transitions:
+ # This could happen if we have ->(..., Loop)
+ return None, None
+
+ if net.transitions != (do_subnet_transitions | redo_subnet_transitions):
+ raise Exception("Something went wrong!")
+
+ # A loop is detected: the set of transitions is partitioned into two disjoint, non-empty subsets (do and redo)
+ return do_subnet_transitions, redo_subnet_transitions
+
+
+def __combine_parts(
+ transitions_to_group_together: Set[PetriNet.Transition],
+ partition: List[Set[PetriNet.Transition]],
+):
+ new_partition = []
+ new_combined_group = set()
+
+ for part in partition:
+ if part & transitions_to_group_together:
+ new_combined_group.update(part)
+ else:
+ new_partition.append(part)
+
+ if new_combined_group:
+ new_partition.append(new_combined_group)
+
+ return new_partition
+
+
+def mine_xor(net: PetriNet, reachability_map):
+ choice_branches = [{t} for t in net.transitions]
+
+ for t1, t2 in combinations(net.transitions, 2):
+ if t1 in reachability_map[t2] or t2 in reachability_map[t1]:
+ new_branch = {t1, t2}
+ choice_branches = __combine_parts(new_branch, choice_branches)
+
+ if net.transitions != set().union(*choice_branches):
+ raise Exception("This should not happen!")
+
+ return choice_branches
+
+
+def mine_partial_order(net, end_place, reachability_map):
+ partition = [{t} for t in net.transitions]
+
+ for place in net.places:
+ out_size = len(place.out_arcs)
+ if out_size > 1 or (place == end_place and out_size > 0):
+ xor_branches = []
+ for start_transition in pn_util.post_set(place):
+ new_branch = {node for node in reachability_map[start_transition]
+ if isinstance(node, PetriNet.Transition)}
+ xor_branches.append(new_branch)
+ union_of_branches = set().union(*xor_branches)
+ if place == end_place:
+ not_in_every_branch = union_of_branches
+ else:
+ intersection_of_branches = set.intersection(*xor_branches)
+ not_in_every_branch = union_of_branches - intersection_of_branches
+ if len(not_in_every_branch) > 1:
+ partition = __combine_parts(not_in_every_branch, partition)
+
+ return partition
+
+
+# ========= Preprocessing Functions =========
+def validate_workflow_net(net: PetriNet):
+ places_no_incoming = [p for p in net.places if not p.in_arcs]
+ if len(places_no_incoming) == 1:
+ start_place = places_no_incoming[0]
+ else:
+ raise Exception("Not a WF-net!")
+
+ places_no_outgoing = [p for p in net.places if not p.out_arcs]
+ if len(places_no_outgoing) == 1:
+ end_place = places_no_outgoing[0]
+ else:
+ raise Exception("Not a WF-net!")
+
+ if not wf_eval.apply(net):
+ raise Exception("Not a WF-net!")
+
+ return start_place, end_place
+
+
+def remove_initial_and_end_silent_activities(
+ net: PetriNet,
+ start_places: Set[PetriNet.Place],
+ end_places: Set[PetriNet.Place],
+):
+ change = True
+ while change and len(net.transitions) > 1:
+ change = False
+ if len(start_places) == 1:
+ start_place = list(start_places)[0]
+ if len(start_place.in_arcs) == 0 and len(start_place.out_arcs) == 1:
+ transition = list(start_place.out_arcs)[0].target
+ if len(transition.in_arcs) == 1 and is_silent(transition):
+ pn_util.remove_place(net, start_place)
+ start_places.remove(start_place)
+ next_places = list(pn_util.post_set(transition))
+ pn_util.remove_transition(net, transition)
+ for p in next_places:
+ start_places.add(p)
+ change = True
+
+ change = True
+ while change and len(net.transitions) > 1:
+ change = False
+ if len(end_places) == 1:
+ end_place = list(end_places)[0]
+ if len(end_place.in_arcs) == 1 and len(end_place.out_arcs) == 0:
+ transition = list(end_place.in_arcs)[0].source
+ if len(transition.out_arcs) == 1 and is_silent(transition):
+ pn_util.remove_transition(net, transition)
+ pn_util.remove_place(net, end_place)
+ end_places.remove(end_place)
+ prev_places = list(pn_util.pre_set(transition))
+ for p in prev_places:
+ end_places.add(p)
+ change = True
+
+ return start_places, end_places
+
+
+def __get_identical_place(
+ place: PetriNet.Place, places_set: Set[PetriNet.Place]
+):
+ for other in places_set:
+ if (pn_util.post_set(place) == pn_util.post_set(other)
+ and pn_util.pre_set(place) == pn_util.pre_set(other)):
+ return other
+ return None
+
+
+def __remove_and_replace_if_present(
+ old_p: PetriNet.Place,
+ new_p: PetriNet.Place,
+ place_set: Set[PetriNet.Place],
+):
+ if old_p in place_set:
+ place_set.remove(old_p)
+ if new_p not in place_set:
+ place_set.add(new_p)
+ return place_set
+
+
+def remove_duplicated_places(
+ net: PetriNet,
+ start_places: Set[PetriNet.Place],
+ end_places: Set[PetriNet.Place],
+):
+ all_places = list(net.places)
+ places_to_keep = {all_places[0]}
+ for place in all_places[1:]:
+ other = __get_identical_place(place, places_to_keep)
+ if other:
+ pn_util.remove_place(net, place)
+ start_places = __remove_and_replace_if_present(place, other, start_places)
+ end_places = __remove_and_replace_if_present(place, other, end_places)
+ else:
+ places_to_keep.add(place)
+
+ return start_places, end_places
+
+
+def remove_unconnected_places(
+ net: PetriNet,
+ start_places: Set[PetriNet.Place],
+ end_places: Set[PetriNet.Place],
+):
+ places = list(net.places)
+ for p in places:
+ if len(p.in_arcs) == 0 and len(p.out_arcs) == 0:
+ pn_util.remove_place(net, p)
+ start_places.remove(p)
+ end_places.remove(p)
+ return start_places, end_places
+
+
+def preprocess(net: PetriNet):
+ all_places = net.places
+ for p1, p2 in combinations(all_places, 2):
+ pre1 = pn_util.pre_set(p1)
+ pre2 = pn_util.pre_set(p2)
+ post1 = pn_util.post_set(p1)
+ post2 = pn_util.post_set(p2)
+
+ if (pre1 == pre2) and (post1 == post2):
+ pn_util.remove_place(net, p2)
+ return preprocess(net)
+
+ if pre1 == pre2:
+ common_post = post1 & post2
+ if len(pre1) > 1 or len(common_post) > 0:
+ new_place = PetriNet.Place(f"place_{next(id_generator())}")
+ net.places.add(new_place)
+
+ for transition in pre1:
+ add_arc_from_to(transition, new_place, net)
+ arcs_to_remove = p1.in_arcs | p2.in_arcs
+ for arc in arcs_to_remove:
+ pn_util.remove_arc(net, arc)
+
+ for transition in common_post:
+ add_arc_from_to(new_place, transition, net)
+ out_arcs = p1.out_arcs | p2.out_arcs
+ for arc in out_arcs:
+ if arc.target in common_post:
+ pn_util.remove_arc(net, arc)
+
+ new_silent = PetriNet.Transition(f"silent_transition_{next(id_generator())}", None)
+ net.transitions.add(new_silent)
+ add_arc_from_to(new_place, new_silent, net)
+ add_arc_from_to(new_silent, p1, net)
+ add_arc_from_to(new_silent, p2, net)
+ return preprocess(net)
+
+ if post1 == post2:
+ common_pre = pre1 & pre2
+ if len(post1) > 1 or len(common_pre) > 0:
+ new_place = PetriNet.Place(f"place_{next(id_generator())}")
+ net.places.add(new_place)
+
+ for transition in post1:
+ add_arc_from_to(new_place, transition, net)
+ arcs_to_remove = p1.out_arcs | p2.out_arcs
+ for arc in arcs_to_remove:
+ pn_util.remove_arc(net, arc)
+
+ for transition in common_pre:
+ add_arc_from_to(transition, new_place, net)
+ in_arcs = p1.in_arcs | p2.in_arcs
+ for arc in in_arcs:
+ if arc.source in common_pre:
+ pn_util.remove_arc(net, arc)
+
+ new_silent = PetriNet.Transition(f"silent_transition_{next(id_generator())}", None)
+ net.transitions.add(new_silent)
+ add_arc_from_to(p1, new_silent, net)
+ add_arc_from_to(p2, new_silent, net)
+ add_arc_from_to(new_silent, new_place, net)
+
+ return preprocess(net)
+
+ return net
+
+
+def __redirect_shared_arcs_to_new_place(
+ net, places: List[PetriNet.Place], new_place_id
+):
+ shared_pre_set = set(pn_util.pre_set(places[0]))
+ for p in places[1:]:
+ shared_pre_set &= set(pn_util.pre_set(p))
+
+ shared_post_set = set(pn_util.post_set(places[0]))
+ for p in places[1:]:
+ shared_post_set &= set(pn_util.post_set(p))
+
+ arcs = list(net.arcs)
+ for arc in arcs:
+ source = arc.source
+ target = arc.target
+ if (source in shared_pre_set and target in places) or (source in places and target in shared_post_set):
+ pn_util.remove_arc(net, arc)
+
+ if len(shared_post_set) > 0 or len(shared_pre_set) > 0:
+ new_place = PetriNet.Place(new_place_id)
+ net.places.add(new_place)
+
+ for node in shared_pre_set:
+ add_arc_from_to(node, new_place, net)
+ for node in shared_post_set:
+ add_arc_from_to(new_place, node, net)
+ return new_place
+ else:
+ return None
+
+
+def add_new_start_and_end_if_needed(
+ net,
+ start_places: Set[PetriNet.Place],
+ end_places: Set[PetriNet.Place],
+):
+ if len(start_places) == 0 or len(end_places) == 0:
+ raise Exception("This should not happen!")
+
+ if len(start_places) > 1:
+ new_source_id = f"source_{next(id_generator())}"
+ new_source = __redirect_shared_arcs_to_new_place(net, list(start_places), new_source_id)
+ if new_source:
+ new_silent = PetriNet.Transition(f"silent_start_{next(id_generator())}", None)
+ net.transitions.add(new_silent)
+ for p in start_places:
+ add_arc_from_to(new_silent, p, net)
+ add_arc_from_to(new_source, new_silent, net)
+ start_places = {new_source}
+
+ if len(end_places) > 1:
+ new_sink_id = f"sink_{next(id_generator())}"
+ new_sink = __redirect_shared_arcs_to_new_place(net, list(end_places), new_sink_id)
+ if new_sink:
+ new_silent = PetriNet.Transition(f"silent_end_{next(id_generator())}", None)
+ net.transitions.add(new_silent)
+ for p in end_places:
+ add_arc_from_to(p, new_silent, net)
+ add_arc_from_to(new_silent, new_sink, net)
+ end_places = {new_sink}
+
+ return start_places, end_places
+
+
+# ========= Translation Functions =========
+def __create_sub_powl_model(
+ net,
+ branch: Set[PetriNet.Transition],
+ start_place: PetriNet.Place,
+ end_place: PetriNet.Place,
+):
+ subnet, subnet_start_place, subnet_end_place = clone_subnet(net, branch, start_place, end_place)
+ powl = __translate_petri_to_powl(subnet, subnet_start_place, subnet_end_place)
+ return powl
+
+
+def __translate_xor(net: PetriNet, start_place: PetriNet.Place, end_place: PetriNet.Place,
+ choice_branches: List[Set[PetriNet.Transition]]):
+ children = []
+ for branch in choice_branches:
+ child_powl = __create_sub_powl_model(net, branch, start_place, end_place)
+ children.append(child_powl)
+ xor_operator = OperatorPOWL(operator=Operator.XOR, children=children)
+ return xor_operator
+
+
+def __translate_loop(net: PetriNet, do_nodes, redo_nodes,
+ start_place: PetriNet.Place, end_place: PetriNet.Place) -> OperatorPOWL:
+ do_powl = __create_sub_powl_model(net, do_nodes, start_place, end_place)
+ redo_powl = __create_sub_powl_model(net, redo_nodes, end_place, start_place)
+ loop_operator = OperatorPOWL(operator=Operator.LOOP, children=[do_powl, redo_powl])
+ return loop_operator
+
+
+def __validate_partial_order(po: StrictPartialOrder):
+ po.order.add_transitive_edges()
+ if po.order.is_irreflexive():
+ return po
+ else:
+ raise Exception("Conversion failed!")
+
+
+def __translate_partial_order(net, transition_groups, i_place: PetriNet.Place, f_place: PetriNet.Place):
+ groups = [tuple(g) for g in transition_groups]
+ transition_to_group_map = {transition: g for g in groups for transition in g}
+
+ group_start_places = {g: set() for g in groups}
+ group_end_places = {g: set() for g in groups}
+ temp_po = BinaryRelation(groups)
+
+ for p in net.places:
+ sources = {arc.source for arc in p.in_arcs}
+ targets = {arc.target for arc in p.out_arcs}
+ source_groups = {transition_to_group_map[t] for t in sources}
+ target_groups = {transition_to_group_map[t] for t in targets}
+
+ # A shared place cannot merge tokens from independent POWL children or
+ # let them compete for one token. Groups on both sides may loop locally;
+ # only the external producers and consumers must be unique.
+ if len(source_groups - target_groups) > 1:
+ raise ValueError(f"Invalid partial order: place {p} has multiple producer groups!")
+ if len(target_groups - source_groups) > 1:
+ raise ValueError(f"Invalid partial order: place {p} has multiple consumer groups!")
+
+ if p == i_place:
+ for t in targets:
+ group_start_places[transition_to_group_map[t]].add(p)
+ if p == f_place:
+ for t in sources:
+ group_end_places[transition_to_group_map[t]].add(p)
+
+ for t1 in sources:
+ group_1 = transition_to_group_map[t1]
+ for t2 in targets:
+ group_2 = transition_to_group_map[t2]
+ if group_1 != group_2:
+ temp_po.add_edge(group_1, group_2)
+ group_end_places[group_1].add(p)
+ group_start_places[group_2].add(p)
+
+ group_to_powl_map = {}
+ children = []
+ for group in groups:
+ subnet, subnet_start_place, subnet_end_place = apply_partial_order_projection(net, set(group),
+ group_start_places[group],
+ group_end_places[group])
+ child = __translate_petri_to_powl(subnet, subnet_start_place, subnet_end_place)
+ group_to_powl_map[group] = child
+ children.append(child)
+
+ po = StrictPartialOrder(children)
+ for source in temp_po.nodes:
+ new_source = group_to_powl_map[source]
+ for target in temp_po.nodes:
+ if temp_po.is_edge(source, target):
+ new_target = group_to_powl_map[target]
+ po.order.add_edge(new_source, new_target)
+
+ po = __validate_partial_order(po)
+ return po
+
+
+def __translate_petri_to_powl(net: PetriNet, start_place: PetriNet.Place, end_place: PetriNet.Place) -> POWL:
+ base_case = mine_base_case(net)
+ if base_case:
+ return base_case
+
+ reachability_map = get_simplified_reachability_graph(net)
+
+ choice_branches = mine_xor(net, reachability_map)
+ if len(choice_branches) > 1:
+ return __translate_xor(net, start_place, end_place, choice_branches)
+
+ self_loop = mine_self_loop(net, start_place, end_place)
+ if self_loop:
+ return __translate_loop(net, self_loop[0], self_loop[1], self_loop[2], self_loop[3])
+
+ do, redo = mine_loop(net, start_place, end_place)
+ if do and redo:
+ return __translate_loop(net, do, redo, start_place, end_place)
+
+ partitions = mine_partial_order(net, end_place, reachability_map)
+ if len(partitions) > 1:
+ return __translate_partial_order(net, partitions, start_place, end_place)
+
+ raise Exception(f"Failed to detect a POWL structure over the following transitions: {net.transitions}")
+
+
+# ========= Main Function =========
+def apply(net: PetriNet) -> POWL:
+ """
+ Convert a Petri net to a POWL model, implementing the approach proposed in:
+
+ Kourani, Humam, Gyunam Park, and Wil van der Aalst. "Translating Workflow Nets into the
+ Partially Ordered Workflow Language." arXiv preprint arXiv:2503.20363 (2025).
+
+ Parameters:
+ - net: PetriNet
+
+ Returns:
+ - POWL model
+ """
+ start_place, end_place = validate_workflow_net(net)
+ net = preprocess(net)
+ res = __translate_petri_to_powl(net, start_place, end_place)
+ return res
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_process_tree.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_process_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..7439acdaa62d0a75758de5ad41624005fcb3be87
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/conversion/wf_net/variants/to_process_tree.py
@@ -0,0 +1,409 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import datetime
+import itertools
+import uuid
+from copy import deepcopy
+from enum import Enum
+
+from pm4py.objects.petri_net.utils import petri_utils as pn_util
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.process_tree import obj as pt_operator
+from pm4py.objects.process_tree.utils import generic as pt_util
+from pm4py.objects.process_tree.utils.generic import tree_sort
+from pm4py.util import exec_utils
+from pm4py.objects.process_tree.utils.generic import parse
+
+TRANSITION_PREFIX = str(uuid.uuid4())
+
+
+class Parameters(Enum):
+ DEBUG = "debug"
+ FOLD = "fold"
+
+
+def generate_label_for_transition(t):
+ return 'tau' if t.label is None else '\'' + t.label.replace("'", "") + '\'' if not t.name.startswith(
+ TRANSITION_PREFIX) else t.label
+
+
+def generate_new_binary_transition(t1, t2, operator, net):
+ t = PetriNet.Transition(TRANSITION_PREFIX + str(datetime.datetime.now()))
+ t.label = (
+ str(operator)
+ + "("
+ + generate_label_for_transition(t1)
+ + ", "
+ + generate_label_for_transition(t2)
+ + ")"
+ )
+ return t
+
+
+def loop_requirement(t1, t2):
+ if t1 == t2:
+ return False
+ for p in pn_util.pre_set(t2):
+ if (
+ len(pn_util.pre_set(p)) != 1
+ ): # check that the preset of the t2 preset has one entry
+ return False
+ if t1 not in pn_util.pre_set(
+ p
+ ): # check that t1 is the unique way to mark the preset of t2
+ return False
+ for p in pn_util.post_set(t2):
+ if len(pn_util.post_set(p)) != 1:
+ return False
+ if t1 not in pn_util.post_set(p):
+ return False
+ for p in pn_util.pre_set(t1):
+ if len(pn_util.post_set(p)) != 1:
+ return False
+ if t1 not in pn_util.post_set(p):
+ return False
+ if t2 not in pn_util.pre_set(p): # t2 has to enable t1!
+ return False
+ for p in pn_util.post_set(t1):
+ if (
+ len(pn_util.pre_set(p)) != 1
+ ): # check that the preset of the t2 preset has one entry
+ return False
+ if t1 not in pn_util.pre_set(
+ p
+ ): # check that t1 is the unique way to mark the preset of t2
+ return False
+ if t2 not in pn_util.post_set(p):
+ return False
+ return True
+
+
+def binary_loop_detection(net):
+ c1 = None
+ c2 = None
+ for t1, t2 in itertools.product(net.transitions, net.transitions):
+ if loop_requirement(t1, t2):
+ c1 = t1
+ c2 = t2
+ break
+ if c1 is not None and c2 is not None:
+ t = generate_new_binary_transition(
+ c1, c2, pt_operator.Operator.LOOP, net
+ )
+ net.transitions.add(t)
+ # reduce
+ for a in c1.in_arcs:
+ pn_util.add_arc_from_to(a.source, t, net)
+ for a in c1.out_arcs:
+ pn_util.add_arc_from_to(t, a.target, net)
+ pn_util.remove_transition(net, c1)
+ pn_util.remove_transition(net, c2)
+ return net
+ return None
+
+
+def concurrent_requirement(t1, t2):
+ if t1 == t2: # check if transitions different
+ return False
+ if (
+ len(pn_util.pre_set(t1)) == 0
+ or len(pn_util.post_set(t1)) == 0
+ or len(pn_util.pre_set(t2)) == 0
+ or len(pn_util.post_set(t2)) == 0
+ ): # not possible in WF-net, just checking...
+ return False
+ pre_pre = set()
+ post_post = set()
+ for p in pn_util.pre_set(t1): # check if t1 is unique post of its preset
+ pre_pre = set.union(pre_pre, pn_util.pre_set(p))
+ if len(pn_util.post_set(p)) > 1 or t1 not in pn_util.post_set(p):
+ return False
+ for p in pn_util.post_set(t1): # check if t1 is unique pre of its postset
+ post_post = set.union(post_post, pn_util.post_set(p))
+ if len(pn_util.pre_set(p)) > 1 or t1 not in pn_util.pre_set(p):
+ return False
+ for p in pn_util.pre_set(t2): # check if t2 is unique post of its preset
+ pre_pre = set.union(pre_pre, pn_util.pre_set(p))
+ if len(pn_util.post_set(p)) > 1 or t2 not in pn_util.post_set(p):
+ return False
+ for p in pn_util.post_set(t2): # check if t2 is unique pre of its postset
+ post_post = set.union(post_post, pn_util.post_set(p))
+ if len(pn_util.pre_set(p)) > 1 or t2 not in pn_util.pre_set(p):
+ return False
+ for p in set.union(
+ pn_util.pre_set(t1), pn_util.pre_set(t2)
+ ): # check if presets synchronize
+ for t in pre_pre:
+ if t not in pn_util.pre_set(p):
+ return False
+ for p in set.union(
+ pn_util.post_set(t1), pn_util.post_set(t2)
+ ): # check if postsets synchronize
+ for t in post_post:
+ if t not in pn_util.post_set(p):
+ return False
+ return True
+
+
+def binary_concurrency_detection(net):
+ c1 = None
+ c2 = None
+ for t1, t2 in itertools.product(net.transitions, net.transitions):
+ if concurrent_requirement(t1, t2):
+ c1 = t1
+ c2 = t2
+ break
+ if c1 is not None and c2 is not None:
+ t = generate_new_binary_transition(
+ c1, c2, pt_operator.Operator.PARALLEL, net
+ )
+ net.transitions.add(t)
+ # reduce
+ for a in c1.in_arcs:
+ pn_util.add_arc_from_to(a.source, t, net)
+ for a in c1.out_arcs:
+ pn_util.add_arc_from_to(t, a.target, net)
+ for a in c2.in_arcs:
+ pn_util.add_arc_from_to(a.source, t, net)
+ for a in c2.out_arcs:
+ pn_util.add_arc_from_to(t, a.target, net)
+ pn_util.remove_transition(net, c1)
+ pn_util.remove_transition(net, c2)
+ return net
+ return None
+
+
+def choice_requirement(t1, t2):
+ return (
+ t1 != t2
+ and pn_util.pre_set(t1) == pn_util.pre_set(t2)
+ and pn_util.post_set(t1) == pn_util.post_set(t2)
+ and len(pn_util.pre_set(t1)) > 0
+ and len(pn_util.post_set(t1)) > 0
+ )
+
+
+def binary_choice_detection(net):
+ c1 = None
+ c2 = None
+ for t1, t2 in itertools.product(net.transitions, net.transitions):
+ if choice_requirement(t1, t2):
+ c1 = t1
+ c2 = t2
+ break
+ if c1 is not None and c2 is not None:
+ t = generate_new_binary_transition(
+ c1, c2, pt_operator.Operator.XOR, net
+ )
+ net.transitions.add(t)
+ for a in c1.in_arcs:
+ pn_util.add_arc_from_to(a.source, t, net)
+ for a in c2.out_arcs:
+ pn_util.add_arc_from_to(t, a.target, net)
+ pn_util.remove_transition(net, c1)
+ pn_util.remove_transition(net, c2)
+ return net
+ return None
+
+
+def sequence_requirement(t1, t2):
+ if t1 == t2:
+ return False
+ if len(pn_util.pre_set(t2)) == 0:
+ return False
+ for p in pn_util.post_set(t1):
+ if len(pn_util.pre_set(p)) != 1 or len(pn_util.post_set(p)) != 1:
+ return False
+ if t1 not in pn_util.pre_set(p):
+ return False
+ if t2 not in pn_util.post_set(p):
+ return False
+ for p in pn_util.pre_set(t2):
+ if len(pn_util.pre_set(p)) != 1 or len(pn_util.post_set(p)) != 1:
+ return False
+ if t1 not in pn_util.pre_set(p):
+ return False
+ if t2 not in pn_util.post_set(
+ p
+ ): # redundant check, just to be sure...
+ return False
+ return True
+
+
+def binary_sequence_detection(net):
+ c1 = None
+ c2 = None
+ for t1, t2 in itertools.product(net.transitions, net.transitions):
+ if sequence_requirement(t1, t2):
+ c1 = t1
+ c2 = t2
+ break
+ if c1 is not None and c2 is not None:
+ t = generate_new_binary_transition(
+ c1, c2, pt_operator.Operator.SEQUENCE, net
+ )
+ net.transitions.add(t)
+ for a in c1.in_arcs:
+ pn_util.add_arc_from_to(a.source, t, net)
+ for a in c2.out_arcs:
+ pn_util.add_arc_from_to(t, a.target, net)
+ for p in pn_util.post_set(c1):
+ pn_util.remove_place(net, p)
+ pn_util.remove_transition(net, c1)
+ pn_util.remove_transition(net, c2)
+ return net
+ return None
+
+
+def __group_blocks_internal(net, parameters=None):
+ if parameters is None:
+ parameters = {}
+
+ if binary_choice_detection(net) is not None:
+ return True
+ elif binary_sequence_detection(net) is not None:
+ return True
+ elif binary_concurrency_detection(net) is not None:
+ return True
+ elif binary_loop_detection(net) is not None:
+ return True
+ else:
+ return False
+
+
+def __insert_dummy_invisibles(net, im, fm, ini_places, parameters=None):
+ if parameters is None:
+ parameters = {}
+
+ places = list(net.places)
+
+ for p in places:
+ if p.name in ini_places:
+ if p not in im and p not in fm:
+ source_trans = [x.source for x in p.in_arcs]
+ target_trans = [x.target for x in p.out_arcs]
+
+ pn_util.remove_place(net, p)
+ source_p = PetriNet.Place(str(uuid.uuid4()))
+ target_p = PetriNet.Place(str(uuid.uuid4()))
+ skip = PetriNet.Transition(str(uuid.uuid4()))
+ net.places.add(source_p)
+ net.places.add(target_p)
+ net.transitions.add(skip)
+
+ pn_util.add_arc_from_to(source_p, skip, net)
+ pn_util.add_arc_from_to(skip, target_p, net)
+
+ for t in source_trans:
+ pn_util.add_arc_from_to(t, source_p, net)
+ for t in target_trans:
+ pn_util.add_arc_from_to(target_p, t, net)
+
+
+def group_blocks_in_net(net, parameters=None):
+ """
+ Groups the blocks in the Petri net
+
+ Parameters
+ --------------
+ net
+ Petri net
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ grouped_net
+ Petri net (blocks are grouped according to the algorithm)
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.algo.analysis.workflow_net import algorithm as wf_eval
+
+ if not wf_eval.apply(net):
+ raise ValueError("The Petri net provided is not a WF-net")
+
+ net = deepcopy(net)
+ ini_places = set(x.name for x in net.places)
+
+ while len(net.transitions) > 1:
+ im = Marking({p: 1 for p in net.places if len(p.in_arcs) == 0})
+ fm = Marking({p: 1 for p in net.places if len(p.out_arcs) == 0})
+
+ if len(im) != 1 and len(fm) != 1:
+ # start/end conditions for block-structured nets
+ # do not hold
+ break
+
+ if __group_blocks_internal(net, parameters):
+ continue
+ else:
+ __insert_dummy_invisibles(net, im, fm, ini_places, parameters)
+ if __group_blocks_internal(net, parameters):
+ continue
+ else:
+ break
+
+ return net
+
+
+def apply(net, im, fm, parameters=None):
+ """
+ Transforms a WF-net to a process tree
+
+ Parameters
+ -------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+
+ Returns
+ -------------
+ tree
+ Process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ debug = exec_utils.get_param_value(Parameters.DEBUG, parameters, False)
+ fold = exec_utils.get_param_value(Parameters.FOLD, parameters, True)
+
+ grouped_net = group_blocks_in_net(net, parameters=parameters)
+
+ if debug:
+ from pm4py.visualization.petri_net import visualizer as pn_viz
+
+ pn_viz.view(pn_viz.apply(grouped_net, parameters={"format": "svg"}))
+ return grouped_net
+ else:
+ if len(grouped_net.transitions) == 1:
+ pt_str = list(grouped_net.transitions)[0].label
+ pt = parse(pt_str)
+ ret = pt_util.fold(pt) if fold else pt
+ tree_sort(ret)
+ return ret
+ else:
+ raise ValueError("Parsing of WF-net Failed")
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2387ac3bb5fbc9501534ee72a124ef6dcab5dd0f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.dfg import obj, importer, exporter, utils
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..79133fdb3fe0fd9dbd01c17a658a263b12101b3c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.dfg.exporter import variants, exporter
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..6755fb4326083f88cff88dd6d64a4c04c82770e2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/exporter.py
@@ -0,0 +1,80 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.dfg.exporter.variants import classic
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ CLASSIC = classic
+
+
+DEFAULT_VARIANT = Variants.CLASSIC
+
+
+def apply(dfg, output_path, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Exports a DFG
+
+ Parameters
+ ---------------
+ dfg
+ Directly-Follows Graph
+ output_path
+ Output path
+ variant
+ Variants of the exporter, possible values:
+ - Variants.CLASSIC: exporting to a .dfg file
+ parameters
+ Variant-specific parameters
+ """
+ exec_utils.get_variant(variant).apply(
+ dfg, output_path, parameters=parameters
+ )
+
+
+def serialize(dfg, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Serializes a DFG object into a binary string
+
+ Parameters
+ --------------
+ dfg
+ DFG
+ variant
+ Variants of the exporter, possible values:
+ - Variants.CLASSIC: exporting to a .dfg file
+ parameters
+ Variant-specific parameters
+
+ Returns
+ --------------
+ serialization
+ String that represents the DFG
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).export_as_string(
+ dfg, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..97e39b9148697468d35f612192eb320e7393baa5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.dfg.exporter.variants import classic
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/variants/classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..aecac488ec6a38672bfd3aebe6404fc687c26305
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/exporter/variants/classic.py
@@ -0,0 +1,159 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import exec_utils
+from enum import Enum
+from collections import Counter
+from pm4py.objects.dfg.utils import dfg_utils
+from pm4py.util import constants
+
+
+class Parameters(Enum):
+ START_ACTIVITIES = "start_activities"
+ END_ACTIVITIES = "end_activities"
+ ENCODING = "encoding"
+
+
+def export_line_by_line(dfg, parameters=None):
+ """
+ Exports a DFG into the .dfg format
+ - Line by line yielding
+
+ Parameters
+ --------------
+ dfg
+ DFG
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ line
+ Lines of the .dfg file (yielded one-by-one)
+ """
+ if parameters is None:
+ parameters = {}
+
+ start_activities = exec_utils.get_param_value(
+ Parameters.START_ACTIVITIES,
+ parameters,
+ Counter(dfg_utils.infer_start_activities(dfg)),
+ )
+ end_activities = exec_utils.get_param_value(
+ Parameters.END_ACTIVITIES,
+ parameters,
+ Counter(dfg_utils.infer_end_activities(dfg)),
+ )
+
+ if len(start_activities) == 0:
+ raise Exception(
+ "error: impossible to determine automatically the start activities from the DFG. Please specify them manually through the START_ACTIVITIES parameter"
+ )
+
+ if len(end_activities) == 0:
+ raise Exception(
+ "error: impossible to determine automatically the end activities from the DFG. Please specify them manually through the END_ACTIVITIES parameter"
+ )
+
+ activities = list(set(x[0] for x in dfg).union(set(x[1] for x in dfg)))
+
+ yield "%d\n" % (len(activities))
+ for act in activities:
+ yield "%s\n" % (act)
+
+ yield "%d\n" % (len(start_activities))
+ for act, count in start_activities.items():
+ yield "%dx%d\n" % (activities.index(act), count)
+
+ yield "%d\n" % (len(end_activities))
+ for act, count in end_activities.items():
+ yield "%dx%d\n" % (activities.index(act), count)
+
+ for el, count in dfg.items():
+ yield "%d>%dx%d\n" % (
+ activities.index(el[0]),
+ activities.index(el[1]),
+ count,
+ )
+
+
+def apply(dfg, output_path, parameters=None):
+ """
+ Exports a DFG into a .dfg file
+
+ Parameters
+ ----------------
+ dfg
+ Directly-Follows Graph
+ output_path
+ Output path
+ parameters
+ Parameters of the algorithm, including:
+ Parameters.START_ACTIVITIES => Start activities of the DFG
+ Parameters.END_ACTIVITIES => End activities of the DFG
+ Parameters.ENCODING => The encoding to be used (default: utf-8)
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ F = open(output_path, "wb")
+ for row in export_line_by_line(dfg, parameters=parameters):
+ F.write(row.encode(encoding))
+ F.close()
+
+
+def export_as_string(dfg, parameters=None):
+ """
+ Exports a DFG as a string
+
+ Parameters
+ --------------
+ dfg
+ Directly-Follows Graph
+ parameters
+ Parameters of the algorithm, including:
+ Parameters.START_ACTIVITIES => Start activities of the DFG
+ Parameters.END_ACTIVITIES => End activities of the DFG
+ Parameters.ENCODING => The encoding to be used (default: utf-8)
+
+ Returns
+ --------------
+ binary_string
+ Binary string
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ ret = []
+ for row in export_line_by_line(dfg, parameters=parameters):
+ ret.append(row)
+ ret = "".join(ret)
+ ret = ret.encode(encoding)
+
+ return ret
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/filtering/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/filtering/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/filtering/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/filtering/dfg_filtering.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/filtering/dfg_filtering.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed28ce8be927a06397ace1458ed8343fb36c68c9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/filtering/dfg_filtering.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.algo.filtering.dfg.dfg_filtering import *
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a880858c41e2856be2820e733104a43e1a6c08fc
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.dfg.importer import importer, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..52d34fec01b73094b985d4ab24a40e00f2d01b18
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/importer.py
@@ -0,0 +1,88 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.dfg.importer.variants import classic
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ CLASSIC = classic
+
+
+DEFAULT_VARIANT = Variants.CLASSIC
+
+
+def apply(file_path, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Import a DFG (along with the start and end activities)
+
+ Parameters
+ --------------
+ file_path
+ Path of the DFG file
+ variant
+ Variant of the importer, possible values:
+ - Variants.CLASSIC: importing from a .dfg file
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ dfg
+ DFG
+ start_activities
+ Start activities
+ end_activities
+ End activities
+ """
+ return exec_utils.get_variant(variant).apply(
+ file_path, parameters=parameters
+ )
+
+
+def deserialize(dfg_string, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Import a DFG from a binary/textual string
+
+ Parameters
+ --------------
+ dfg_string
+ DFG represented as a string in the .dfg format
+ variant
+ Variant of the importer, possible values:
+ - Variants.CLASSIC: importing from a .dfg file
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ dfg
+ DFG
+ start_activities
+ Start activities
+ end_activities
+ End activities
+ """
+ return exec_utils.get_variant(variant).import_dfg_from_string(
+ dfg_string, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..95bd9cb32e645b88dced2adff871a8269e3cbe47
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.dfg.importer.variants import classic
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/variants/classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e87f8f38c265caf6acfbdb825c09932d6c09868
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/importer/variants/classic.py
@@ -0,0 +1,167 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants, exec_utils
+from io import StringIO
+from enum import Enum
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def import_dfg_from_rows(rows, parameters=None):
+ """
+ Import a DFG (along with the start and end activities) from the rows of a .dfg file
+
+ Parameters
+ --------------
+ rows
+ Rows the DFG file
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ dfg
+ DFG
+ start_activities
+ Start activities
+ end_activities
+ End activities
+ """
+ if parameters is None:
+ parameters = {}
+
+ activities = []
+ start_activities = {}
+ end_activities = {}
+ dfg = {}
+
+ num_activities = int(rows[0])
+ i = 1
+ while i <= num_activities:
+ activities.append(rows[i].strip())
+ i = i + 1
+
+ num_sa = int(rows[i])
+
+ target = i + num_sa
+ i = i + 1
+
+ while i <= target:
+ act, count = rows[i].strip().split("x")
+ act = activities[int(act)]
+ count = int(count)
+ start_activities[act] = count
+ i = i + 1
+
+ num_ea = int(rows[i])
+
+ target = i + num_ea
+ i = i + 1
+
+ while i <= target:
+ act, count = rows[i].strip().split("x")
+ act = activities[int(act)]
+ count = int(count)
+ end_activities[act] = count
+ i = i + 1
+
+ while i < len(rows):
+ acts, count = rows[i].strip().split("x")
+ count = int(count)
+ a1, a2 = acts.split(">")
+ a1 = activities[int(a1)]
+ a2 = activities[int(a2)]
+ dfg[(a1, a2)] = count
+ i = i + 1
+
+ return dfg, start_activities, end_activities
+
+
+def apply(file_path, parameters=None):
+ """
+ Import a DFG (along with the start and end activities) from a .dfg file
+
+ Parameters
+ --------------
+ file_path
+ Path of the DFG file
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ dfg
+ DFG
+ start_activities
+ Start activities
+ end_activities
+ End activities
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ F = open(file_path, "r", encoding=encoding)
+ content = F.readlines()
+ F.close()
+
+ return import_dfg_from_rows(content, parameters=parameters)
+
+
+def import_dfg_from_string(dfg_string, parameters=None):
+ """
+ Import a DFG (along with the start and end activities) from a string representing a .dfg file
+
+ Parameters
+ --------------
+ dfg_string
+ String representing a .dfg file
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ dfg
+ DFG
+ start_activities
+ Start activities
+ end_activities
+ End activities
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ if type(dfg_string) is bytes:
+ dfg_string = dfg_string.decode(encoding)
+
+ return import_dfg_from_rows(
+ StringIO(dfg_string).readlines(), parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cd6bede5e8ee788366383b104f133746aa586a0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/obj.py
@@ -0,0 +1,86 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections import Counter
+from typing import Tuple, Any, Counter as TCounter
+
+
+class PerformanceDFG(dict):
+ """Dictionary-compatible performance DFG with calculation metadata.
+
+ Performance values are intentionally kept as a regular mapping for
+ backwards compatibility. The optional business-hour schedule lets
+ downstream consumers render those values using the same definition of a
+ working day that was used during discovery.
+ """
+
+ def __init__(self, *args, business_hour_slots=None, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.business_hour_slots = (
+ tuple(tuple(slot) for slot in business_hour_slots)
+ if business_hour_slots is not None
+ else None
+ )
+
+ def copy(self):
+ return type(self)(
+ self, business_hour_slots=self.business_hour_slots
+ )
+
+
+class DirectlyFollowsGraph:
+
+ def __init__(self, graph=None, start_activities=None, end_activities=None):
+ if graph is None:
+ graph = {}
+ if start_activities is None:
+ start_activities = {}
+ if end_activities is None:
+ end_activities = {}
+ self._graph = Counter(graph)
+ self._start_activities = Counter(start_activities)
+ self._end_activities = Counter(end_activities)
+
+ @property
+ def graph(self) -> TCounter[Tuple[Any, Any]]:
+ return self._graph
+
+ @property
+ def start_activities(self) -> TCounter[Any]:
+ return self._start_activities
+
+ @property
+ def end_activities(self) -> TCounter[Any]:
+ return self._end_activities
+
+ def __repr__(self):
+ return repr(self._graph)
+
+ def __str__(self):
+ return str(self._graph)
+
+ def __iter__(self):
+ yield dict(self.graph)
+ yield dict(self.start_activities)
+ yield dict(self.end_activities)
+
+
+DFG = DirectlyFollowsGraph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/log.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5f777757064a2d0e44b1ce1fdeddb7607806cbf
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/log.py
@@ -0,0 +1,24 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.algo.discovery.dfg.variants.freq_triples import *
+from pm4py.algo.discovery.dfg.variants.native import *
+from pm4py.algo.discovery.dfg.variants.performance import *
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/pandas.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/pandas.py
new file mode 100644
index 0000000000000000000000000000000000000000..a690753365a114a5252c4d5bb9dc0f70a17180b8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/retrieval/pandas.py
@@ -0,0 +1,23 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.algo.discovery.dfg.adapters.pandas.df_statistics import *
+from pm4py.algo.discovery.dfg.adapters.pandas.freq_triples import *
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/util.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9544bc0342e5060b866b5acbdea400bd6580881
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/util.py
@@ -0,0 +1,176 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections import Counter
+from typing import Dict, Collection, Any, Tuple
+
+from pm4py.util import nx_utils
+
+from pm4py.objects.dfg.obj import DFG
+
+
+def get_vertices(dfg: DFG) -> Collection[Any]:
+ """
+ Returns the vertices of the dfg
+
+ :param dfg: input directly follows graph
+
+ :rtype: ``Collection[Any]``
+ """
+ alphabet = set()
+ [alphabet.update({a, b}) for (a, b) in dfg.graph]
+ [alphabet.update({a}) for a in dfg.start_activities]
+ [alphabet.update({a}) for a in dfg.end_activities]
+ return alphabet
+
+
+def get_outgoing_arcs(dfg: DFG) -> Dict[Any, Dict[Any, int]]:
+ """
+ Returns the outgoing arcs of the provided DFG graph.
+ Returns a dictionary mapping each 'source' node onto its set of 'target' nodes and associated frequency.
+
+ :param dfg: ``DFG`` object
+
+ :rtype: ``Dict[str, Counter[str]]``
+
+ """
+ outgoing = {a: Counter() for a in get_vertices(dfg)}
+ for a, b in dfg.graph:
+ outgoing[a][b] = (
+ dfg.graph[(a, b)]
+ if b not in outgoing[a]
+ else outgoing[a][b] + dfg.graph[(a, b)]
+ )
+ return outgoing
+
+
+def get_incoming_arcs(dfg: DFG) -> Dict[Any, Dict[Any, int]]:
+ """
+ Returns the incoming arcs of the provided DFG graph.
+ Returns a dictionary mapping each 'target' node onto its set of 'source' nodes and associated frequency.
+
+ :param dfg: ``DFG`` object
+
+ :rtype: ``Dict[str, Counter[str]]``
+
+ """
+ incoming = {a: Counter() for a in get_vertices(dfg)}
+ for a, b in dfg.graph:
+ incoming[b][a] = (
+ dfg.graph[(a, b)]
+ if a not in incoming[b]
+ else incoming[b][a] + dfg.graph[(a, b)]
+ )
+ return incoming
+
+
+def get_source_vertices(dfg: DFG) -> Collection[Any]:
+ """
+ Gets source vertices from a Directly-Follows Graph.
+ Vertices are returned that have no incoming arcs
+
+ :param dfg: ``DFG`` object
+
+ :rtype: ``Collection[Any]``
+ """
+ starters = set()
+ incoming = get_incoming_arcs(dfg)
+ [starters.add(a) for a in incoming if len(incoming[a]) == 0]
+ return starters
+
+
+def get_sink_vertices(dfg: DFG) -> Collection[Any]:
+ """
+ Gets sink vertices from a Directly-Follows Graph.
+ Vertices are returned that have no outgoing arcs
+
+ :param dfg: ``DFG`` object
+
+ :rtype: ``Collection[Any]``
+ """
+ ends = set()
+ outgoing = get_outgoing_arcs(dfg)
+ [ends.add(a) for a in outgoing if len(outgoing[a]) == 0]
+ return ends
+
+
+def get_transitive_relations(
+ dfg: DFG,
+) -> Tuple[Dict[Any, Collection[Any]], Dict[Any, Collection[Any]]]:
+ """
+ Computes the full transitive relations in both directions (all
+ activities reachable from a given activity and all activities that can
+ reach the activity).
+
+ :param dfg: Directly Follows Graph (DFG) object.
+ :type dfg: dict
+
+ :return: A tuple containing:
+ - First argument: maps an activity to all other activities that are able to reach it ('transitive pre-set').
+ - Second argument: maps an activity to all other activities that it can reach ('transitive post-set').
+ :rtype: ``Tuple[Dict[Any, Collection[Any]], Dict[Any, Collection[Any]]]``
+ """
+ G = nx_utils.DiGraph()
+ alph = get_vertices(dfg)
+
+ for act in alph:
+ G.add_node(act)
+
+ for edge in dfg.graph:
+ G.add_edge(edge[0], edge[1])
+
+ pre = {}
+ post = {}
+
+ for a in alph:
+ pre[a] = nx_utils.ancestors(G, a)
+ post[a] = nx_utils.descendants(G, a)
+
+ return pre, post
+
+
+def get_vertex_frequencies(dfg: DFG) -> Dict[Any, int]:
+ """
+ Computes the number of times a vertex in the dfg is visited.
+ The number equals the number of occurrences in the underlying log and is computed by summing up the incoming
+ arc frequency and the number of starts in the vertex. The value is equal to the number of outgoing arcs combined
+ with the number of endings of the vertex.
+ """
+ c = Counter()
+ for v in get_vertices(dfg):
+ c[v] = 0
+ for a, b in dfg.graph:
+ c[a] += dfg.graph[(a, b)]
+ for a in dfg.start_activities:
+ c[a] += dfg.start_activities[a]
+ return c
+
+
+def as_nx_graph(dfg: DFG):
+ nx_graph = nx_utils.DiGraph()
+ nx_graph.add_nodes_from(get_vertices(dfg))
+ for a, b in dfg.graph:
+ nx_graph.add_edge(a, b)
+ return nx_graph
+
+
+def get_edges(dfg: DFG) -> Collection[Tuple[Any, Any]]:
+ return dfg.graph.keys()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6bf35743c382600be8d9714b055587de85c8928
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/utils/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.dfg.utils import dfg_utils
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/utils/dfg_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/utils/dfg_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4b18ef88436e927ab15e8f8b1eb2140b8113db7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/dfg/utils/dfg_utils.py
@@ -0,0 +1,1006 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections import Counter
+from copy import copy
+
+import numpy as np
+
+from pm4py.util import variants_util, nx_utils
+
+
+def get_outgoing_edges(dfg):
+ """
+ Gets outgoing edges of the provided DFG graph
+ """
+ outgoing = {}
+ for el in dfg:
+ if type(el[0]) is str:
+ if el[0] not in outgoing:
+ outgoing[el[0]] = {}
+ outgoing[el[0]][el[1]] = dfg[el]
+ else:
+ if el[0][0] not in outgoing:
+ outgoing[el[0][0]] = {}
+ outgoing[el[0][0]][el[0][1]] = el[1]
+ return outgoing
+
+
+def get_ingoing_edges(dfg):
+ """
+ Get ingoing edges of the provided DFG graph
+ """
+ ingoing = {}
+ for el in dfg:
+ if type(el[0]) is str:
+ if el[1] not in ingoing:
+ ingoing[el[1]] = {}
+ ingoing[el[1]][el[0]] = dfg[el]
+ else:
+ if el[0][1] not in ingoing:
+ ingoing[el[0][1]] = {}
+ ingoing[el[0][1]][el[0][0]] = el[1]
+ return ingoing
+
+
+def infer_start_activities(dfg):
+ """
+ Infer start activities from a Directly-Follows Graph
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows Graph
+
+ Returns
+ ----------
+ start_activities : list
+ Start activities in the log
+
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+
+ start_activities = []
+
+ for act in outgoing:
+ if act not in ingoing:
+ start_activities.append(act)
+
+ return start_activities
+
+
+def infer_end_activities(dfg):
+ """
+ Infer end activities from a Directly-Follows Graph
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows Graph
+
+ Returns
+ ----------
+ end_activities : list
+ End activities in the log
+
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+
+ end_activities = []
+
+ for act in ingoing:
+ if act not in outgoing:
+ end_activities.append(act)
+
+ return end_activities
+
+
+def infer_start_activities_from_prev_connections_and_current_dfg(
+ initial_dfg, dfg, activities, include_self=True
+):
+ """
+ Infer the start activities from the previous connections
+
+ Parameters
+ ----------
+ initial_dfg
+ Initial DFG
+ dfg
+ Directly-follows graph
+ activities
+ List of the activities contained in DFG
+
+ """
+ start_activities = set()
+ for el in initial_dfg:
+ if el[0][1] in activities and el[0][0] not in activities:
+ start_activities.add(el[0][1])
+ if include_self:
+ start_activities = start_activities.union(
+ set(infer_start_activities(dfg))
+ )
+ return start_activities
+
+
+def infer_end_activities_from_succ_connections_and_current_dfg(
+ initial_dfg, dfg, activities, include_self=True
+):
+ """
+ Infer the end activities from the previous connections
+
+ Parameters
+ ----------
+ initial_dfg
+ Initial DFG
+ dfg
+ Directly-follows graph
+ activities
+ List of the activities contained in DFG
+
+ """
+ end_activities = set()
+ for el in initial_dfg:
+ if el[0][0] in activities and el[0][1] not in activities:
+ end_activities.add(el[0][0])
+ if include_self:
+ end_activities = end_activities.union(set(infer_end_activities(dfg)))
+ return end_activities
+
+
+def get_outputs_of_outside_activities_going_to_start_activities(
+ initial_dfg, dfg, activities
+):
+ """
+ Get outputs of outside activities going to start activities
+
+ Parameters
+ ------------
+ initial_dfg
+ Initial DFG
+ dfg
+ Directly-follows graph
+ activities
+ Activities contained in the DFG
+
+ """
+ outputs = set()
+ start_activities = (
+ infer_start_activities_from_prev_connections_and_current_dfg(
+ initial_dfg, dfg, activities, include_self=False
+ )
+ )
+ outside_activities_going_to_start_activities = set()
+ for el in initial_dfg:
+ if el[0][0] not in activities and el[0][1] in start_activities:
+ outside_activities_going_to_start_activities.add(el[0][0])
+ for el in initial_dfg:
+ if (
+ el[0][0] in outside_activities_going_to_start_activities
+ and el[0][1] not in activities
+ ):
+ outputs.add(el[0][1])
+ outputs = outputs - outside_activities_going_to_start_activities
+ return outputs
+
+
+def get_inputs_of_outside_activities_reached_by_end_activities(
+ initial_dfg, dfg, activities
+):
+ """
+ Get inputs of outside activities going to start activities
+
+ Parameters
+ ----------
+ initial_dfg
+ Initial DFG
+ dfg
+ Directly-follows graph
+ activities
+ Activities contained in the DFG
+
+ """
+ inputs = set()
+ end_activities = (
+ infer_end_activities_from_succ_connections_and_current_dfg(
+ initial_dfg, dfg, activities, include_self=False
+ )
+ )
+ input_activities_reached_by_end_activities = set()
+ for el in initial_dfg:
+ if el[0][1] not in activities and el[0][0] in end_activities:
+ input_activities_reached_by_end_activities.add(el[0][1])
+ for el in initial_dfg:
+ if (
+ el[0][1] in input_activities_reached_by_end_activities
+ and el[0][0] not in activities
+ ):
+ inputs.add(el[0][0])
+ inputs = inputs - input_activities_reached_by_end_activities
+
+ return inputs
+
+
+def get_activities_from_dfg(dfg):
+ """
+ Get the list of attributes directly from DFG graph
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows graph
+
+ Returns
+ -----------
+ list_activities
+ List of activities that are present in the DFG graph
+
+ """
+ set_activities = set()
+ for el in dfg:
+ if type(el[0]) is str:
+ set_activities.add(el[0])
+ set_activities.add(el[1])
+ else:
+ set_activities.add(el[0][0])
+ set_activities.add(el[0][1])
+ list_activities = sorted(list(set_activities))
+
+ return list_activities
+
+
+def get_max_activity_count(dfg, act):
+ """
+ Get maximum count of an ingoing/outgoing edge related to an activity
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows graph
+ act
+ Activity
+
+ Returns
+ ------------
+ max_value
+ Maximum count of ingoing/outgoing edges to attributes
+
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+ max_value = -1
+ if act in ingoing:
+ for act2 in ingoing[act]:
+ if ingoing[act][act2] > max_value:
+ max_value = ingoing[act][act2]
+ if act in outgoing:
+ for act2 in outgoing[act]:
+ if outgoing[act][act2] > max_value:
+ max_value = outgoing[act][act2]
+ return max_value
+
+
+def sum_ingoutg_val_activ(dictio, activity):
+ """
+ Gets the sum of ingoing/outgoing values of an activity
+
+ Parameters
+ ----------
+ dictio
+ Dictionary
+ activity
+ Current examined activity
+
+ Returns
+ -----------
+ summ
+
+ """
+ summ = 0
+ for act2 in dictio[activity]:
+ summ += dictio[activity][act2]
+ return summ
+
+
+def max_occ_all_activ(dfg):
+ """
+ Get maximum ingoing/outgoing sum of values related to attributes in DFG graph
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+ max_value = -1
+
+ for act in ingoing:
+ summ = sum_ingoutg_val_activ(ingoing, act)
+ if summ > max_value:
+ max_value = summ
+
+ for act in outgoing:
+ summ = sum_ingoutg_val_activ(outgoing, act)
+ if summ > max_value:
+ max_value = summ
+
+ return max_value
+
+
+def max_occ_among_specif_activ(dfg, activities):
+ """
+ Get maximum ingoing/outgoing sum of values related to attributes in DFG graph
+ (here attributes to consider are specified)
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+ max_value = -1
+
+ for act in activities:
+ if act in ingoing:
+ summ = sum_ingoutg_val_activ(ingoing, act)
+ if summ > max_value:
+ max_value = summ
+ if act in outgoing:
+ summ = sum_ingoutg_val_activ(outgoing, act)
+ if summ > max_value:
+ max_value = summ
+
+ return max_value
+
+
+def sum_start_activities_count(dfg):
+ """
+ Gets the sum of start attributes count inside a DFG
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows graph
+
+ Returns
+ -------------
+ Sum of start attributes count
+
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+
+ sum_values = 0
+
+ for act in outgoing:
+ if act not in ingoing:
+ for act2 in outgoing[act]:
+ sum_values += outgoing[act][act2]
+
+ return sum_values
+
+
+def sum_end_activities_count(dfg):
+ """
+ Gets the sum of end attributes count inside a DFG
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows graph
+
+ Returns
+ -------------
+ Sum of start attributes count
+
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+
+ sum_values = 0
+
+ for act in ingoing:
+ if act not in outgoing:
+ for act2 in ingoing[act]:
+ sum_values += ingoing[act][act2]
+
+ return sum_values
+
+
+def sum_activities_count(dfg, activities, enable_halving=True):
+ """
+ Gets the sum of specified attributes count inside a DFG
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows graph
+ activities
+ Activities to sum
+ enable_halving
+ Halves the sum in specific occurrences
+
+ Returns
+ -------------
+ Sum of start attributes count
+
+ """
+ ingoing = get_ingoing_edges(dfg)
+ outgoing = get_outgoing_edges(dfg)
+
+ sum_values = 0
+
+ for act in activities:
+ if act in outgoing:
+ for act2 in outgoing[act]:
+ sum_values += outgoing[act][act2]
+ if act in ingoing:
+ for act2 in ingoing[act]:
+ sum_values += ingoing[act][act2]
+ if enable_halving:
+ if act in ingoing and act in outgoing:
+ sum_values = int(sum_values / 2)
+
+ return sum_values
+
+
+def filter_dfg_on_act(dfg, listact):
+ """
+ Filter a DFG graph on a list of attributes
+ (to produce a projected DFG graph)
+
+ Parameters
+ ----------
+ dfg
+ Current DFG graph
+ listact
+ List of attributes to filter on
+
+ """
+ new_dfg = []
+ for el in dfg:
+ if el[0][0] in listact and el[0][1] in listact:
+ new_dfg.append(el)
+ return new_dfg
+
+
+def negate(dfg):
+ """
+ Negate relationship in the DFG graph
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows graph
+
+ Returns
+ ----------
+ negated_dfg
+ Negated Directly-Follows graph (for parallel cut detection)
+
+ """
+ negated_dfg = []
+
+ outgoing = get_outgoing_edges(dfg)
+
+ for el in dfg:
+ if el[0][1] not in outgoing or el[0][0] not in outgoing[el[0][1]]:
+ negated_dfg.append(el)
+
+ return negated_dfg
+
+
+def get_activities_direction(dfg, activities):
+ """
+ Calculate activities direction (in a similar way to Heuristics Miner)
+
+ Parameters
+ ----------
+ dfg
+ Directly-follows graph
+ activities
+ (if provided) activities of the subtree
+
+ Returns
+ -----------
+ direction
+ Dictionary that contains for each direction a number that goes from -1 (all ingoing edges)
+ to 1 (all outgoing edges)
+
+ """
+
+ if activities is None:
+ activities = get_activities_from_dfg(dfg)
+
+ ingoing_list = get_ingoing_edges(dfg)
+ outgoing_list = get_outgoing_edges(dfg)
+
+ direction = {}
+ for act in activities:
+ outgoing = 0
+ ingoing = 0
+ if act in outgoing_list:
+ outgoing = sum(list(outgoing_list[act].values()))
+ if act in ingoing_list:
+ ingoing = sum(list(ingoing_list[act].values()))
+ dependency = (outgoing - ingoing) / (ingoing + outgoing + 1)
+ direction[act] = dependency
+ return direction
+
+
+def get_activities_dirlist(activities_direction):
+ """
+ Form an ordered list out of a dictionary that contains for each activity
+ the direction (going from -1 if all ingoing edges, to 1 if all outgoing edges)
+
+ Parameters
+ ----------
+ activities_direction
+ Dictionary that contains for each direction a number that goes from -1 (all ingoing edges)
+ to 1 (all outgoing edges)
+
+ Returns
+ ----------
+ dirlist
+ Sorted list of couples of activity plus the direction
+
+ """
+ dirlist = []
+ for act in activities_direction:
+ dirlist.append([act, activities_direction[act]])
+ dirlist = sorted(dirlist, key=lambda x: (x[1], x[0]), reverse=True)
+ return dirlist
+
+
+def get_activities_self_loop(dfg):
+ """
+ Get attributes that are in self-loop in this subtree
+
+ Parameters
+ ----------
+ dfg
+ Directly-follows graph
+
+ Returns
+ ----------
+ self_loop_act
+ Activities of the graph that are in subloop
+
+ """
+ self_loop_act = []
+
+ outgoing = get_outgoing_edges(dfg)
+
+ for act in outgoing:
+ if act in list(outgoing[act].keys()):
+ self_loop_act.append(act)
+ return self_loop_act
+
+
+def get_connected_components(
+ ingoing, outgoing, activities, force_insert_missing_acti=True
+):
+ """
+ Get connected components in the DFG graph
+
+ Parameters
+ ----------
+ ingoing
+ Ingoing attributes
+ outgoing
+ Outgoing attributes
+ activities
+ Activities to consider
+ force_insert_missing_acti
+ Force the insertion of a missing activity
+
+ """
+ activities_considered = set()
+
+ connected_components = []
+
+ for act in ingoing:
+ ingoing_act = set(ingoing[act].keys())
+ if act in outgoing:
+ ingoing_act = ingoing_act.union(set(outgoing[act].keys()))
+
+ ingoing_act.add(act)
+
+ if ingoing_act not in connected_components:
+ connected_components.append(ingoing_act)
+ activities_considered = activities_considered.union(
+ set(ingoing_act)
+ )
+
+ for act in outgoing:
+ if act not in ingoing:
+ outgoing_act = set(outgoing[act].keys())
+ outgoing_act.add(act)
+ if outgoing_act not in connected_components:
+ connected_components.append(outgoing_act)
+ activities_considered = activities_considered.union(
+ set(outgoing_act)
+ )
+
+ if force_insert_missing_acti:
+ for activ in activities:
+ if activ not in activities_considered:
+ added_set = set()
+ added_set.add(activ)
+ connected_components.append(added_set)
+ activities_considered.add(activ)
+
+ max_it = len(connected_components)
+ for it in range(max_it - 1):
+ something_changed = False
+
+ old_connected_components = copy(connected_components)
+ connected_components = []
+
+ for i in range(len(old_connected_components)):
+ conn1 = old_connected_components[i]
+
+ if conn1 is not None:
+ for j in range(i + 1, len(old_connected_components)):
+ conn2 = old_connected_components[j]
+ if conn2 is not None:
+ inte = conn1.intersection(conn2)
+
+ if len(inte) > 0:
+ conn1 = conn1.union(conn2)
+ something_changed = True
+ old_connected_components[j] = None
+
+ if conn1 is not None and conn1 not in connected_components:
+ connected_components.append(conn1)
+
+ if not something_changed:
+ break
+
+ if len(connected_components) == 0:
+ for activity in activities:
+ connected_components.append([activity])
+
+ return connected_components
+
+
+def add_to_most_probable_component(comps, act2, ingoing, outgoing):
+ """
+ Adds a lost component in parallel cut detection to the most probable component
+
+ Parameters
+ ----------
+ comps
+ Connected components
+ act2
+ Activity that has been missed
+ ingoing
+ Map of ingoing attributes
+ outgoing
+ Map of outgoing attributes
+
+ Returns
+ -------------
+ comps
+ Fixed connected components
+
+ """
+ sums = []
+ idx_max_sum = 0
+
+ for comp in comps:
+ summ = 0
+ for act1 in comp:
+ if act1 in ingoing and act2 in ingoing[act1]:
+ summ = summ + ingoing[act1][act2]
+ if act1 in outgoing and act2 in outgoing[act1]:
+ summ = summ + outgoing[act1][act2]
+ sums.append(summ)
+ if sums[-1] > sums[idx_max_sum]:
+ idx_max_sum = len(sums) - 1
+
+ comps[idx_max_sum].add(act2)
+
+ return comps
+
+
+def get_all_activities_connected_as_output_to_activity(dfg, activity):
+ """
+ Gets all the activities that are connected as output to a given activity
+
+ Parameters
+ ----------
+ dfg
+ Directly-follows graph
+ activity
+ Activity
+
+ Returns
+ -------------
+ all_activities
+ All activities connected as output to a given activity
+
+ """
+ all_activities = set()
+
+ for el in dfg:
+ if el[0][0] == activity:
+ all_activities.add(el[0][1])
+
+ return all_activities
+
+
+def get_all_activities_connected_as_input_to_activity(dfg, activity):
+ """
+ Gets all the activities that are connected as input to a given activity
+
+ Parameters
+ ----------
+ dfg
+ Directly-follows graph
+ activity
+ Activity
+
+ Returns
+ ------------
+ all_activities
+ All activities connected as input to a given activities
+
+ """
+ all_activities = set()
+ for el in dfg:
+ if el[0][1] == activity:
+ all_activities.add(el[0][0])
+ return all_activities
+
+
+def get_dfg_np_matrix(dfg):
+ """
+ Gets a Numpy matrix describing the DFG graph, along with a dictionary
+ making correspondence between indexes and activities names
+
+ Parameters
+ ----------
+ dfg
+ Directly-Follows graph
+
+ Returns
+ -------------
+ matrix
+ Matrix describing the DFG
+ index_corresp
+ Dictionary making correspondence between indexes and activities names
+
+ """
+ activities_in_dfg = get_activities_from_dfg(dfg)
+ matrix = np.zeros((len(activities_in_dfg), len(activities_in_dfg)))
+
+ for el in dfg:
+ if type(el[0]) is str:
+ # manage DFG expressed as dictionary (the key is a tuple)
+ first_el = el[0]
+ second_el = el[1]
+ n_occ = dfg[el]
+ else:
+ # manage DFG expressed as list of: ((act0, act1), count)
+ first_el = el[0][0]
+ second_el = el[0][1]
+ n_occ = el[1]
+ act_ind_0 = activities_in_dfg.index(first_el)
+ act_ind_1 = activities_in_dfg.index(second_el)
+ matrix[act_ind_0, act_ind_1] = n_occ
+
+ index_corresp = {}
+ for index, act in enumerate(activities_in_dfg):
+ index_corresp[index] = act
+
+ return matrix, index_corresp
+
+
+def get_dfg_sa_ea_act_from_variants(variants, parameters=None):
+ """
+ Gets the DFG, the start and end activities, and the activities
+ from the dictionary/set/list of variants in the log
+
+ Parameters
+ ----------
+ variants
+ Dictionary/set/list of variants
+ parameters
+ Parameters of the algorithm, including:
+
+ - variants_sep: the delimiter splitting activities in a variant
+
+ Returns
+ --------------
+ dfg
+ DFG
+ list_act
+ List of different activities
+ start_activities : dict
+ Start activities
+ end_activities : dict
+ End activities
+
+ """
+ if parameters is None:
+ parameters = {}
+ variants = set(
+ variants_util.get_activities_from_variant(v) for v in variants
+ )
+ dfg = dict(
+ Counter(
+ list((x[i], x[i + 1]) for x in variants for i in range(len(x) - 1))
+ )
+ )
+ list_act = list(set(y for x in variants for y in x))
+ start_activities = dict(Counter(x[0] for x in variants if x))
+ end_activities = dict(Counter(x[-1] for x in variants if x))
+ return dfg, list_act, start_activities, end_activities
+
+
+def transform_dfg_to_directed_nx_graph(dfg, activities=None):
+ """
+ Transform DFG to directed NetworkX graph
+
+ Returns
+ ------------
+ G
+ NetworkX digraph
+ nodes_map
+ Correspondence between digraph nodes and activities
+
+ """
+ if activities is None:
+ activities = get_activities_from_dfg(dfg)
+
+ G = nx_utils.DiGraph()
+ for act in activities:
+ G.add_node(act)
+ for el in dfg:
+ act1 = el[0][0]
+ act2 = el[0][1]
+ G.add_edge(act1, act2)
+ return G
+
+
+def get_successors(dfg, activities_model=None):
+ """
+ Gets the successors of any node of the DFG graph
+
+ Parameters
+ ----------
+ dfg
+ DFG
+ activities_model
+ Activities of the process model (if None, it is inferred from the process model)
+
+ Returns
+ -----------------
+ successors
+ Dictionary associating to each node all the descendants
+
+ """
+ if activities_model is None:
+ activities_model = set(x[0] for x in dfg).union(set(x[1] for x in dfg))
+ prev = {x: set() for x in activities_model}
+ curr = {x: set() for x in activities_model}
+ changed = {x: True for x in activities_model}
+ for x in dfg:
+ curr[x[0]].add(x[1])
+ sthing_diff = True
+ while sthing_diff:
+ sthing_diff = False
+ diff = {}
+ for x in prev:
+ if changed[x]:
+ this_diff = curr[x].difference(prev[x])
+ if this_diff:
+ sthing_diff = True
+ else:
+ changed[x] = False
+ diff[x] = this_diff
+ prev = copy(curr)
+ for x in diff:
+ if changed[x]:
+ for y in diff[x]:
+ curr[x] = curr[x].union(curr[y])
+ return curr
+
+
+def get_predecessors(dfg, activities_model=None):
+ """
+ Gets the predecessors of any node of the DFG graph
+
+ Parameters
+ ----------
+ dfg
+ DFG
+ activities_model
+ Activities of the process model (if None, it is inferred from the process model)
+
+ Returns
+ -----------------
+ predecessors
+ Dictionary associating to each node all the ascendants
+
+ """
+ if activities_model is None:
+ activities_model = set(x[0] for x in dfg).union(set(x[1] for x in dfg))
+ prev = {x: set() for x in activities_model}
+ curr = {x: set() for x in activities_model}
+ changed = {x: True for x in activities_model}
+ for x in dfg:
+ curr[x[1]].add(x[0])
+ sthing_diff = True
+ while sthing_diff:
+ sthing_diff = False
+ diff = {}
+ for x in prev:
+ if changed[x]:
+ this_diff = curr[x].difference(prev[x])
+ if this_diff:
+ sthing_diff = True
+ else:
+ changed[x] = False
+ diff[x] = this_diff
+ prev = copy(curr)
+ for x in diff:
+ if changed[x]:
+ for y in diff[x]:
+ curr[x] = curr[x].union(curr[y])
+ return curr
+
+
+def get_transitive_relations(dfg, alphabet):
+ """
+
+ Parameters
+ ----------
+ dfg
+ directly follows relation (counter describing activity pairs)
+
+ Returns
+ -------
+ tuple with two dicts.
+ first argument maps an activit on all other activities that are able to reach the activity ('transitive pre set')
+ second argument maps an activity on all other activities that it can reach (transitively) ('transitive post set')
+
+ """
+ pre = {a: set() for a in alphabet}
+ post = {a: set() for a in alphabet}
+ if len(dfg) > 0:
+ q = [e for e in dfg]
+ while len(q) > 0:
+ s, t = q.pop(0)
+ post[s].add(t)
+ pre[t].add(s)
+ post[s].update(post[t])
+ pre[t].update(pre[s])
+ for a, b in dfg:
+ if b == s and not post[s].issubset(post[a]):
+ post[a].update(post[s])
+ q.append((a, b))
+ if a == t and not pre[t].issubset(pre[b]):
+ pre[b].update(pre[t])
+ q.append((a, b))
+ return pre, post
+
+
+def get_alphabet(dfg):
+ alpha = set()
+ for a, b in dfg:
+ alpha.add(a)
+ alpha.add(b)
+ return alpha
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/genetic_matrix/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/genetic_matrix/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1868764ce5a538310292c6ebdb657cdace3b29c6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/genetic_matrix/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.genetic_matrix import obj
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/genetic_matrix/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/genetic_matrix/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..75916371fc6b86bf9564de9bcf969f17a38fca21
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/genetic_matrix/obj.py
@@ -0,0 +1,60 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+# Author: Maximilian Josef Frank (https://orcid.org/0000-0002-0714-7748)
+
+from typing import Dict, FrozenSet, List
+
+class GeneticMatrix:
+ def __init__(
+ self,
+ input_map: Dict[str, List[FrozenSet[str]]],
+ output_map: Dict[str, List[FrozenSet[str]]],
+ transitions: List[str],
+ ):
+ """
+ Initialize a Genetic matrix
+
+ Reference paper:
+ Maximilian Josef Frank. "Optimising and Implementing the Genetic Miner in PM4Py" (2026).
+
+ Parameters
+ -------------
+ input_map
+ Input map for each node
+ output_map
+ Output map for each node
+ transitions
+ List of transitions
+ """
+ self.input_map = input_map
+ self.output_map = output_map
+ self.transitions = transitions
+
+ def __repr__(self):
+ return str({
+ "I": self.input_map,
+ "O": self.output_map,
+ "T": self.transitions
+ })
+
+ def __str__(self):
+ return self.__repr__()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..79bbf79d376ebd33b3a6b5d168744b542766a435
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.heuristics_net import defaults, edge, obj, node
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/defaults.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/defaults.py
new file mode 100644
index 0000000000000000000000000000000000000000..f38c70f97182e55bcb84204a7c1b9800858145e7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/defaults.py
@@ -0,0 +1,34 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+DEPENDENCY_THRESH = "dependency_thresh"
+AND_MEASURE_THRESH = "and_measure_thresh"
+MIN_ACT_COUNT = "min_act_count"
+MIN_DFG_OCCURRENCES = "min_dfg_occurrences"
+DFG_PRE_CLEANING_NOISE_THRESH = "dfg_pre_cleaning_noise_thresh"
+LOOP_LENGTH_TWO_THRESH = "loop_length_two_thresh"
+
+DEFAULT_DEPENDENCY_THRESH = 0.5
+DEFAULT_AND_MEASURE_THRESH = 0.65
+DEFAULT_MIN_ACT_COUNT = 1
+DEFAULT_MIN_DFG_OCCURRENCES = 1
+DEFAULT_DFG_PRE_CLEANING_NOISE_THRESH = 0.05
+DEFAULT_LOOP_LENGTH_TWO_THRESH = 0.5
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/edge.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/edge.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b683ea383500f7edc611052113f3efc0fd57088
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/edge.py
@@ -0,0 +1,96 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+class Edge:
+ def __init__(
+ self,
+ start_node,
+ end_node,
+ dependency_value,
+ dfg_value,
+ repr_value,
+ label="",
+ repr_color="#000000",
+ edge_type="frequency",
+ net_name="",
+ ):
+ """
+ Constructor
+
+ Parameters
+ ------------
+ start_node
+ Start node of the edge
+ end_node
+ End node of the edge
+ dependency_value
+ Dependency value of the edge
+ dfg_value
+ DFG value of the edge
+ repr_value
+ Value used in the representation
+ label
+ (If provided) label of the edge
+ repr_color
+ (If provided) Color that shall represent the edge
+ edge_type
+ Type of the edge (frequency or performance)
+ net_name
+ (If provided) name of the Heuristics Net
+ """
+ self.start_node = start_node
+ self.end_node = end_node
+ self.dependency_value = dependency_value
+ self.dfg_value = dfg_value
+ self.repr_value = repr_value
+ self.label = label
+ self.repr_color = repr_color
+ self.edge_type = edge_type
+ self.net_name = net_name
+ self.repr_font_color = None
+ self.pen_width = None
+
+ def get_color(self):
+ """
+ Gets the color to use for the representation
+ """
+ return self.repr_color
+
+ def get_font_color(self):
+ """
+ Gets the font color to use for the representation
+ """
+ if self.repr_font_color is not None:
+ return self.repr_font_color
+ return self.repr_color
+
+ def get_penwidth(self, default):
+ """
+ Gets the pen width to use for the representation
+
+ Parameters
+ --------------
+ default
+ Default value
+ """
+ if self.pen_width is not None:
+ return self.pen_width
+ return default
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/node.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/node.py
new file mode 100644
index 0000000000000000000000000000000000000000..aadaac9042ee2980bd4d0b9da15a08460b1ed04a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/node.py
@@ -0,0 +1,350 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.heuristics_net import defaults
+from pm4py.objects.heuristics_net.edge import Edge
+
+
+class Node:
+ def __init__(
+ self,
+ heuristics_net,
+ node_name,
+ node_occ,
+ is_start_node=False,
+ is_end_node=False,
+ default_edges_color="#000000",
+ node_type="frequency",
+ net_name="",
+ nodes_dictionary=None,
+ ):
+ """
+ Constructor
+
+ Parameters
+ -------------
+ heuristics_net
+ Parent heuristics net
+ node_name
+ Name of the node (may be the activity)
+ node_occ
+ Occurrences of the node
+ is_start_node
+ Tells if the node is a start node
+ is_end_node
+ Tells if the node is a end node
+ default_edges_color
+ Default edges color
+ node_type
+ Type of the node (frequency/performance)
+ net_name
+ (If provided) name of the Heuristics Net
+ """
+ self.heuristics_net = heuristics_net
+ self.node_name = node_name
+ self.node_occ = node_occ
+ self.is_start_activity = is_start_node
+ self.is_end_activity = is_end_node
+ self.input_connections = {}
+ self.output_connections = {}
+ self.and_measures_in = {}
+ self.and_measures_out = {}
+ self.loop_length_two = {}
+ self.output_couples_and_measure = []
+ self.default_edges_color = default_edges_color
+ self.node_type = node_type
+ self.net_name = net_name
+ self.nodes_dictionary = nodes_dictionary
+ self.fill_color = None
+ self.font_color = None
+
+ def add_output_connection(
+ self,
+ other_node,
+ dependency_value,
+ dfg_value,
+ repr_color=None,
+ repr_value=None,
+ ):
+ """
+ Adds an output connection to another node
+
+ Parameters
+ -------------
+ other_node
+ Other node
+ dependency_value
+ Dependency value
+ dfg_value
+ DFG value
+ repr_color
+ Color associated to the edge
+ repr_value
+ Value associated to the edge (if None, dfg_value is used)
+ """
+ if repr_color is None:
+ repr_color = self.default_edges_color
+ if repr_value is None:
+ repr_value = dfg_value
+ edge = Edge(
+ self,
+ other_node,
+ dependency_value,
+ dfg_value,
+ repr_value,
+ repr_color=repr_color,
+ edge_type=self.node_type,
+ net_name=self.net_name,
+ )
+ if other_node not in self.output_connections:
+ self.output_connections[other_node] = []
+ self.output_connections[other_node].append(edge)
+
+ def add_input_connection(
+ self,
+ other_node,
+ dependency_value,
+ dfg_value,
+ repr_color=None,
+ repr_value=None,
+ ):
+ """
+ Adds an input connection to another node
+
+ Parameters
+ -------------
+ other_node
+ Other node
+ dependency_value
+ Dependency value
+ dfg_value
+ DFG value
+ repr_color
+ Color associated to the edge
+ repr_value
+ Value associated to the edge (if None, dfg_value is used)
+ """
+ if repr_color is None:
+ repr_color = self.default_edges_color
+ if repr_value is None:
+ repr_value = dfg_value
+ edge = Edge(
+ self,
+ other_node,
+ dependency_value,
+ dfg_value,
+ repr_value,
+ repr_color=repr_color,
+ edge_type=self.node_type,
+ net_name=self.net_name,
+ )
+ if other_node not in self.input_connections:
+ self.input_connections[other_node] = []
+ self.input_connections[other_node].append(edge)
+
+ def calculate_and_measure_out(
+ self, and_measure_thresh=defaults.AND_MEASURE_THRESH
+ ):
+ """
+ Calculate AND measure for output relations (as couples)
+
+ Parameters
+ -------------
+ and_measure_thresh
+ AND measure threshold
+ """
+ out_nodes = sorted(
+ list(self.output_connections), key=lambda x: x.node_name
+ )
+ i = 0
+ while i < len(out_nodes):
+ n1 = out_nodes[i].node_name
+ j = i + 1
+ while j < len(out_nodes):
+ n2 = out_nodes[j].node_name
+ c1 = (
+ self.heuristics_net.dfg_matrix[n1][n2]
+ if n1 in self.heuristics_net.dfg_matrix
+ and n2 in self.heuristics_net.dfg_matrix[n1]
+ else 0
+ )
+ c2 = (
+ self.heuristics_net.dfg_matrix[n2][n1]
+ if n2 in self.heuristics_net.dfg_matrix
+ and n1 in self.heuristics_net.dfg_matrix[n2]
+ else 0
+ )
+ c3 = (
+ self.heuristics_net.dfg_matrix[self.node_name][n1]
+ if self.node_name in self.heuristics_net.dfg_matrix
+ and n1 in self.heuristics_net.dfg_matrix[self.node_name]
+ else 0
+ )
+ c4 = (
+ self.heuristics_net.dfg_matrix[self.node_name][n2]
+ if self.node_name in self.heuristics_net.dfg_matrix
+ and n2 in self.heuristics_net.dfg_matrix[self.node_name]
+ else 0
+ )
+ value = (c1 + c2) / (c3 + c4 + 1)
+ if value >= and_measure_thresh:
+ if n1 not in self.and_measures_out:
+ self.and_measures_out[n1] = {}
+ self.and_measures_out[n1][n2] = value
+ j = j + 1
+ i = i + 1
+
+ def calculate_and_measure_in(
+ self, and_measure_thresh=defaults.AND_MEASURE_THRESH
+ ):
+ """
+ Calculate AND measure for input relations (as couples)
+
+ Parameters
+ --------------
+ and_measure_thresh
+ AND measure threshold
+ """
+ in_nodes = sorted(
+ list(self.input_connections), key=lambda x: x.node_name
+ )
+ i = 0
+ while i < len(in_nodes):
+ n1 = in_nodes[i].node_name
+ j = i + 1
+ while j < len(in_nodes):
+ n2 = in_nodes[j].node_name
+ c1 = (
+ self.heuristics_net.dfg_matrix[n1][n2]
+ if n1 in self.heuristics_net.dfg_matrix
+ and n2 in self.heuristics_net.dfg_matrix[n1]
+ else 0
+ )
+ c2 = (
+ self.heuristics_net.dfg_matrix[n2][n1]
+ if n2 in self.heuristics_net.dfg_matrix
+ and n1 in self.heuristics_net.dfg_matrix[n2]
+ else 0
+ )
+ c3 = (
+ self.heuristics_net.dfg_matrix[n1][self.node_name]
+ if n1 in self.heuristics_net.dfg_matrix
+ and self.node_name in self.heuristics_net.dfg_matrix[n1]
+ else 0
+ )
+ c4 = (
+ self.heuristics_net.dfg_matrix[n2][self.node_name]
+ if n2 in self.heuristics_net.dfg_matrix
+ and self.node_name in self.heuristics_net.dfg_matrix[n2]
+ else 0
+ )
+ value = (c1 + c2) / (c3 + c4 + 1)
+ if value >= and_measure_thresh:
+ if n1 not in self.and_measures_in:
+ self.and_measures_in[n1] = {}
+ self.and_measures_in[n1][n2] = value
+ j = j + 1
+ i = i + 1
+
+ def calculate_loops_length_two(
+ self,
+ dfg_matrix,
+ freq_triples_matrix,
+ loops_length_two_thresh=defaults.DEFAULT_LOOP_LENGTH_TWO_THRESH,
+ ):
+ """
+ Calculate loops of length two
+
+ Parameters
+ --------------
+ dfg_matrix
+ DFG matrix
+ freq_triples_matrix
+ Matrix of triples
+ loops_length_two_thresh
+ Loops length two threshold
+ """
+ if (
+ self.nodes_dictionary is not None
+ and self.node_name in freq_triples_matrix
+ ):
+ n1 = self.node_name
+ for n2 in freq_triples_matrix[n1]:
+ c1 = (
+ dfg_matrix[n1][n2]
+ if n1 in dfg_matrix and n2 in dfg_matrix[n1]
+ else 0
+ )
+ v1 = (
+ freq_triples_matrix[n1][n2]
+ if n1 in freq_triples_matrix
+ and n2 in freq_triples_matrix[n1]
+ else 0
+ )
+ v2 = (
+ freq_triples_matrix[n2][n1]
+ if n2 in freq_triples_matrix
+ and n1 in freq_triples_matrix[n2]
+ else 0
+ )
+ l2l = (v1 + v2) / (v1 + v2 + 1)
+ if l2l >= loops_length_two_thresh:
+ self.loop_length_two[n2] = c1
+
+ def get_fill_color(self, default):
+ """
+ Gets the fill color for the representation
+
+ Parameters
+ --------------
+ default
+ Default value
+ """
+ if self.fill_color is not None:
+ return self.fill_color
+ return default
+
+ def get_font_color(self):
+ """
+ Gets the font color for the representation
+ """
+ if self.font_color is not None:
+ return self.font_color
+ return "#000000"
+
+ def __repr__(self):
+ ret = "(node:" + self.node_name + " connections:{"
+ for index, conn in enumerate(self.output_connections.keys()):
+ if index > 0:
+ ret = ret + ", "
+ ret = (
+ ret
+ + conn.node_name
+ + ":"
+ + str(
+ [x.dependency_value for x in self.output_connections[conn]]
+ )
+ )
+ ret = ret + "})"
+ return ret
+
+ def __str__(self):
+ return self.__repr__()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..9576ad67c9e372471db7e261560eba01021f5e7e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/heuristics_net/obj.py
@@ -0,0 +1,171 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from copy import deepcopy
+
+from pm4py.objects.dfg.utils import dfg_utils
+
+DEFAULT_NET_NAME = ""
+
+
+class HeuristicsNet:
+ def __init__(
+ self,
+ frequency_dfg,
+ activities=None,
+ start_activities=None,
+ end_activities=None,
+ activities_occurrences=None,
+ default_edges_color="#000000",
+ performance_dfg=None,
+ dfg_window_2=None,
+ freq_triples=None,
+ net_name=DEFAULT_NET_NAME,
+ ):
+ """
+ Initialize an Hueristics Net
+
+ The implementation is based on the original paper on Heuristics Miner, namely:
+
+ Weijters, A. J. M. M., Wil MP van Der Aalst, and AK Alves De Medeiros.
+ "Process mining with the heuristics miner-algorithm."
+ Technische Universiteit Eindhoven, Tech. Rep. WP 166 (2006): 1-34.
+
+ and it manages to calculate the dependency matrix, the loops of length one and two, and
+ the AND measure
+
+ Parameters
+ -------------
+ frequency_dfg
+ Directly-Follows graph (frequency)
+ activities
+ Activities
+ start_activities
+ Start activities
+ end_activities
+ End activities
+ activities_occurrences
+ Activities occurrences
+ default_edges_color
+ (If provided) Default edges color
+ performance_dfg
+ Performance DFG
+ dfg_window_2
+ DFG window 2
+ freq_triples
+ Frequency triples
+ net_name
+ (If provided) name of the heuristics net
+ """
+ self.net_name = [net_name]
+
+ self.nodes = {}
+ self.dependency_matrix = {}
+ self.dfg_matrix = {}
+
+ self.dfg = frequency_dfg
+ self.performance_dfg = performance_dfg
+ self.node_type = (
+ "frequency" if self.performance_dfg is None else "performance"
+ )
+
+ self.activities = activities
+ if self.activities is None:
+ self.activities = dfg_utils.get_activities_from_dfg(frequency_dfg)
+ if start_activities is None:
+ self.start_activities = [
+ dfg_utils.infer_start_activities(frequency_dfg)
+ ]
+ else:
+ self.start_activities = [start_activities]
+ if end_activities is None:
+ self.end_activities = [
+ dfg_utils.infer_end_activities(frequency_dfg)
+ ]
+ else:
+ self.end_activities = [end_activities]
+ self.activities_occurrences = activities_occurrences
+ if self.activities_occurrences is None:
+ self.activities_occurrences = {}
+ for act in self.activities:
+ self.activities_occurrences[act] = (
+ dfg_utils.sum_activities_count(frequency_dfg, [act])
+ )
+ self.default_edges_color = [default_edges_color]
+ self.dfg_window_2 = dfg_window_2
+ self.dfg_window_2_matrix = {}
+ self.freq_triples = freq_triples
+ self.freq_triples_matrix = {}
+ self.concurrent_activities = {}
+ self.sojourn_times = {}
+
+ def __add__(self, other_net):
+ copied_self = deepcopy(self)
+ for node_name in copied_self.nodes:
+ if node_name in other_net.nodes:
+ node1 = copied_self.nodes[node_name]
+ node2 = other_net.nodes[node_name]
+ n1n = {x.node_name: x for x in node1.output_connections}
+ n2n = {x.node_name: x for x in node2.output_connections}
+ for out_node1 in node1.output_connections:
+ if out_node1.node_name in n2n:
+ node1.output_connections[out_node1] = (
+ node1.output_connections[out_node1]
+ + node2.output_connections[
+ n2n[out_node1.node_name]
+ ]
+ )
+ for out_node2 in node2.output_connections:
+ if out_node2.node_name not in n1n:
+ if out_node2.node_name in copied_self.nodes:
+ nn = copied_self.nodes[out_node2.node_name]
+ node1.output_connections[nn] = (
+ node2.output_connections[out_node2]
+ )
+ else:
+ node1.output_connections[out_node2] = (
+ node2.output_connections[out_node2]
+ )
+ diffext = [
+ other_net.nodes[node]
+ for node in other_net.nodes
+ if node not in copied_self.nodes
+ ]
+ for node in diffext:
+ copied_self.nodes[node.node_name] = node
+ copied_self.start_activities = (
+ copied_self.start_activities + other_net.start_activities
+ )
+ copied_self.end_activities = (
+ copied_self.end_activities + other_net.end_activities
+ )
+ copied_self.default_edges_color = (
+ copied_self.default_edges_color + other_net.default_edges_color
+ )
+ copied_self.net_name = copied_self.net_name + other_net.net_name
+
+ return copied_self
+
+ def __repr__(self):
+ return str(self.nodes)
+
+ def __str__(self):
+ return str(self.nodes)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1fdb0ae9c69b5f5bd5fa31211ec88ec33e3b984
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.log import obj, exporter, importer, util
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b7b8af11bab29f26723c01c548719537ec9d95e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.exporter import xes
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8048e89bdc82f0eea89589389592f5e1b217f529
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.exporter.xes import exporter, variants, util
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d97aacee6214bd2462946042ab431de5b32c504
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/exporter.py
@@ -0,0 +1,94 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.conversion.log import converter as log_conversion
+from pm4py.objects.log.exporter.xes.variants import etree_xes_exp, line_by_line
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ ETREE = etree_xes_exp
+ LINE_BY_LINE = line_by_line
+
+
+DEFAULT_VARIANT = Variants.LINE_BY_LINE
+
+
+def apply(log, output_file_path, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Method to export a XES from a log
+
+ Parameters
+ -----------
+ log
+ Trace log
+ output_file_path
+ Output file path
+ variant
+ Selected variant of the algorithm
+ parameters
+ Parameters of the algorithm:
+ Parameters.COMPRESS -> Indicates that the XES file must be compressed
+ """
+ parameters = dict() if parameters is None else parameters
+ return exec_utils.get_variant(variant).apply(
+ log_conversion.apply(
+ log,
+ variant=log_conversion.Variants.TO_EVENT_LOG,
+ parameters=parameters,
+ ),
+ output_file_path,
+ parameters=parameters,
+ )
+
+
+def serialize(log, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Serialize a log into a binary string containing the XES of the log
+
+ Parameters
+ -----------
+ log
+ Trace log
+ variant
+ Selected variant of the algorithm
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ string
+ String describing the XES
+ """
+ parameters = dict() if parameters is None else parameters
+
+ log_string = exec_utils.get_variant(variant).export_log_as_string(
+ log_conversion.apply(
+ log,
+ variant=log_conversion.Variants.TO_EVENT_LOG,
+ parameters=parameters,
+ ),
+ parameters=parameters,
+ )
+
+ return log_string
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/util/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1a3a56c2b059cd82ae2be496c83302b626c088a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/util/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.exporter.xes.util import compression
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/util/compression.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/util/compression.py
new file mode 100644
index 0000000000000000000000000000000000000000..52a88c185cbc74df3dc460b06d05cca3a48849d8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/util/compression.py
@@ -0,0 +1,51 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import os
+import shutil
+import tempfile
+
+
+# this is ugly, should be done internally in the exporter...
+def compress(file):
+ """
+ Compress a file in-place adding .gz suffix
+
+ Parameters
+ -----------
+ file
+ Uncompressed file
+
+ Returns
+ -----------
+ compressed_file
+ Compressed file path
+ """
+ extension = file.split(".")[-1] + ".gz"
+ fp = tempfile.NamedTemporaryFile(suffix=extension)
+ fp.close()
+ with open(file, "rb") as f_in:
+ with gzip.open(fp.name, "wb") as f_out:
+ shutil.copyfileobj(f_in, f_out)
+ shutil.move(fp.name, file + ".gz")
+ os.remove(file)
+ return file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0332ee4ad0bc51d00674435ce1b7be7362addd64
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.exporter.xes.variants import etree_xes_exp, line_by_line
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/etree_xes_exp.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/etree_xes_exp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3ffd3aae3eba8b2849980f02818d48c02971049
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/etree_xes_exp.py
@@ -0,0 +1,439 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import importlib.util
+from enum import Enum
+
+try:
+ # do not compromise anymore importing the XES "exporter" package if "lxml" is / cannot be installed,
+ # and this variant cannot be used.
+ # after all, the default variant is now the "line_by_line" one.
+ from lxml import etree
+except BaseException:
+ pass
+
+from pm4py.objects.conversion.log import converter as log_converter
+from pm4py.objects.log import obj as log_instance
+from pm4py.objects.log.util import xes as xes_util
+from pm4py.util import constants
+from pm4py.util import exec_utils
+from io import BytesIO
+import gzip
+
+
+class Parameters(Enum):
+ COMPRESS = "compress"
+ SHOW_PROGRESS_BAR = "show_progress_bar"
+ ENCODING = "encoding"
+
+
+# defines correspondence between Python types and XES types
+__TYPE_CORRESPONDENCE = {
+ "str": xes_util.TAG_STRING,
+ "int": xes_util.TAG_INT,
+ "float": xes_util.TAG_FLOAT,
+ "datetime": xes_util.TAG_DATE,
+ "Timestamp": xes_util.TAG_DATE,
+ "bool": xes_util.TAG_BOOLEAN,
+ "dict": xes_util.TAG_LIST,
+ "numpy.int64": xes_util.TAG_INT,
+ "numpy.float64": xes_util.TAG_FLOAT,
+ "numpy.datetime64": xes_util.TAG_DATE,
+}
+# if a type is not found in the previous list, then default to string
+__DEFAULT_TYPE = xes_util.TAG_STRING
+
+
+def __get_xes_attr_type(attr_name, attr_type):
+ """
+ Transform a Python attribute type (e.g. str, datetime) into a XES attribute type (e.g. string, date)
+
+ Parameters
+ ----------
+ attr_name
+ Name of the attribute
+ attr_type:
+ Python attribute type
+ """
+ if attr_name == xes_util.DEFAULT_NAME_KEY:
+ return xes_util.TAG_STRING
+ elif attr_type in __TYPE_CORRESPONDENCE:
+ attr_type_xes = __TYPE_CORRESPONDENCE[attr_type]
+ else:
+ attr_type_xes = __DEFAULT_TYPE
+ return attr_type_xes
+
+
+def __get_xes_attr_value(attr_value, attr_type_xes):
+ """
+ Transform an attribute value from Python format to XES format (the type is provided as argument)
+
+ Parameters
+ ----------
+ attr_value:
+ XES attribute value
+ attr_type_xes:
+ XES attribute type
+
+ """
+ if attr_type_xes == xes_util.TAG_DATE:
+ return attr_value.isoformat()
+ elif attr_type_xes == xes_util.TAG_BOOLEAN:
+ return str(attr_value).lower()
+ return str(attr_value)
+
+
+def __export_attributes(log, root):
+ """
+ Export XES attributes (at the log level) from a PM4PY log
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ root:
+ Output XML root element
+
+ """
+ __export_attributes_element(log, root)
+
+
+def __export_extensions(log, root):
+ """
+ Export XES extensions from a PM4PY log
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ root:
+ Output XML root element
+
+ """
+ for ext in log.extensions.keys():
+ ext_value = log.extensions[ext]
+ log_extension = etree.SubElement(root, xes_util.TAG_EXTENSION)
+ if (
+ ext is not None
+ and ext_value[xes_util.KEY_PREFIX] is not None
+ and ext_value[xes_util.KEY_URI] is not None
+ ):
+ log_extension.set(xes_util.KEY_NAME, ext)
+ log_extension.set(
+ xes_util.KEY_PREFIX, ext_value[xes_util.KEY_PREFIX]
+ )
+ log_extension.set(xes_util.KEY_URI, ext_value[xes_util.KEY_URI])
+
+
+def __export_globals(log, root):
+ """
+ Export XES globals from a PM4PY log
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ root:
+ Output XML root element
+
+ """
+ for glob in log.omni_present.keys():
+ glob_els = log.omni_present[glob]
+ xes_global = etree.SubElement(root, xes_util.TAG_GLOBAL)
+ xes_global.set(xes_util.KEY_SCOPE, glob)
+ __export_attributes_element(glob_els, xes_global)
+
+
+def __export_classifiers(log, root):
+ """
+ Export XES classifiers from a PM4PY log
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ root:
+ Output XML root element
+
+ """
+ for clas in log.classifiers.keys():
+ clas_value = log.classifiers[clas]
+ classifier = etree.SubElement(root, xes_util.TAG_CLASSIFIER)
+ classifier.set(xes_util.KEY_NAME, clas)
+ values_spaces = [(" " in x) for x in clas_value]
+ values_spaces = [x for x in values_spaces if x]
+ if len(values_spaces) > 0:
+ clas_value = ["'" + x + "'" for x in clas_value]
+ classifier.set(xes_util.KEY_KEYS, " ".join(clas_value))
+
+
+def __export_attributes_element(log_element, xml_element):
+ """
+ Export attributes related to a single element
+
+ Parameters
+ ----------
+ log_element:
+ Element in log (event, trace ...)
+ xml_element:
+ XML element
+ """
+ if hasattr(log_element, "attributes"):
+ log_element = log_element.attributes
+
+ if isinstance(log_element, list) or isinstance(log_element, set):
+ items = log_element
+ else:
+ items = log_element.items()
+
+ for attr, attr_value in items:
+ if attr is not None and attr_value is not None:
+ attr_type = type(attr_value).__name__
+ attr_type_xes = __get_xes_attr_type(attr, attr_type)
+ if attr_type is not None and attr_type_xes is not None:
+ if attr_type_xes == xes_util.TAG_LIST:
+ if attr_value["value"] is None:
+ this_attribute = etree.SubElement(
+ xml_element, attr_type_xes
+ )
+ this_attribute.set(xes_util.KEY_KEY, attr)
+ this_attribute_values = etree.SubElement(
+ this_attribute, "values"
+ )
+ __export_attributes_element(
+ attr_value["children"], this_attribute_values
+ )
+ else:
+ attr_type = type(attr_value["value"]).__name__
+ attr_type_xes = __get_xes_attr_type(attr, attr_type)
+ if attr_type is not None and attr_type_xes is not None:
+ if attr_value is not None:
+ this_attribute = etree.SubElement(
+ xml_element, attr_type_xes
+ )
+ this_attribute.set(xes_util.KEY_KEY, attr)
+ this_attribute.set(
+ xes_util.KEY_VALUE,
+ str(attr_value["value"]),
+ )
+ __export_attributes_element(
+ attr_value["children"], this_attribute
+ )
+ else:
+ attr_value = __get_xes_attr_value(
+ attr_value, attr_type_xes
+ )
+ if attr_value is not None:
+ this_attribute = etree.SubElement(
+ xml_element, attr_type_xes
+ )
+ this_attribute.set(xes_util.KEY_KEY, attr)
+ this_attribute.set(xes_util.KEY_VALUE, str(attr_value))
+
+
+def __export_traces_events(tr, trace):
+ """
+ Export XES events given a PM4PY trace
+
+ Parameters
+ ----------
+ tr: :class:`pm4py.log.log.Trace`
+ PM4PY trace
+ trace:
+ Output XES trace
+
+ """
+
+ for ev in tr:
+ event = etree.SubElement(trace, xes_util.TAG_EVENT)
+ __export_attributes_element(ev, event)
+
+
+def __export_traces(log, root, parameters=None):
+ """
+ Export XES traces from a PM4PY log
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ root:
+ Output XML root element
+
+ """
+ if parameters is None:
+ parameters = {}
+
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+
+ progress = None
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ from tqdm.auto import tqdm
+
+ progress = tqdm(
+ total=len(log), desc="exporting log, completed traces :: "
+ )
+
+ for tr in log:
+ trace = etree.SubElement(root, xes_util.TAG_TRACE)
+ __export_attributes_element(tr, trace)
+ __export_traces_events(tr, trace)
+ if progress is not None:
+ progress.update()
+
+ # gracefully close progress bar
+ if progress is not None:
+ progress.close()
+ del progress
+
+
+def export_log_tree(log, parameters=None):
+ """
+ Get XES log XML tree from a PM4Py log
+
+ Parameters
+ -----------
+ log
+ PM4Py log
+
+ Returns
+ -----------
+ tree
+ XML tree
+ """
+ # If the log is in log_instance.EventStream, then transform it into
+ # log_instance.EventLog format
+ if type(log) is log_instance.EventStream:
+ log = log_converter.apply(
+ log,
+ variant=log_converter.Variants.TO_EVENT_LOG,
+ parameters=parameters,
+ )
+ root = etree.Element(xes_util.TAG_LOG)
+ root.set(xes_util.TAG_VERSION, xes_util.VALUE_XES_VERSION)
+ root.set(xes_util.TAG_FEATURES, xes_util.VALUE_XES_FEATURES)
+ root.set(xes_util.TAG_XMLNS, xes_util.VALUE_XMLNS)
+
+ # add attributes at the log level
+ __export_attributes(log, root)
+ # add extensions at the log level
+ __export_extensions(log, root)
+ # add globals at the log level
+ __export_globals(log, root)
+ # add classifiers at the log level
+ __export_classifiers(log, root)
+ # add traces at the log level
+ __export_traces(log, root, parameters=parameters)
+
+ tree = etree.ElementTree(root)
+
+ return tree
+
+
+def export_log_as_string(log, parameters=None):
+ """
+ Export a log into a string
+
+ Parameters
+ -----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ logString
+ Log as a string
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ compress = exec_utils.get_param_value(
+ Parameters.COMPRESS, parameters, False
+ )
+
+ # Gets the XML tree to export
+ tree = export_log_tree(log, parameters=parameters)
+
+ b = BytesIO()
+
+ if compress:
+ d = gzip.GzipFile(fileobj=b, mode="wb")
+ else:
+ d = b
+
+ tree.write(d, pretty_print=True, xml_declaration=True, encoding=encoding)
+
+ if compress:
+ d.close()
+
+ return b.getvalue()
+
+
+def __export_log(log, output_file_path, parameters=None):
+ """
+ Export XES log from a PM4PY log
+
+ Parameters
+ ----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ output_file_path:
+ Output file path
+ parameters
+ Parameters of the algorithm
+
+ """
+ parameters = dict() if parameters is None else parameters
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ compress = exec_utils.get_param_value(
+ Parameters.COMPRESS,
+ parameters,
+ output_file_path.lower().endswith(".gz"),
+ )
+
+ # Gets the XML tree to export
+ tree = export_log_tree(log, parameters=parameters)
+
+ if compress:
+ if not output_file_path.lower().endswith(".gz"):
+ output_file_path = output_file_path + ".gz"
+ f = gzip.open(output_file_path, mode="wb")
+ else:
+ f = open(output_file_path, "wb")
+
+ # Effectively do the export of the event log
+ tree.write(f, pretty_print=True, xml_declaration=True, encoding=encoding)
+
+ f.close()
+
+
+def apply(log, output_file_path, parameters=None):
+ return __export_log(log, output_file_path, parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/line_by_line.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/line_by_line.py
new file mode 100644
index 0000000000000000000000000000000000000000..52d2f2f9aafae83314c1a0486beb2d067bd147d9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/exporter/xes/variants/line_by_line.py
@@ -0,0 +1,401 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import importlib.util
+from enum import Enum
+from io import BytesIO
+
+from pm4py.objects.log.util import xes as xes_util
+from pm4py.util import exec_utils, constants
+from xml.sax.saxutils import quoteattr
+
+
+class Parameters(Enum):
+ COMPRESS = "compress"
+ SHOW_PROGRESS_BAR = "show_progress_bar"
+ ENCODING = "encoding"
+
+
+# defines correspondence between Python types and XES types
+__TYPE_CORRESPONDENCE = {
+ "str": xes_util.TAG_STRING,
+ "int": xes_util.TAG_INT,
+ "float": xes_util.TAG_FLOAT,
+ "datetime": xes_util.TAG_DATE,
+ "Timestamp": xes_util.TAG_DATE,
+ "bool": xes_util.TAG_BOOLEAN,
+ "dict": xes_util.TAG_LIST,
+ "numpy.int64": xes_util.TAG_INT,
+ "numpy.float64": xes_util.TAG_FLOAT,
+ "numpy.datetime64": xes_util.TAG_DATE,
+}
+# if a type is not found in the previous list, then default to string
+__DEFAULT_TYPE = xes_util.TAG_STRING
+
+
+def __get_xes_attr_type(attr_name, attr_type):
+ """
+ Transform a Python attribute type (e.g. str, datetime) into a XES attribute type (e.g. string, date)
+
+ Parameters
+ ----------
+ attr_name
+ Name of the attribute
+ attr_type:
+ Python attribute type
+ """
+ if attr_name == xes_util.DEFAULT_NAME_KEY:
+ return xes_util.TAG_STRING
+ elif attr_type in __TYPE_CORRESPONDENCE:
+ attr_type_xes = __TYPE_CORRESPONDENCE[attr_type]
+ else:
+ attr_type_xes = __DEFAULT_TYPE
+ return attr_type_xes
+
+
+def __get_xes_attr_value(attr_value, attr_type_xes):
+ """
+ Transform an attribute value from Python format to XES format (the type is provided as argument)
+
+ Parameters
+ ----------
+ attr_value:
+ XES attribute value
+ attr_type_xes:
+ XES attribute type
+
+ """
+ if attr_type_xes == xes_util.TAG_DATE:
+ return attr_value.isoformat()
+ elif attr_type_xes == xes_util.TAG_BOOLEAN:
+ return str(attr_value).lower()
+ return str(attr_value)
+
+
+def get_tab_indent(n):
+ """
+ Get the desidered number of indentations as string
+
+ Parameters
+ -------------
+ n
+ Number of indentations
+
+ Returns
+ -------------
+ str_tab_indent
+ Desidered number of indentations as string
+ """
+ return "".join(["\t"] * n)
+
+
+def escape(stru):
+ """
+ XML-escape a string
+
+ Parameters
+ ----------------
+ stru
+ String to be escaped
+
+ Returns
+ ----------------
+ escaped_stru
+ Escaped string
+ """
+ return quoteattr(stru)
+
+
+def export_attribute(attr_name, attr_value, indent_level):
+ """
+ Exports an attribute
+
+ Parameters
+ --------------
+ attr_name
+ Name of the attribute
+ attr_value
+ Value of the attribute
+ indent_level
+ Level of indentation
+
+ Returns
+ --------------
+ stru
+ String representing the content of the attribute
+ """
+ ret = []
+ if attr_name is not None and attr_value is not None:
+ attr_type = __get_xes_attr_type(attr_name, type(attr_value).__name__)
+ if not attr_type == xes_util.TAG_LIST:
+ attr_value = __get_xes_attr_value(attr_value, attr_type)
+ ret.append(
+ get_tab_indent(indent_level)
+ + "<%s key=%s value=%s />\n"
+ % (attr_type, escape(attr_name), escape(attr_value))
+ )
+ else:
+ if attr_value[xes_util.KEY_VALUE] is None:
+ # list
+ ret.append(
+ get_tab_indent(indent_level)
+ + "\n" % (escape(attr_name))
+ )
+ ret.append(get_tab_indent(indent_level + 1) + "\n")
+ for subattr in attr_value[xes_util.KEY_CHILDREN]:
+ ret.append(
+ export_attribute(
+ subattr[0], subattr[1], indent_level + 2
+ )
+ )
+ ret.append(get_tab_indent(indent_level + 1) + "\n")
+ ret.append(get_tab_indent(indent_level) + "
\n")
+ else:
+ # nested attribute
+ this_value = attr_value[xes_util.KEY_VALUE]
+ this_type = __get_xes_attr_type(
+ attr_name, type(this_value).__name__
+ )
+ this_value = __get_xes_attr_value(this_value, this_type)
+ ret.append(
+ get_tab_indent(indent_level)
+ + "<%s key=%s value=%s>\n"
+ % (this_type, escape(attr_name), escape(this_value))
+ )
+ for subattr_name, subattr_value in attr_value[
+ xes_util.KEY_CHILDREN
+ ].items():
+ ret.append(
+ export_attribute(
+ subattr_name, subattr_value, indent_level + 1
+ )
+ )
+ ret.append("%s>\n" % this_type)
+ return "".join(ret)
+
+
+def export_trace_line_by_line(trace, fp_obj, encoding):
+ """
+ Exports the content of a trace line-by-line
+ to a file object
+
+ Parameters
+ -----------------
+ trace
+ Trace
+ fp_obj
+ File object
+ encoding
+ Encoding
+ """
+ fp_obj.write((get_tab_indent(1) + "\n").encode(encoding))
+ for attr_name, attr_value in trace.attributes.items():
+ fp_obj.write(
+ export_attribute(attr_name, attr_value, 2).encode(encoding)
+ )
+ for event in trace:
+ fp_obj.write((get_tab_indent(2) + "\n").encode(encoding))
+ for attr_name, attr_value in event.items():
+ fp_obj.write(
+ export_attribute(attr_name, attr_value, 3).encode(encoding)
+ )
+ fp_obj.write((get_tab_indent(2) + "\n").encode(encoding))
+ fp_obj.write((get_tab_indent(1) + "\n").encode(encoding))
+
+
+def export_log_line_by_line(log, fp_obj, encoding, parameters=None):
+ """
+ Exports the contents of the log line-by-line
+ to a file object
+
+ Parameters
+ --------------
+ log
+ Event log
+ fp_obj
+ File object
+ encoding
+ Encoding
+ parameters
+ Parameters of the algorithm
+ """
+ if parameters is None:
+ parameters = {}
+
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+
+ progress = None
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ from tqdm.auto import tqdm
+
+ progress = tqdm(
+ total=len(log), desc="exporting log, completed traces :: "
+ )
+
+ fp_obj.write(
+ ('\n').encode(
+ encoding
+ )
+ )
+ fp_obj.write(
+ (
+ "\n'
+ ).encode(encoding)
+ )
+ for ext_name, ext_value in log.extensions.items():
+ fp_obj.write(
+ (
+ get_tab_indent(1)
+ + '\n'
+ % (
+ ext_name,
+ ext_value[xes_util.KEY_PREFIX],
+ ext_value[xes_util.KEY_URI],
+ )
+ ).encode(encoding)
+ )
+ for clas_name, clas_attributes in log.classifiers.items():
+ fp_obj.write(
+ (
+ get_tab_indent(1)
+ + '\n'
+ % (clas_name, " ".join(clas_attributes))
+ ).encode(encoding)
+ )
+ for attr_name, attr_value in log.attributes.items():
+ fp_obj.write(
+ export_attribute(attr_name, attr_value, 1).encode(encoding)
+ )
+ for scope in log.omni_present:
+ fp_obj.write(
+ (get_tab_indent(1) + '\n' % (scope)).encode(
+ encoding
+ )
+ )
+ for attr_name, attr_value in log.omni_present[scope].items():
+ fp_obj.write(
+ export_attribute(attr_name, attr_value, 2).encode(encoding)
+ )
+ fp_obj.write((get_tab_indent(1) + "\n").encode(encoding))
+ for trace in log:
+ export_trace_line_by_line(trace, fp_obj, encoding)
+ if progress is not None:
+ progress.update()
+ # gracefully close progress bar
+ if progress is not None:
+ progress.close()
+ del progress
+
+ fp_obj.write("\n".encode(encoding))
+
+
+def apply(log, output_file_path, parameters=None):
+ """
+ Exports a XES log using a non-standard exporter
+ (classifiers, lists, nested attributes, globals, extensions are not supported)
+
+ Parameters
+ ------------
+ log
+ Event log
+ output_file_path
+ Path to the XES file
+ parameters
+ Parameters
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ compress = exec_utils.get_param_value(
+ Parameters.COMPRESS,
+ parameters,
+ output_file_path.lower().endswith(".gz"),
+ )
+
+ if compress:
+ if not output_file_path.lower().endswith(".gz"):
+ output_file_path = output_file_path + ".gz"
+ f = gzip.open(output_file_path, mode="wb")
+ else:
+ f = open(output_file_path, "wb")
+
+ export_log_line_by_line(log, f, encoding, parameters=parameters)
+
+ f.close()
+
+
+def export_log_as_string(log, parameters=None):
+ """
+ Export a log into a string
+
+ Parameters
+ -----------
+ log: :class:`pm4py.log.log.EventLog`
+ PM4PY log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ logString
+ Log as a string
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ compress = exec_utils.get_param_value(
+ Parameters.COMPRESS, parameters, False
+ )
+
+ b = BytesIO()
+
+ if compress:
+ d = gzip.GzipFile(fileobj=b, mode="wb")
+ else:
+ d = b
+
+ export_log_line_by_line(log, d, encoding, parameters=parameters)
+
+ if compress:
+ d.close()
+
+ return b.getvalue()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..18fef27237b436488562563a58f5300d14c82246
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.importer import xes
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f5a5b6035a512a4d7f01148653baaa994680e2b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.importer.xes import variants, importer
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b183334a74741ddcdcbc652faf3b20667242ec9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/importer.py
@@ -0,0 +1,136 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from pm4py.util import constants
+
+from pm4py.objects.log.importer.xes.variants import (
+ iterparse,
+ line_by_line,
+ iterparse_mem_compressed,
+ iterparse_20,
+ chunk_regex,
+ rustxes,
+)
+
+
+class Variants(Enum):
+ ITERPARSE = iterparse
+ LINE_BY_LINE = line_by_line
+ ITERPARSE_MEM_COMPRESSED = iterparse_mem_compressed
+ ITERPARSE_20 = iterparse_20
+ CHUNK_REGEX = chunk_regex
+ RUSTXES = rustxes
+
+
+def __get_variant(variant_str: str):
+ variant = Variants.CHUNK_REGEX
+
+ if variant_str == "nonstandard":
+ variant = Variants.LINE_BY_LINE
+ elif variant_str == "iterparse":
+ variant = Variants.ITERPARSE
+ elif variant_str == "lxml":
+ variant = Variants.ITERPARSE
+ elif variant_str == "chunk_regex":
+ variant = Variants.CHUNK_REGEX
+ elif variant_str == "line_by_line":
+ variant = Variants.LINE_BY_LINE
+ elif variant_str == "iterparse_20":
+ variant = Variants.ITERPARSE_20
+ elif variant_str == "iterparse_mem_compressed":
+ variant = Variants.ITERPARSE_MEM_COMPRESSED
+ elif variant_str == "rustxes" or variant_str == "r4pm":
+ variant = Variants.RUSTXES
+
+ return variant
+
+
+def apply(path, parameters=None, variant=constants.DEFAULT_XES_PARSER):
+ """
+ Import a XES log into a EventLog object
+
+ Parameters
+ -----------
+ path
+ Log path
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.INSERT_TRACE_INDICES -> Specify if trace indexes should be added as event attribute for each event
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ variant
+ Variant of the algorithm to use, including:
+ - Variants.ITERPARSE
+ - Variants.LINE_BY_LINE
+
+ Returns
+ -----------
+ log
+ Trace log object
+ """
+ if parameters is None:
+ parameters = {}
+
+ if type(variant) is str:
+ variant = __get_variant(variant)
+
+ log = variant.value.apply(path, parameters=parameters)
+
+ return log
+
+
+def deserialize(
+ log_string, parameters=None, variant=constants.DEFAULT_XES_PARSER
+):
+ """
+ Deserialize a text/binary string representing a XES log
+
+ Parameters
+ -----------
+ log_string
+ String that contains the XES
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.INSERT_TRACE_INDICES -> Specify if trace indexes should be added as event attribute for each event
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ variant
+ Variant of the algorithm to use, including:
+ - Variants.ITERPARSE
+ - Variants.LINE_BY_LINE
+
+ Returns
+ -----------
+ log
+ Trace log object
+ """
+ if parameters is None:
+ parameters = {}
+
+ if type(variant) is str:
+ variant = __get_variant(variant)
+
+ return variant.value.import_from_string(log_string, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b41dea3ec82a0f9a79cadfee1d80fcab0e0c80a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/__init__.py
@@ -0,0 +1,27 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.importer.xes.variants import (
+ iterparse,
+ line_by_line,
+ iterparse_mem_compressed,
+ chunk_regex,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/chunk_regex.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/chunk_regex.py
new file mode 100644
index 0000000000000000000000000000000000000000..8dbb2cad9fe5bfb2d7111afd08c5e03e6e78548f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/chunk_regex.py
@@ -0,0 +1,297 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import os
+import sys
+from enum import Enum
+from io import BytesIO
+
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.util import constants, exec_utils
+from pm4py.util.dt_parsing import parser as dt_parser
+import re
+from collections import deque
+
+
+class Parameters(Enum):
+ DECOMPRESS_SERIALIZATION = "decompress_serialization"
+ ENCODING = "encoding"
+
+
+def apply(filename, parameters=None):
+ return import_log(filename, parameters)
+
+
+def import_log_from_file_object(
+ F, encoding, file_size=sys.maxsize, parameters=None
+):
+ """
+ Import a log object from a (XML) file object
+
+ Parameters
+ -----------
+ F
+ file object
+ encoding
+ Encoding
+ file_size
+ Size of the file (measured on disk)
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ log
+ Log file
+ """
+ nb = 2**12 # bytes per chunk
+ rex = re.compile(r"(<|>)")
+ parser = dt_parser.get()
+ cont = F.read(nb)
+ curr_els_attrs = []
+ fk_dict = {}
+ log = EventLog()
+ trace = None
+ while cont:
+ lst = deque(rex.split(cont.decode(encoding)))
+ while lst:
+ el = lst.popleft()
+ if len(el.rstrip()) > 0:
+ if el == "<":
+ continue
+ elif el == ">":
+ continue
+ while len(lst) == 0:
+ # need to read more
+ cont = F.read(nb)
+ if cont:
+ lst2 = rex.split(cont.decode(encoding))
+ el = el + lst2[0]
+ lst = deque(lst2[1:])
+ else:
+ break
+ if el[0] == "/":
+ if len(curr_els_attrs) > 1:
+ curr_els_attrs.pop()
+ else:
+ return log
+ continue
+ idx = el.find(" ")
+ if idx > -1:
+ tag = el[:idx]
+ el = el.split('"')
+ el[-1] = el[-1].strip()
+ if tag == "string":
+ curr_els_attrs[-1][el[1]] = el[3]
+ if el[-1] != "/":
+ curr_els_attrs.append(fk_dict)
+ continue
+ elif tag == "date":
+ curr_els_attrs[-1][el[1]] = parser.apply(el[3])
+ if el[-1] != "/":
+ curr_els_attrs.append(fk_dict)
+ continue
+ elif tag == "int":
+ curr_els_attrs[-1][el[1]] = int(el[3])
+ if el[-1] != "/":
+ curr_els_attrs.append(fk_dict)
+ continue
+ elif tag == "float":
+ curr_els_attrs[-1][el[1]] = float(el[3])
+ if el[-1] != "/":
+ curr_els_attrs.append(fk_dict)
+ continue
+ elif tag == "boolean":
+ curr_els_attrs[-1][el[1]] = (
+ True if el[3] == "true" else False
+ )
+ if el[-1] != "/":
+ curr_els_attrs.append(fk_dict)
+ continue
+ elif tag == "extension":
+ ext = log.extensions
+ name = el[
+ [i for i in range(len(el)) if "name=" in el[i]][0]
+ + 1
+ ]
+ prefix = el[
+ [i for i in range(len(el)) if "prefix=" in el[i]][
+ 0
+ ]
+ + 1
+ ]
+ uri = el[
+ [i for i in range(len(el)) if "uri=" in el[i]][0]
+ + 1
+ ]
+ ext[name] = {"prefix": prefix, "uri": uri}
+ if el[-1] != "/":
+ curr_els_attrs.append(ext)
+ continue
+ elif tag == "classifier":
+ classif = log.classifiers
+ name = el[
+ [i for i in range(len(el)) if "name=" in el[i]][0]
+ + 1
+ ]
+ keys = el[
+ [i for i in range(len(el)) if "keys=" in el[i]][0]
+ + 1
+ ]
+ if "'" in keys:
+ classif[name] = [
+ x for x in keys.split("'") if x.strip()
+ ]
+ else:
+ classif[name] = keys.split()
+ if el[-1] != "/":
+ curr_els_attrs.append(classif)
+ continue
+ elif tag == "global":
+ glob = log.omni_present
+ scope = el[1]
+ dct = {}
+ glob[scope] = dct
+ if el[-1] != "/":
+ curr_els_attrs.append(dct)
+ continue
+ elif tag == "log":
+ curr_els_attrs.append(log.attributes)
+ continue
+ elif tag == "list":
+ dct_children = {}
+ dct = {"value": None, "children": dct_children}
+ curr_els_attrs[-1][el[1]] = dct
+ curr_els_attrs.append(dct_children)
+ continue
+ else:
+ if el == "event":
+ event = Event()
+ curr_els_attrs.append(event)
+ trace.append(event)
+ continue
+ elif el == "trace":
+ trace = Trace()
+ curr_els_attrs.append(trace.attributes)
+ log.append(trace)
+ continue
+ elif el == "log":
+ curr_els_attrs.append(log.attributes)
+ continue
+ elif el == "values":
+ curr_els_attrs.append(curr_els_attrs[-1])
+ cont = F.read(nb)
+ return log
+
+
+def import_log(filename, parameters=None):
+ """
+ Import a log object from a XML file containing the traces, the events
+ and the simple attributes of them.
+
+ Parameters
+ ----------
+ filename
+ XES file to parse
+ parameters
+ Parameters of the algorithm, including:
+
+ - Parameters.TIMESTAMP_SORT: Specify if we should sort log by timestamp.
+ - Parameters.TIMESTAMP_KEY: If sort is enabled, then sort the log by using this key.
+ - Parameters.REVERSE_SORT: Specify in which direction the log should be sorted.
+ - Parameters.MAX_TRACES: Specify the maximum number of traces to import.
+ - Parameters.MAX_BYTES: Maximum number of bytes to read.
+ - Parameters.SKYP_BYTES: Number of bytes to skip.
+ - Parameters.SET_ATTRIBUTES_TO_READ: Names of the attributes that should be parsed.
+ If not specified, then all attributes are parsed.
+ - Parameters.ENCODING: Regulates the encoding of the log (default: utf-8).
+
+ Returns
+ -------
+ log
+ Log file
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ is_compressed = filename.endswith(".gz")
+ file_size = os.stat(filename).st_size
+
+ if is_compressed:
+ f = gzip.open(filename, mode="rb")
+ else:
+ f = open(filename, "rb")
+
+ log = import_log_from_file_object(
+ f, encoding, file_size=file_size, parameters=parameters
+ )
+
+ f.close()
+
+ return log
+
+
+def import_from_string(log_string, parameters=None):
+ """
+ Deserialize a text/binary string representing a XES log
+
+ Parameters
+ -----------
+ log_string
+ String that contains the XES
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ log
+ Trace log object
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ decompress_serialization = exec_utils.get_param_value(
+ Parameters.DECOMPRESS_SERIALIZATION, parameters, False
+ )
+
+ if type(log_string) is str:
+ log_string = log_string.encode(constants.DEFAULT_ENCODING)
+
+ b = BytesIO(log_string)
+
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+
+ log = import_log_from_file_object(s, encoding, parameters=parameters)
+ s.close()
+ b.close()
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f8d6ad56b46e23bb9e985d867caf843bd12248e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse.py
@@ -0,0 +1,571 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import logging
+import importlib.util
+import sys
+from enum import Enum
+from io import BytesIO
+
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.objects.log.util import sorting
+from pm4py.util import exec_utils, constants
+from pm4py.util import xes_constants
+from pm4py.util.dt_parsing import parser as dt_parser
+
+
+class Parameters(Enum):
+ TIMESTAMP_SORT = "timestamp_sort"
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ REVERSE_SORT = "reverse_sort"
+ MAX_TRACES = "max_traces"
+ SHOW_PROGRESS_BAR = "show_progress_bar"
+ DECOMPRESS_SERIALIZATION = "decompress_serialization"
+ ENCODING = "encoding"
+
+
+# ITERPARSE EVENTS
+_EVENT_END = "end"
+_EVENT_START = "start"
+
+
+def count_traces(context):
+ """
+ Efficiently count the number of traces of a XES event log
+
+ Parameters
+ -------------
+ context
+ XML iterparse context
+ Returns
+ -------------
+ num_traces
+ Number of traces of the XES log
+ """
+ num_traces = 0
+
+ for tree_event, elem in context:
+ if tree_event == _EVENT_START: # starting to read
+ if elem.tag.endswith(xes_constants.TAG_TRACE):
+ num_traces = num_traces + 1
+ elem.clear()
+
+ del context
+
+ return num_traces
+
+
+def import_from_context(context, num_traces, parameters=None):
+ """
+ Import a XES log from an iterparse context
+
+ Parameters
+ --------------
+ context
+ Iterparse context
+ num_traces
+ Number of traces of the XES log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ log
+ Event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ max_no_traces_to_import = exec_utils.get_param_value(
+ Parameters.MAX_TRACES, parameters, sys.maxsize
+ )
+ timestamp_sort = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_SORT, parameters, False
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ reverse_sort = exec_utils.get_param_value(
+ Parameters.REVERSE_SORT, parameters, False
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+
+ date_parser = dt_parser.get()
+ progress = None
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ from tqdm.auto import tqdm
+
+ progress = tqdm(
+ total=num_traces, desc="parsing log, completed traces :: "
+ )
+
+ log = None
+ trace = None
+ event = None
+
+ tree = {}
+
+ for tree_event, elem in context:
+ if tree_event == _EVENT_START: # starting to read
+ parent = (
+ tree[elem.getparent()] if elem.getparent() in tree else None
+ )
+
+ if elem.tag.endswith(xes_constants.TAG_STRING):
+ if parent is not None:
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ elem.get(xes_constants.KEY_VALUE),
+ tree,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_DATE):
+ try:
+ dt = date_parser.apply(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem, parent, elem.get(xes_constants.KEY_KEY), dt, tree
+ )
+ except TypeError:
+ logging.info(
+ "failed to parse date: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse date: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_EVENT):
+ if event is not None:
+ raise SyntaxError(
+ "file contains in another tag"
+ )
+ event = Event()
+ tree[elem] = event
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_TRACE):
+ if len(log) >= max_no_traces_to_import:
+ break
+ if trace is not None:
+ raise SyntaxError(
+ "file contains in another tag"
+ )
+ trace = Trace()
+ tree[elem] = trace.attributes
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_FLOAT):
+ if parent is not None:
+ try:
+ val = float(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse float: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_INT):
+ if parent is not None:
+ try:
+ val = int(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse int: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_BOOLEAN):
+ if parent is not None:
+ try:
+ val0 = elem.get(xes_constants.KEY_VALUE)
+ val = False
+ if str(val0).lower() == "true":
+ val = True
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse boolean: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LIST):
+ if parent is not None:
+ # lists have no value, hence we put None as a value
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ None,
+ tree,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_ID):
+ if parent is not None:
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ elem.get(xes_constants.KEY_VALUE),
+ tree,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_EXTENSION):
+ if log is None:
+ raise SyntaxError("extension found outside of tag")
+ if (
+ elem.get(xes_constants.KEY_NAME) is not None
+ and elem.get(xes_constants.KEY_PREFIX) is not None
+ and elem.get(xes_constants.KEY_URI) is not None
+ ):
+ log.extensions[elem.get(xes_constants.KEY_NAME)] = {
+ xes_constants.KEY_PREFIX: elem.get(
+ xes_constants.KEY_PREFIX
+ ),
+ xes_constants.KEY_URI: elem.get(xes_constants.KEY_URI),
+ }
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_GLOBAL):
+ if log is None:
+ raise SyntaxError("global found outside of tag")
+ if elem.get(xes_constants.KEY_SCOPE) is not None:
+ log.omni_present[elem.get(xes_constants.KEY_SCOPE)] = {}
+ tree[elem] = log.omni_present[
+ elem.get(xes_constants.KEY_SCOPE)
+ ]
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_CLASSIFIER):
+ if log is None:
+ raise SyntaxError("classifier found outside of tag")
+ if elem.get(xes_constants.KEY_KEYS) is not None:
+ classifier_value = elem.get(xes_constants.KEY_KEYS)
+ if "'" in classifier_value:
+ log.classifiers[elem.get(xes_constants.KEY_NAME)] = [
+ x for x in classifier_value.split("'") if x.strip()
+ ]
+ else:
+ log.classifiers[elem.get(xes_constants.KEY_NAME)] = (
+ classifier_value.split()
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LOG):
+ if log is not None:
+ raise SyntaxError("file contains > 1 tags")
+ log = EventLog()
+ tree[elem] = log.attributes
+ continue
+
+ elif tree_event == _EVENT_END:
+ if elem in tree:
+ del tree[elem]
+ elem.clear()
+ if elem.getprevious() is not None:
+ try:
+ del elem.getparent()[0]
+ except TypeError:
+ pass
+
+ if elem.tag.endswith(xes_constants.TAG_EVENT):
+ if trace is not None:
+ trace.append(event)
+ event = None
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_TRACE):
+ log.append(trace)
+
+ if progress is not None:
+ progress.update()
+
+ trace = None
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LOG):
+ continue
+
+ # gracefully close progress bar
+ if progress is not None:
+ progress.close()
+ del context, progress
+
+ if timestamp_sort:
+ log = sorting.sort_timestamp(
+ log, timestamp_key=timestamp_key, reverse_sort=reverse_sort
+ )
+
+ # sets the activity key as default classifier in the log's properties
+ log.properties[constants.PARAMETER_CONSTANT_ACTIVITY_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ log.properties[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ # sets the default timestamp key
+ log.properties[constants.PARAMETER_CONSTANT_TIMESTAMP_KEY] = (
+ xes_constants.DEFAULT_TIMESTAMP_KEY
+ )
+ # sets the default resource key
+ log.properties[constants.PARAMETER_CONSTANT_RESOURCE_KEY] = (
+ xes_constants.DEFAULT_RESOURCE_KEY
+ )
+ # sets the default transition key
+ log.properties[constants.PARAMETER_CONSTANT_TRANSITION_KEY] = (
+ xes_constants.DEFAULT_TRANSITION_KEY
+ )
+ # sets the default group key
+ log.properties[constants.PARAMETER_CONSTANT_GROUP_KEY] = (
+ xes_constants.DEFAULT_GROUP_KEY
+ )
+
+ return log
+
+
+def apply(filename, parameters=None):
+ """
+ Imports an XES file into a log object
+
+ Parameters
+ ----------
+ filename:
+ Absolute filename
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ A log
+ """
+ return import_log(filename, parameters)
+
+
+def import_log(filename, parameters=None):
+ """
+ Imports an XES file into a log object
+
+ Parameters
+ ----------
+ filename:
+ Absolute filename
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ A log
+ """
+ from lxml import etree
+
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+ is_compressed = filename.lower().endswith(".gz")
+
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ if is_compressed:
+ f = gzip.open(filename, "rb")
+ else:
+ f = open(filename, "rb")
+ context = etree.iterparse(
+ f, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ num_traces = count_traces(context)
+ f.close()
+ else:
+ # avoid the iteration to calculate the number of traces is "tqdm" is
+ # not used
+ num_traces = 0
+
+ if is_compressed:
+ f = gzip.open(filename, "rb")
+ else:
+ f = open(filename, "rb")
+ context = etree.iterparse(
+ f, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+
+ log = import_from_context(context, num_traces, parameters=parameters)
+ f.close()
+ return log
+
+
+def import_from_string(log_string, parameters=None):
+ """
+ Deserialize a text/binary string representing a XES log
+
+ Parameters
+ -----------
+ log_string
+ String that contains the XES
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.INSERT_TRACE_INDICES -> Specify if trace indexes should be added as event attribute for each event
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -----------
+ log
+ Trace log object
+ """
+ from lxml import etree
+
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+ decompress_serialization = exec_utils.get_param_value(
+ Parameters.DECOMPRESS_SERIALIZATION, parameters, False
+ )
+
+ if type(log_string) is str:
+ log_string = log_string.encode(constants.DEFAULT_ENCODING)
+
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ # first iteration: count the number of traces
+ b = BytesIO(log_string)
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+ context = etree.iterparse(
+ s, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ num_traces = count_traces(context)
+ s.close()
+ b.close()
+ else:
+ # avoid the iteration to calculate the number of traces is "tqdm" is
+ # not used
+ num_traces = 0
+
+ # second iteration: actually read the content
+ b = BytesIO(log_string)
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+ context = etree.iterparse(
+ s, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ log = import_from_context(context, num_traces, parameters=parameters)
+ s.close()
+ b.close()
+ return log
+
+
+def __parse_attribute(elem, store, key, value, tree):
+ if len(elem.getchildren()) == 0:
+ if type(store) is list:
+ # changes to the store of lists: not dictionaries anymore
+ # but pairs of key-values.
+ store.append((key, value))
+ else:
+ store[key] = value
+ else:
+ if elem.getchildren()[0].tag.endswith(xes_constants.TAG_VALUES):
+ attribute = {
+ xes_constants.KEY_VALUE: value,
+ xes_constants.KEY_CHILDREN: list(),
+ }
+ if type(store) is list:
+ store.append((key, attribute))
+ else:
+ store[key] = attribute
+ tree[elem] = attribute[xes_constants.KEY_CHILDREN]
+ tree[elem.getchildren()[0]] = tree[elem]
+ else:
+ attribute = {
+ xes_constants.KEY_VALUE: value,
+ xes_constants.KEY_CHILDREN: dict(),
+ }
+ if type(store) is list:
+ store.append((key, attribute))
+ else:
+ store[key] = attribute
+ tree[elem] = attribute[xes_constants.KEY_CHILDREN]
+ return tree
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse_20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse_20.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bf4ab6a929f3b719fd6d078bbcc0981125bf49d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse_20.py
@@ -0,0 +1,574 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import logging
+import importlib.util
+import sys
+from enum import Enum
+from io import BytesIO
+
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.objects.log.util import sorting
+from pm4py.util import exec_utils, constants
+from pm4py.util import xes_constants
+from pm4py.util.dt_parsing import parser as dt_parser
+
+
+class Parameters(Enum):
+ TIMESTAMP_SORT = "timestamp_sort"
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ REVERSE_SORT = "reverse_sort"
+ MAX_TRACES = "max_traces"
+ SHOW_PROGRESS_BAR = "show_progress_bar"
+ DECOMPRESS_SERIALIZATION = "decompress_serialization"
+ ENCODING = "encoding"
+
+
+# ITERPARSE EVENTS
+_EVENT_END = "end"
+_EVENT_START = "start"
+
+
+def count_traces(context):
+ """
+ Efficiently count the number of traces of a XES event log
+
+ Parameters
+ -------------
+ context
+ XML iterparse context
+ Returns
+ -------------
+ num_traces
+ Number of traces of the XES log
+ """
+ num_traces = 0
+
+ for tree_event, elem in context:
+ if tree_event == _EVENT_START: # starting to read
+ if elem.tag.endswith(xes_constants.TAG_TRACE):
+ num_traces = num_traces + 1
+ elem.clear()
+
+ del context
+
+ return num_traces
+
+
+def import_from_context(context, num_traces, parameters=None):
+ """
+ Import a XES log from an iterparse context
+
+ Parameters
+ --------------
+ context
+ Iterparse context
+ num_traces
+ Number of traces of the XES log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ log
+ Event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ max_no_traces_to_import = exec_utils.get_param_value(
+ Parameters.MAX_TRACES, parameters, sys.maxsize
+ )
+ timestamp_sort = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_SORT, parameters, False
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ reverse_sort = exec_utils.get_param_value(
+ Parameters.REVERSE_SORT, parameters, False
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+
+ date_parser = dt_parser.get()
+ progress = None
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ from tqdm.auto import tqdm
+
+ progress = tqdm(
+ total=num_traces, desc="parsing log, completed traces :: "
+ )
+
+ log = None
+ trace = None
+ event = None
+
+ tree = {}
+
+ for tree_event, elem in context:
+ if tree_event == _EVENT_START: # starting to read
+ parent = (
+ tree[elem.getparent()] if elem.getparent() in tree else None
+ )
+
+ if elem.tag.endswith(xes_constants.TAG_STRING):
+ if parent is not None:
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ elem.get(xes_constants.KEY_VALUE),
+ tree,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_DATE):
+ try:
+ dt = date_parser.apply(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem, parent, elem.get(xes_constants.KEY_KEY), dt, tree
+ )
+ except TypeError:
+ logging.info(
+ "failed to parse date: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse date: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_EVENT):
+ if event is not None:
+ raise SyntaxError(
+ "file contains in another tag"
+ )
+ event = Event()
+ tree[elem] = event
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_TRACE):
+ if len(log) >= max_no_traces_to_import:
+ break
+ if trace is not None:
+ raise SyntaxError(
+ "file contains in another tag"
+ )
+ trace = Trace()
+ tree[elem] = trace.attributes
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_FLOAT):
+ if parent is not None:
+ try:
+ val = float(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse float: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_INT):
+ if parent is not None:
+ try:
+ val = int(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse int: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_BOOLEAN):
+ if parent is not None:
+ try:
+ val0 = elem.get(xes_constants.KEY_VALUE)
+ val = False
+ if str(val0).lower() == "true":
+ val = True
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse boolean: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(
+ xes_constants.TAG_LIST
+ ) or elem.tag.endswith(xes_constants.TAG_CONTAINER):
+ if parent is not None:
+ # lists have no value, hence we put None as a value
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ None,
+ tree,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_ID):
+ if parent is not None:
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ elem.get(xes_constants.KEY_VALUE),
+ tree,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_EXTENSION):
+ if log is None:
+ raise SyntaxError("extension found outside of tag")
+ if (
+ elem.get(xes_constants.KEY_NAME) is not None
+ and elem.get(xes_constants.KEY_PREFIX) is not None
+ and elem.get(xes_constants.KEY_URI) is not None
+ ):
+ log.extensions[elem.get(xes_constants.KEY_NAME)] = {
+ xes_constants.KEY_PREFIX: elem.get(
+ xes_constants.KEY_PREFIX
+ ),
+ xes_constants.KEY_URI: elem.get(xes_constants.KEY_URI),
+ }
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_GLOBAL):
+ if log is None:
+ raise SyntaxError("global found outside of tag")
+ if elem.get(xes_constants.KEY_SCOPE) is not None:
+ log.omni_present[elem.get(xes_constants.KEY_SCOPE)] = {}
+ tree[elem] = log.omni_present[
+ elem.get(xes_constants.KEY_SCOPE)
+ ]
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_CLASSIFIER):
+ if log is None:
+ raise SyntaxError("classifier found outside of tag")
+ if elem.get(xes_constants.KEY_KEYS) is not None:
+ classifier_value = elem.get(xes_constants.KEY_KEYS)
+ if "'" in classifier_value:
+ log.classifiers[elem.get(xes_constants.KEY_NAME)] = [
+ x for x in classifier_value.split("'") if x.strip()
+ ]
+ else:
+ log.classifiers[elem.get(xes_constants.KEY_NAME)] = (
+ classifier_value.split()
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LOG):
+ if log is not None:
+ raise SyntaxError("file contains > 1 tags")
+ log = EventLog()
+ tree[elem] = log.attributes
+ continue
+
+ elif tree_event == _EVENT_END:
+ if elem in tree:
+ del tree[elem]
+ elem.clear()
+ if elem.getprevious() is not None:
+ try:
+ del elem.getparent()[0]
+ except TypeError:
+ pass
+
+ if elem.tag.endswith(xes_constants.TAG_EVENT):
+ if trace is not None:
+ trace.append(event)
+ event = None
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_TRACE):
+ log.append(trace)
+
+ if progress is not None:
+ progress.update()
+
+ trace = None
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LOG):
+ continue
+
+ # gracefully close progress bar
+ if progress is not None:
+ progress.close()
+ del context, progress
+
+ if timestamp_sort:
+ log = sorting.sort_timestamp(
+ log, timestamp_key=timestamp_key, reverse_sort=reverse_sort
+ )
+
+ # sets the activity key as default classifier in the log's properties
+ log.properties[constants.PARAMETER_CONSTANT_ACTIVITY_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ log.properties[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ # sets the default timestamp key
+ log.properties[constants.PARAMETER_CONSTANT_TIMESTAMP_KEY] = (
+ xes_constants.DEFAULT_TIMESTAMP_KEY
+ )
+ # sets the default resource key
+ log.properties[constants.PARAMETER_CONSTANT_RESOURCE_KEY] = (
+ xes_constants.DEFAULT_RESOURCE_KEY
+ )
+ # sets the default transition key
+ log.properties[constants.PARAMETER_CONSTANT_TRANSITION_KEY] = (
+ xes_constants.DEFAULT_TRANSITION_KEY
+ )
+ # sets the default group key
+ log.properties[constants.PARAMETER_CONSTANT_GROUP_KEY] = (
+ xes_constants.DEFAULT_GROUP_KEY
+ )
+
+ return log
+
+
+def apply(filename, parameters=None):
+ """
+ Imports an XES file into a log object
+
+ Parameters
+ ----------
+ filename:
+ Absolute filename
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ A log
+ """
+ return import_log(filename, parameters)
+
+
+def import_log(filename, parameters=None):
+ """
+ Imports an XES file into a log object
+
+ Parameters
+ ----------
+ filename:
+ Absolute filename
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ A log
+ """
+ from lxml import etree
+
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+ is_compressed = filename.lower().endswith(".gz")
+
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ if is_compressed:
+ f = gzip.open(filename, "rb")
+ else:
+ f = open(filename, "rb")
+ context = etree.iterparse(
+ f, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ num_traces = count_traces(context)
+ f.close()
+ else:
+ # avoid the iteration to calculate the number of traces is "tqdm" is
+ # not used
+ num_traces = 0
+
+ if is_compressed:
+ f = gzip.open(filename, "rb")
+ else:
+ f = open(filename, "rb")
+ context = etree.iterparse(
+ f, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+
+ log = import_from_context(context, num_traces, parameters=parameters)
+ f.close()
+ return log
+
+
+def import_from_string(log_string, parameters=None):
+ """
+ Deserialize a text/binary string representing a XES log
+
+ Parameters
+ -----------
+ log_string
+ String that contains the XES
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.INSERT_TRACE_INDICES -> Specify if trace indexes should be added as event attribute for each event
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -----------
+ log
+ Trace log object
+ """
+ from lxml import etree
+
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+ decompress_serialization = exec_utils.get_param_value(
+ Parameters.DECOMPRESS_SERIALIZATION, parameters, False
+ )
+
+ if type(log_string) is str:
+ log_string = log_string.encode(constants.DEFAULT_ENCODING)
+
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ # first iteration: count the number of traces
+ b = BytesIO(log_string)
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+ context = etree.iterparse(
+ s, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ num_traces = count_traces(context)
+ s.close()
+ b.close()
+ else:
+ # avoid the iteration to calculate the number of traces is "tqdm" is
+ # not used
+ num_traces = 0
+
+ # second iteration: actually read the content
+ b = BytesIO(log_string)
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+ context = etree.iterparse(
+ s, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ log = import_from_context(context, num_traces, parameters=parameters)
+ s.close()
+ b.close()
+ return log
+
+
+def __parse_attribute(elem, store, key, value, tree):
+ if len(elem.getchildren()) == 0:
+ if type(store) is list:
+ # changes to the store of lists: not dictionaries anymore
+ # but pairs of key-values.
+ store.append((key, value))
+ elif type(store) is set:
+ store.add((key, value))
+ else:
+ store[key] = value
+ else:
+ if elem.tag.endswith(xes_constants.TAG_LIST):
+ attribute = {
+ xes_constants.KEY_VALUE: value,
+ xes_constants.KEY_CHILDREN: list(),
+ }
+ elif elem.tag.endswith(xes_constants.TAG_CONTAINER):
+ attribute = {
+ xes_constants.KEY_VALUE: value,
+ xes_constants.KEY_CHILDREN: set(),
+ }
+ else:
+ attribute = {
+ xes_constants.KEY_VALUE: value,
+ xes_constants.KEY_CHILDREN: dict(),
+ }
+ if type(store) is list:
+ store.append((key, attribute))
+ else:
+ store[key] = attribute
+ tree[elem] = attribute[xes_constants.KEY_CHILDREN]
+ return tree
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse_mem_compressed.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse_mem_compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee463cea3c966547e1e057257affe2e26b4c02ae
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/iterparse_mem_compressed.py
@@ -0,0 +1,591 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import logging
+import importlib.util
+import sys
+from enum import Enum
+from io import BytesIO
+
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.objects.log.util import sorting
+from pm4py.util import exec_utils, constants
+from pm4py.util import xes_constants
+from pm4py.util.dt_parsing import parser as dt_parser
+
+
+class Parameters(Enum):
+ TIMESTAMP_SORT = "timestamp_sort"
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ REVERSE_SORT = "reverse_sort"
+ MAX_TRACES = "max_traces"
+ SHOW_PROGRESS_BAR = "show_progress_bar"
+ DECOMPRESS_SERIALIZATION = "decompress_serialization"
+ ENCODING = "encoding"
+
+
+# ITERPARSE EVENTS
+_EVENT_END = "end"
+_EVENT_START = "start"
+
+
+def count_traces(context):
+ """
+ Efficiently count the number of traces of a XES event log
+
+ Parameters
+ -------------
+ context
+ XML iterparse context
+ Returns
+ -------------
+ num_traces
+ Number of traces of the XES log
+ """
+ num_traces = 0
+
+ for tree_event, elem in context:
+ if tree_event == _EVENT_START: # starting to read
+ if elem.tag.endswith(xes_constants.TAG_TRACE):
+ num_traces = num_traces + 1
+ elem.clear()
+
+ del context
+
+ return num_traces
+
+
+def import_from_context(context, num_traces, log, parameters=None):
+ """
+ Import a XES log from an iterparse context
+
+ Parameters
+ --------------
+ context
+ Iterparse context
+ num_traces
+ Number of traces of the XES log
+ log
+ Event log (empty)
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ log
+ Event log (filled with the contents of the XES log)
+ """
+ if parameters is None:
+ parameters = {}
+
+ max_no_traces_to_import = exec_utils.get_param_value(
+ Parameters.MAX_TRACES, parameters, sys.maxsize
+ )
+ timestamp_sort = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_SORT, parameters, False
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ reverse_sort = exec_utils.get_param_value(
+ Parameters.REVERSE_SORT, parameters, False
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+
+ date_parser = dt_parser.get()
+ progress = None
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ from tqdm.auto import tqdm
+
+ progress = tqdm(
+ total=num_traces, desc="parsing log, completed traces :: "
+ )
+
+ trace = None
+ event = None
+
+ tree = {}
+ compression_dictio = {}
+
+ for tree_event, elem in context:
+ if tree_event == _EVENT_START: # starting to read
+ parent = (
+ tree[elem.getparent()] if elem.getparent() in tree else None
+ )
+
+ if elem.tag.endswith(xes_constants.TAG_STRING):
+ if parent is not None:
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ elem.get(xes_constants.KEY_VALUE),
+ tree,
+ compression_dictio,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_DATE):
+ try:
+ dt = date_parser.apply(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ dt,
+ tree,
+ compression_dictio,
+ )
+ except TypeError:
+ logging.info(
+ "failed to parse date: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse date: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_EVENT):
+ if event is not None:
+ raise SyntaxError(
+ "file contains in another tag"
+ )
+ event = Event()
+ tree[elem] = event
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_TRACE):
+ if len(log) >= max_no_traces_to_import:
+ break
+ if trace is not None:
+ raise SyntaxError(
+ "file contains in another tag"
+ )
+ trace = Trace()
+ tree[elem] = trace.attributes
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_FLOAT):
+ if parent is not None:
+ try:
+ val = float(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ compression_dictio,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse float: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_INT):
+ if parent is not None:
+ try:
+ val = int(elem.get(xes_constants.KEY_VALUE))
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ compression_dictio,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse int: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_BOOLEAN):
+ if parent is not None:
+ try:
+ val0 = elem.get(xes_constants.KEY_VALUE)
+ val = False
+ if str(val0).lower() == "true":
+ val = True
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ val,
+ tree,
+ compression_dictio,
+ )
+ except ValueError:
+ logging.info(
+ "failed to parse boolean: "
+ + str(elem.get(xes_constants.KEY_VALUE))
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LIST):
+ if parent is not None:
+ # lists have no value, hence we put None as a value
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ None,
+ tree,
+ compression_dictio,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_ID):
+ if parent is not None:
+ tree = __parse_attribute(
+ elem,
+ parent,
+ elem.get(xes_constants.KEY_KEY),
+ elem.get(xes_constants.KEY_VALUE),
+ tree,
+ compression_dictio,
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_EXTENSION):
+ if (
+ elem.get(xes_constants.KEY_NAME) is not None
+ and elem.get(xes_constants.KEY_PREFIX) is not None
+ and elem.get(xes_constants.KEY_URI) is not None
+ ):
+ log.extensions[elem.get(xes_constants.KEY_NAME)] = {
+ xes_constants.KEY_PREFIX: elem.get(
+ xes_constants.KEY_PREFIX
+ ),
+ xes_constants.KEY_URI: elem.get(xes_constants.KEY_URI),
+ }
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_GLOBAL):
+ if elem.get(xes_constants.KEY_SCOPE) is not None:
+ log.omni_present[elem.get(xes_constants.KEY_SCOPE)] = {}
+ tree[elem] = log.omni_present[
+ elem.get(xes_constants.KEY_SCOPE)
+ ]
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_CLASSIFIER):
+ if elem.get(xes_constants.KEY_KEYS) is not None:
+ classifier_value = elem.get(xes_constants.KEY_KEYS)
+ if "'" in classifier_value:
+ log.classifiers[elem.get(xes_constants.KEY_NAME)] = [
+ x for x in classifier_value.split("'") if x.strip()
+ ]
+ else:
+ log.classifiers[elem.get(xes_constants.KEY_NAME)] = (
+ classifier_value.split()
+ )
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LOG):
+ tree[elem] = log.attributes
+ continue
+
+ elif tree_event == _EVENT_END:
+ if elem in tree:
+ del tree[elem]
+ elem.clear()
+ if elem.getprevious() is not None:
+ try:
+ del elem.getparent()[0]
+ except TypeError:
+ pass
+
+ if elem.tag.endswith(xes_constants.TAG_EVENT):
+ if trace is not None:
+ trace.append(event)
+ event = None
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_TRACE):
+ log.append(trace)
+
+ if progress is not None:
+ progress.update()
+
+ trace = None
+ continue
+
+ elif elem.tag.endswith(xes_constants.TAG_LOG):
+ continue
+
+ # gracefully close progress bar
+ if progress is not None:
+ progress.close()
+ del context, progress
+
+ if timestamp_sort:
+ log = sorting.sort_timestamp(
+ log, timestamp_key=timestamp_key, reverse_sort=reverse_sort
+ )
+
+ # sets the activity key as default classifier in the log's properties
+ log.properties[constants.PARAMETER_CONSTANT_ACTIVITY_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ log.properties[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ # sets the default timestamp key
+ log.properties[constants.PARAMETER_CONSTANT_TIMESTAMP_KEY] = (
+ xes_constants.DEFAULT_TIMESTAMP_KEY
+ )
+ # sets the default resource key
+ log.properties[constants.PARAMETER_CONSTANT_RESOURCE_KEY] = (
+ xes_constants.DEFAULT_RESOURCE_KEY
+ )
+ # sets the default transition key
+ log.properties[constants.PARAMETER_CONSTANT_TRANSITION_KEY] = (
+ xes_constants.DEFAULT_TRANSITION_KEY
+ )
+ # sets the default group key
+ log.properties[constants.PARAMETER_CONSTANT_GROUP_KEY] = (
+ xes_constants.DEFAULT_GROUP_KEY
+ )
+
+ return log
+
+
+def apply(filename, parameters=None):
+ """
+ Imports an XES file into a log object
+
+ Parameters
+ ----------
+ filename:
+ Absolute filename
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ A log
+ """
+ return import_log(filename, parameters)
+
+
+def import_log(filename, parameters=None):
+ """
+ Imports an XES file into a log object
+
+ Parameters
+ ----------
+ filename:
+ Absolute filename
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -------
+ log : :class:`pm4py.log.log.EventLog`
+ A log
+ """
+ from lxml import etree
+
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+ is_compressed = filename.lower().endswith(".gz")
+
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ if is_compressed:
+ f = gzip.open(filename, "rb")
+ else:
+ f = open(filename, "rb")
+ context = etree.iterparse(
+ f, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ num_traces = count_traces(context)
+ f.close()
+ else:
+ # avoid the iteration to calculate the number of traces is "tqdm" is
+ # not used
+ num_traces = 0
+
+ if is_compressed:
+ f = gzip.open(filename, "rb")
+ else:
+ f = open(filename, "rb")
+ context = etree.iterparse(
+ f, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+
+ log = EventLog()
+ log = import_from_context(context, num_traces, log, parameters=parameters)
+ f.close()
+ return log
+
+
+def import_from_string(log_string, parameters=None):
+ """
+ Deserialize a text/binary string representing a XES log
+
+ Parameters
+ -----------
+ log_string
+ String that contains the XES
+ parameters
+ Parameters of the algorithm, including
+ Parameters.TIMESTAMP_SORT -> Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY -> If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT -> Specify in which direction the log should be sorted
+ Parameters.INSERT_TRACE_INDICES -> Specify if trace indexes should be added as event attribute for each event
+ Parameters.MAX_TRACES -> Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.SHOW_PROGRESS_BAR -> Enables/disables the progress bar (default: True)
+ Parameters.ENCODING -> regulates the encoding (default: utf-8)
+
+ Returns
+ -----------
+ log
+ Trace log object
+ """
+ from lxml import etree
+
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+ show_progress_bar = exec_utils.get_param_value(
+ Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR
+ )
+ decompress_serialization = exec_utils.get_param_value(
+ Parameters.DECOMPRESS_SERIALIZATION, parameters, False
+ )
+
+ if type(log_string) is str:
+ log_string = log_string.encode(constants.DEFAULT_ENCODING)
+
+ if importlib.util.find_spec("tqdm") and show_progress_bar:
+ # first iteration: count the number of traces
+ b = BytesIO(log_string)
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+ context = etree.iterparse(
+ s, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ num_traces = count_traces(context)
+ s.close()
+ b.close()
+ else:
+ # avoid the iteration to calculate the number of traces is "tqdm" is
+ # not used
+ num_traces = 0
+
+ # second iteration: actually read the content
+ b = BytesIO(log_string)
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+ context = etree.iterparse(
+ s, events=[_EVENT_START, _EVENT_END], encoding=encoding
+ )
+ log = EventLog()
+ log = import_from_context(context, num_traces, log, parameters=parameters)
+ s.close()
+ b.close()
+ return log
+
+
+def __parse_attribute(elem, store, key, value, tree, compression_dict):
+ if len(elem.getchildren()) == 0:
+ if key in compression_dict:
+ # using existing istantiations of existing objects
+ key = compression_dict[key]
+ else:
+ # set up a new instantiation
+ compression_dict[key] = key
+
+ if value in compression_dict:
+ # using existing istantiations of existing objects
+ value = compression_dict[value]
+ else:
+ # set up a new instantiation
+ compression_dict[value] = value
+
+ if type(store) is list:
+ # changes to the store of lists: not dictionaries anymore
+ # but pairs of key-values.
+ store.append((key, value))
+ else:
+ store[key] = value
+ else:
+ if elem.getchildren()[0].tag.endswith(xes_constants.TAG_VALUES):
+ attribute = {
+ xes_constants.KEY_VALUE: value,
+ xes_constants.KEY_CHILDREN: list(),
+ }
+ if type(store) is list:
+ store.append((key, attribute))
+ else:
+ store[key] = attribute
+ tree[elem] = attribute[xes_constants.KEY_CHILDREN]
+ tree[elem.getchildren()[0]] = tree[elem]
+ else:
+ attribute = {
+ xes_constants.KEY_VALUE: value,
+ xes_constants.KEY_CHILDREN: dict(),
+ }
+ if type(store) is list:
+ store.append((key, attribute))
+ else:
+ store[key] = attribute
+ tree[elem] = attribute[xes_constants.KEY_CHILDREN]
+ return tree
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/line_by_line.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/line_by_line.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fac4ce3748bc0f6f5b2ae2b82b2e0178d483c1d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/line_by_line.py
@@ -0,0 +1,350 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import os
+import sys
+from enum import Enum
+from io import BytesIO
+
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.objects.log.util import sorting
+from pm4py.util import constants, xes_constants, exec_utils
+from pm4py.util.dt_parsing import parser as dt_parser
+
+
+class Parameters(Enum):
+ TIMESTAMP_SORT = "timestamp_sort"
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ REVERSE_SORT = "reverse_sort"
+ MAX_TRACES = "max_traces"
+ MAX_BYTES = "max_bytes"
+ SKIP_BYTES = "skip_bytes"
+ SET_ATTRIBUTES_TO_READ = "set_attributes_to_read"
+ DECOMPRESS_SERIALIZATION = "decompress_serialization"
+ ENCODING = "encoding"
+
+
+def apply(filename, parameters=None):
+ return import_log(filename, parameters)
+
+
+def __fetch_param_value(param, params):
+ return params[param] if param in params else param.value
+
+
+def read_attribute_key_value(
+ tag, content, date_parser, values_dict, set_attributes_to_read
+):
+ """
+ Reads an attribute from the line of the log
+
+ Parameters
+ --------------
+ tag
+ Tag
+ content
+ Full content of the line
+ date_parser
+ Date parser
+ values_dict
+ Dictionary of keys/values already met during the parsing
+ set_attributes_to_read
+ Names of the attributes that should be parsed. If None, then, all the attributes are parsed.
+
+ Returns
+ --------------
+ key
+ Key of the attribute
+ value
+ Value of the attribute
+ """
+ key = content[1]
+ value = None
+
+ if set_attributes_to_read is None or key in set_attributes_to_read:
+ if tag.startswith("string"):
+ value = content[3]
+ elif tag.startswith("date"):
+ value = date_parser.apply(content[3])
+ elif tag.startswith("int"):
+ value = int(content[3])
+ elif tag.startswith("float"):
+ value = float(content[3])
+ elif tag.startswith("boolean"):
+ value = True if content[3] == "true" else False
+ else:
+ value = content[3]
+
+ # limits the number of different instantiations of the same key
+ if key in values_dict:
+ key = values_dict[key]
+ else:
+ values_dict[key] = key
+
+ # limits the number of different instantations of the same value
+ if value in values_dict:
+ value = values_dict[value]
+ else:
+ values_dict[value] = value
+
+ return key, value
+
+
+def import_log_from_file_object(
+ f, encoding, file_size=sys.maxsize, parameters=None
+):
+ r"""
+ Deserialize a text/binary string representing a XES log.
+
+ Parameters
+ ----------
+ log_string : str or bytes
+ String that contains the XES.
+ parameters : dict, optional
+ Parameters of the algorithm, including:
+
+ - Parameters.TIMESTAMP_SORT: Specify if we should sort log by timestamp.
+ - Parameters.TIMESTAMP_KEY: If sort is enabled, then sort the log by using this key.
+ - Parameters.REVERSE_SORT: Specify in which direction the log should be sorted.
+ - Parameters.INSERT_TRACE_INDICES: Specify if trace indexes should be added as event attribute for each event.
+ - Parameters.MAX_TRACES: Specify the maximum number of traces to import.
+ - Parameters.DECOMPRESS_SERIALIZATION: Specify if the string needs to be decompressed.
+ - Parameters.SET_ATTRIBUTES_TO_READ: Names of the attributes that should be parsed.
+ If not specified, then all attributes are parsed.
+ - Parameters.ENCODING: Regulates the encoding of the log (default: utf-8).
+
+ Returns
+ -------
+ log
+ Trace log object.
+ """
+ values_dict = {}
+ date_parser = dt_parser.get()
+
+ set_attributes_to_read = exec_utils.get_param_value(
+ Parameters.SET_ATTRIBUTES_TO_READ, parameters, None
+ )
+ max_no_traces_to_import = exec_utils.get_param_value(
+ Parameters.MAX_TRACES, parameters, sys.maxsize
+ )
+ timestamp_sort = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_SORT, parameters, False
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ reverse_sort = exec_utils.get_param_value(
+ Parameters.REVERSE_SORT, parameters, False
+ )
+
+ skip_bytes = exec_utils.get_param_value(
+ Parameters.SKIP_BYTES, parameters, False
+ )
+ max_bytes_to_read = exec_utils.get_param_value(
+ Parameters.MAX_BYTES, parameters, sys.maxsize
+ )
+
+ if file_size > max_bytes_to_read:
+ skip_bytes = file_size - max_bytes_to_read
+
+ log = EventLog()
+ tracecount = 0
+ trace = None
+ event = None
+
+ f.seek(skip_bytes)
+
+ for line in f:
+ content = line.decode(encoding).split('"')
+ if len(content) > 0:
+ tag = content[0].split("<")[-1]
+ if trace is not None:
+ if event is not None:
+ if len(content) == 5:
+ key, value = read_attribute_key_value(
+ tag,
+ content,
+ date_parser,
+ values_dict,
+ set_attributes_to_read,
+ )
+ if value is not None:
+ event[key] = value
+ elif tag.startswith("/event"):
+ trace.append(event)
+ event = None
+ elif tag.startswith("event"):
+ event = Event()
+ elif len(content) == 5:
+ key, value = read_attribute_key_value(
+ tag,
+ content,
+ date_parser,
+ values_dict,
+ set_attributes_to_read,
+ )
+ if value is not None:
+ trace.attributes[key] = value
+ elif tag.startswith("/trace"):
+ log.append(trace)
+ tracecount += 1
+ if tracecount > max_no_traces_to_import:
+ break
+ trace = None
+ elif tag.startswith("trace"):
+ trace = Trace()
+
+ if timestamp_sort:
+ log = sorting.sort_timestamp(
+ log, timestamp_key=timestamp_key, reverse_sort=reverse_sort
+ )
+
+ # sets the activity key as default classifier in the log's properties
+ log.properties[constants.PARAMETER_CONSTANT_ACTIVITY_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ log.properties[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = (
+ xes_constants.DEFAULT_NAME_KEY
+ )
+ # sets the default timestamp key
+ log.properties[constants.PARAMETER_CONSTANT_TIMESTAMP_KEY] = (
+ xes_constants.DEFAULT_TIMESTAMP_KEY
+ )
+ # sets the default resource key
+ log.properties[constants.PARAMETER_CONSTANT_RESOURCE_KEY] = (
+ xes_constants.DEFAULT_RESOURCE_KEY
+ )
+ # sets the default transition key
+ log.properties[constants.PARAMETER_CONSTANT_TRANSITION_KEY] = (
+ xes_constants.DEFAULT_TRANSITION_KEY
+ )
+ # sets the default group key
+ log.properties[constants.PARAMETER_CONSTANT_GROUP_KEY] = (
+ xes_constants.DEFAULT_GROUP_KEY
+ )
+
+ return log
+
+
+def import_log(filename, parameters=None):
+ r"""
+ Import a log object from a XML file containing the traces, the events
+ and the simple attributes of them.
+
+ Parameters
+ ----------
+ filename
+ XES file to parse
+ parameters
+ Parameters of the algorithm, including:
+
+ - Parameters.TIMESTAMP_SORT: Specify if we should sort log by timestamp.
+ - Parameters.TIMESTAMP_KEY: If sort is enabled, then sort the log by using this key.
+ - Parameters.REVERSE_SORT: Specify in which direction the log should be sorted.
+ - Parameters.MAX_TRACES: Specify the maximum number of traces to import from the log (read in order in the XML file).
+ - Parameters.MAX_BYTES: Maximum number of bytes to read.
+ - Parameters.SKYP_BYTES: Number of bytes to skip.
+ - Parameters.SET_ATTRIBUTES_TO_READ: Names of the attributes that should be parsed.
+ If not specified, then all the attributes are parsed.
+ - Parameters.ENCODING: Regulates the encoding of the log (default: utf-8).
+
+ Returns
+ -------
+ log
+ Log file
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ is_compressed = filename.endswith(".gz")
+ file_size = os.stat(filename).st_size
+
+ if is_compressed:
+ f = gzip.open(filename, mode="rb")
+ else:
+ f = open(filename, "rb")
+
+ log = import_log_from_file_object(
+ f, encoding, file_size=file_size, parameters=parameters
+ )
+
+ f.close()
+
+ return log
+
+
+def import_from_string(log_string, parameters=None):
+ """
+ Deserialize a text/binary string representing a XES log.
+
+ Parameters
+ ----------
+ log_string
+ String that contains the XES
+ parameters
+ Parameters of the algorithm, including:
+
+ Parameters.TIMESTAMP_SORT: Specify if we should sort log by timestamp
+ Parameters.TIMESTAMP_KEY: If sort is enabled, then sort the log by using this key
+ Parameters.REVERSE_SORT: Specify in which direction the log should be sorted
+ Parameters.INSERT_TRACE_INDICES: Specify if trace indexes should be added as event attribute for each event
+ Parameters.MAX_TRACES: Specify the maximum number of traces to import from the log (read in order in the XML file)
+ Parameters.DECOMPRESS_SERIALIZATION: Specify if the string needs to be decompressed during the parsing
+ Parameters.SET_ATTRIBUTES_TO_READ: Names of the attributes that should be parsed. If not specified, then, all the attributes are parsed.
+ Parameters.ENCODING: Regulates the encoding of the log (default: utf-8)
+
+ Returns
+ -----------
+ log
+ Trace log object
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ decompress_serialization = exec_utils.get_param_value(
+ Parameters.DECOMPRESS_SERIALIZATION, parameters, False
+ )
+
+ if type(log_string) is str:
+ log_string = log_string.encode(constants.DEFAULT_ENCODING)
+
+ b = BytesIO(log_string)
+
+ if decompress_serialization:
+ s = gzip.GzipFile(fileobj=b, mode="rb")
+ else:
+ s = b
+
+ log = import_log_from_file_object(s, encoding, parameters=parameters)
+ s.close()
+ b.close()
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/rustxes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/rustxes.py
new file mode 100644
index 0000000000000000000000000000000000000000..148872751338806e092b9ffde32bfb08e20041d0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/importer/xes/variants/rustxes.py
@@ -0,0 +1,101 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from pm4py.util import exec_utils, constants
+from typing import Optional, Dict, Any, Union
+from pm4py.objects.log.obj import EventLog
+from pm4py.objects.conversion.log import converter as log_converter
+import pandas as pd
+from copy import copy
+from pm4py.util.dt_parsing.variants import strpfromiso
+import importlib.util
+from pm4py.util.rustxes_utils import import_rustxes_backend
+
+
+class Parameters(Enum):
+ RETURN_LEGACY_LOG_OBJECT = "return_legacy_log_object"
+ RETURN_PL_LAZYFRAME = "return_pl_lazyframe"
+
+
+def apply(
+ log_path: str, parameters: Optional[Dict[Any, Any]] = None
+) -> Union[EventLog, pd.DataFrame]:
+ if parameters is None:
+ parameters = {}
+
+ return_legacy_log_object = exec_utils.get_param_value(
+ Parameters.RETURN_LEGACY_LOG_OBJECT, parameters, True
+ )
+ return_pl_lazyframe = exec_utils.get_param_value(Parameters.RETURN_PL_LAZYFRAME, parameters, False)
+
+ rustxes_backend, _ = import_rustxes_backend()
+
+ log = rustxes_backend.import_xes(log_path)
+ log = log[0]
+
+ if not return_pl_lazyframe:
+ log = log.to_pandas()
+ for col in log.columns:
+ if "date" in str(log[col].dtype) or "time" in str(log[col].dtype):
+ log[col] = strpfromiso.fix_dataframe_column(log[col])
+ else:
+ import polars as pl
+
+ log = log.lazy()
+
+ schema = log.collect_schema()
+ datetime_expressions = []
+ for col_name, dtype in schema.items():
+ dtype_str = str(dtype).lower()
+ if "date" in dtype_str or "time" in dtype_str:
+ expr = pl.col(col_name)
+ has_timezone = "time_zone=" in dtype_str and "time_zone=none" not in dtype_str
+ if constants.ENABLE_DATETIME_COLUMNS_AWARE:
+ expr = (
+ expr.dt.convert_time_zone("UTC")
+ if has_timezone
+ else expr.dt.replace_time_zone("UTC")
+ )
+ datetime_expressions.append(expr.alias(col_name))
+ elif has_timezone:
+ datetime_expressions.append(expr.dt.replace_time_zone(None).alias(col_name))
+ if datetime_expressions:
+ log = log.with_columns(datetime_expressions)
+
+ log = log.collect().lazy()
+
+ if importlib.util.find_spec("cudf") and not return_pl_lazyframe:
+ import cudf
+
+ log = cudf.DataFrame(log)
+
+ if return_legacy_log_object:
+ this_parameters = copy(parameters)
+ this_parameters["stream_postprocessing"] = True
+
+ log = log_converter.apply(
+ log,
+ variant=log_converter.Variants.TO_EVENT_LOG,
+ parameters=this_parameters,
+ )
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..0de1a73ad7dc899b61c62aea35da8ddb28c1433d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/obj.py
@@ -0,0 +1,441 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+from collections.abc import Mapping, Sequence
+from enum import Enum
+
+
+class XESExtension(Enum):
+ ArtifactLifecycle = (
+ "ArtifactLifecycle",
+ "artifactlifecycle",
+ "http://www.xes-standard.org/artifactlifecycle.xesext",
+ )
+ Concept = (
+ "Concept",
+ "concept",
+ "http://www.xes-standard.org/concept.xesext",
+ )
+ Cost = ("Cost", "cost", "http://www.xes-standard.org/cost.xesext")
+ Identity = (
+ "Identity",
+ "identity",
+ "http://www.xes-standard.org/identity.xesext",
+ )
+ Lifecycle = (
+ "Lifecycle",
+ "lifecycle",
+ "http://www.xes-standard.org/lifecycle.xesext",
+ )
+ Micro = ("Micro", "micro", "http://www.xes-standard.org/micro.xesext")
+ Organizational = (
+ "Organizational",
+ "org",
+ "http://www.xes-standard.org/org.xesext",
+ )
+ Semantic = (
+ "Semantic",
+ "semantic",
+ "http://www.xes-standard.org/semantic.xesext",
+ )
+ SoftwareCommunication = (
+ "Software Communication",
+ "swcomm",
+ "http://www.xes-standard.org/swcomm.xesext",
+ )
+ SoftwareEvent = (
+ "Software Event",
+ "swevent",
+ "http://www.xes-standard.org/swevent.xesext",
+ )
+ SoftwareTelemetry = (
+ "Software Telemetry",
+ "swtelemetry",
+ "http://www.xes-standard.org/swtelemetry.xesext",
+ )
+ Time = ("Time", "time", "http://www.xes-standard.org/time.xesext")
+
+ def __init__(self, name, prefix, uri):
+ self._name = name
+ self._prefix = prefix
+ self._uri = uri
+
+ @property
+ def name(self):
+ return self._name
+
+ @property
+ def prefix(self):
+ return self._prefix
+
+ @property
+ def uri(self):
+ return self._uri
+
+
+class Event(Mapping):
+ def __init__(self, *args, **kw):
+ self._dict = dict(*args, **kw)
+
+ def __getitem__(self, key):
+ return self._dict[key]
+
+ def __setitem__(self, key, value):
+ self._dict[key] = value
+
+ def __iter__(self):
+ return iter(self._dict)
+
+ def __len__(self):
+ return len(self._dict)
+
+ def __delitem__(self, key):
+ del self._dict[key]
+
+ def __repr__(self):
+ return str(dict(self))
+
+ def __hash__(self):
+ return hash(frozenset((str(x), str(y)) for x, y in self.items()))
+
+ def __eq__(self, other):
+ return frozenset(
+ (str(x), str(y)) for x, y in self.items()
+ ) == frozenset((str(x), str(y)) for x, y in other.items())
+
+ def __copy__(self):
+ event = Event()
+ for k, v in self._dict.items():
+ event[k] = v
+ return event
+
+ def __deepcopy__(self, memodict={}):
+ event = Event()
+ for k, v in self._dict.items():
+ if type(v) is dict:
+ event[k] = copy.deepcopy(v)
+ else:
+ event[k] = v
+ return event
+
+
+class EventStream(Sequence):
+
+ def __init__(self, *args, **kwargs):
+ self._attributes = (
+ kwargs["attributes"] if "attributes" in kwargs else {}
+ )
+ self._extensions = (
+ kwargs["extensions"] if "extensions" in kwargs else {}
+ )
+ self._omni = (
+ kwargs["omni_present"]
+ if "omni_present" in kwargs
+ else kwargs["globals"] if "globals" in kwargs else {}
+ )
+ self._classifiers = (
+ kwargs["classifiers"] if "classifiers" in kwargs else {}
+ )
+ self._properties = (
+ kwargs["properties"] if "properties" in kwargs else {}
+ )
+ self._list = list(*args)
+
+ def __hash__(self):
+ ret = 0
+ for ev in self._list:
+ ret += hash(ev)
+ ret = ret % 479001599
+ return ret
+
+ def __eq__(self, other):
+ if len(self) != len(other):
+ return False
+ elif self.attributes != other.attributes:
+ return False
+ elif self.extensions != other.extensions:
+ return False
+ elif self.omni_present != other.omni_present:
+ return False
+ elif self.classifiers != other.classifiers:
+ return False
+ else:
+ for i in range(len(self._list)):
+ if self[i] != other[i]:
+ return False
+ return True
+
+ def __getitem__(self, key):
+ return self._list[key]
+
+ def __iter__(self):
+ return iter(self._list)
+
+ def __len__(self):
+ return len(self._list)
+
+ def __contains__(self, item):
+ return item in self._list
+
+ def __reversed__(self):
+ return reversed(self._list)
+
+ def __setitem__(self, key, value):
+ self._list[key] = value
+
+ def index(self, x, start: int = ..., end: int = ...):
+ return self._list.index(x, start, end)
+
+ def count(self, x):
+ return self._list.count(x)
+
+ def __str__(self):
+ return str(self._list)
+
+ def append(self, x):
+ self._list.append(x)
+
+ def _get_attributes(self):
+ return self._attributes
+
+ def _get_extensions(self):
+ return self._extensions
+
+ def _get_omni(self):
+ return self._omni
+
+ def _get_classifiers(self):
+ return self._classifiers
+
+ def _get_properties(self):
+ return self._properties
+
+ def _set_properties(self, properties):
+ self._properties = properties
+
+ def __copy__(self):
+ event_stream = EventStream()
+ event_stream._attributes = copy.copy(self._attributes)
+ event_stream._extensions = copy.copy(self._extensions)
+ event_stream._omni = copy.copy(self._omni)
+ event_stream._classifiers = copy.copy(self._classifiers)
+ event_stream._properties = copy.copy(self._properties)
+ for ev in self._list:
+ event_stream._list.append(ev)
+ return event_stream
+
+ def __deepcopy__(self, memodict={}):
+ event_stream = EventStream()
+ event_stream._attributes = copy.deepcopy(self._attributes)
+ event_stream._extensions = copy.deepcopy(self._extensions)
+ event_stream._omni = copy.deepcopy(self._omni)
+ event_stream._classifiers = copy.deepcopy(self._classifiers)
+ event_stream._properties = copy.deepcopy(self._properties)
+ for ev in self._list:
+ event_stream._list.append(copy.deepcopy(ev))
+ return event_stream
+
+ attributes = property(_get_attributes)
+ extensions = property(_get_extensions)
+ omni_present = property(_get_omni)
+ classifiers = property(_get_classifiers)
+ properties = property(_get_properties, _set_properties)
+
+
+class Trace(Sequence):
+
+ def __init__(self, *args, **kwargs):
+ self._set_attributes(
+ kwargs["attributes"] if "attributes" in kwargs else {}
+ )
+ self._properties = (
+ kwargs["properties"] if "properties" in kwargs else {}
+ )
+ self._list = list(*args)
+
+ def __hash__(self):
+ ret = 0
+ for ev in self._list:
+ ret += hash(ev)
+ ret = ret % 479001599
+ return ret
+
+ def __eq__(self, other):
+ if len(self) != len(other):
+ return False
+ elif self.attributes != other.attributes:
+ return False
+ else:
+ for i in range(len(self._list)):
+ if self[i] != other[i]:
+ return False
+ return True
+
+ def __getitem__(self, key):
+ return self._list[key]
+
+ def __iter__(self):
+ return iter(self._list)
+
+ def __len__(self):
+ return len(self._list)
+
+ def __contains__(self, item):
+ return item in self._list
+
+ def __reversed__(self):
+ return reversed(self._list)
+
+ def __setitem__(self, key, value):
+ self._list[key] = value
+
+ def index(self, x, start: int = ..., end: int = ...):
+ return self._list.index(x, start, end)
+
+ def count(self, x):
+ return self._list.count(x)
+
+ def insert(self, i, x):
+ self._list.insert(i, x)
+
+ def append(self, x):
+ self._list.append(x)
+
+ def _set_attributes(self, attributes):
+ self._attributes = attributes
+
+ def _get_attributes(self):
+ return self._attributes
+
+ def _get_properties(self):
+ return self._properties
+
+ def _set_properties(self, properties):
+ self._properties = properties
+
+ attributes = property(_get_attributes)
+ properties = property(_get_properties, _set_properties)
+
+ def __repr__(self, ret_list=False):
+ if len(self._list) == 0:
+ ret = {"attributes": self._attributes, "events": []}
+ elif len(self._list) == 1:
+ ret = {"attributes": self._attributes, "events": [self._list[0]]}
+ else:
+ ret = {
+ "attributes": self._attributes,
+ "events": [self._list[0], "..", self._list[-1]],
+ }
+ if ret_list:
+ return ret
+ return str(ret)
+
+ def __str__(self):
+ return str(self.__repr__())
+
+ def __copy__(self):
+ new_attributes = {}
+ for k, v in self.attributes.items():
+ new_attributes[k] = v
+ trace = Trace(attributes=new_attributes)
+ for ev in self._list:
+ trace.append(ev)
+ return trace
+
+ def __deepcopy__(self, memodict={}):
+ new_attributes = {}
+ for k, v in self.attributes.items():
+ if type(new_attributes) is dict:
+ new_attributes[k] = copy.deepcopy(v)
+ else:
+ new_attributes[k] = v
+ trace = Trace(attributes=new_attributes)
+ for ev in self._list:
+ trace.append(copy.deepcopy(ev))
+ return trace
+
+
+class EventLog(EventStream):
+ def __init__(self, *args, **kwargs):
+ super(EventLog, self).__init__(*args, **kwargs)
+
+ def __repr__(self):
+ if len(self._list) == 0:
+ ret = []
+ elif len(self._list) == 1:
+ ret = [self._list[0].__repr__(ret_list=True)]
+ else:
+ ret = [
+ self._list[0].__repr__(ret_list=True),
+ "....",
+ self._list[-1].__repr__(ret_list=True),
+ ]
+ return str(ret)
+
+ def __str__(self):
+ return str(self.__repr__())
+
+ def __copy__(self):
+ log = EventLog()
+ log._attributes = copy.copy(self._attributes)
+ log._extensions = copy.copy(self._extensions)
+ log._omni = copy.copy(self._omni)
+ log._classifiers = copy.copy(self._classifiers)
+ log._properties = copy.copy(self._properties)
+ for trace in self._list:
+ log._list.append(trace)
+ return log
+
+ def __deepcopy__(self, memodict={}):
+ log = EventLog()
+ log._attributes = copy.deepcopy(self._attributes)
+ log._extensions = copy.deepcopy(self._extensions)
+ log._omni = copy.deepcopy(self._omni)
+ log._classifiers = copy.deepcopy(self._classifiers)
+ log._properties = copy.deepcopy(self._properties)
+ for trace in self._list:
+ log._list.append(copy.deepcopy(trace))
+ return log
+
+ def __hash__(self):
+ ret = 0
+ for trace in self._list:
+ ret += hash(trace)
+ ret = ret % 479001599
+ return ret
+
+ def __eq__(self, other):
+ if len(self) != len(other):
+ return False
+ elif self.attributes != other.attributes:
+ return False
+ elif self.extensions != other.extensions:
+ return False
+ elif self.omni_present != other.omni_present:
+ return False
+ elif self.classifiers != other.classifiers:
+ return False
+ else:
+ for i in range(len(self._list)):
+ if self[i] != other[i]:
+ return False
+ return True
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d73b47fa2a6423a08b3c95ef5e2dd2b58e11409
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/__init__.py
@@ -0,0 +1,45 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.util import (
+ activities_to_alphabet,
+ artificial,
+ basic_filter,
+ dataframe_utils,
+ df_extra_utils,
+ df_features_utils,
+ filtering_utils,
+ get_class_representation,
+ get_log_encoded,
+ get_prefixes,
+ index_attribute,
+ insert_classifier,
+ interval_lifecycle,
+ log,
+ log_regex,
+ move_attrs_to_trace,
+ pandas_log_wrapper,
+ pandas_numpy_variants,
+ sampling,
+ sorting,
+ split_train_test,
+ xes,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/activities_to_alphabet.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/activities_to_alphabet.py
new file mode 100644
index 0000000000000000000000000000000000000000..55eb1b4c879b7150b76afa9227da57519dbac795
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/activities_to_alphabet.py
@@ -0,0 +1,88 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from enum import Enum
+from pm4py.util import exec_utils, xes_constants
+import pandas as pd
+from typing import Optional, Dict, Any, Union, Tuple
+
+
+class Parameters(Enum):
+ ACTIVITY_KEY = "activity_key"
+ RETURN_MAPPING = "return_mapping"
+
+
+def apply(
+ dataframe: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None
+) -> Union[pd.DataFrame, Tuple[pd.DataFrame, Dict[str, str]]]:
+ """
+ Remap the activities in a dataframe using an augmented alphabet to minimize the size of the encoding
+
+ Running example:
+
+ import pm4py
+ from pm4py.objects.log.util import activities_to_alphabet
+ from pm4py.util import constants
+
+ dataframe = pm4py.read_xes("tests/input_data/running-example.xes")
+ renamed_dataframe = activities_to_alphabet.apply(dataframe, parameters={constants.PARAMETER_CONSTANT_ACTIVITY_KEY: "concept:name"})
+ print(renamed_dataframe)
+
+ Parameters
+ --------------
+ dataframe
+ Pandas dataframe
+ parameters
+ Parameters of the method, including:
+ - Parameters.ACTIVITY_KEY => attribute to be used as activity
+ - Parameters.RETURN_MAPPING => (boolean) enables the returning the mapping dictionary (so the original activities can be re-constructed)
+
+ Returns
+ --------------
+ ren_dataframe
+ Pandas dataframe in which the activities have been remapped to the (augmented) alphabet
+ inv_mapping
+ (if required) Dictionary associating to every letter of the (augmented) alphabet the original activity
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ return_mapping = exec_utils.get_param_value(
+ Parameters.RETURN_MAPPING, parameters, False
+ )
+
+ activities_count = list(dataframe[activity_key].value_counts().to_dict())
+ remap_dict = {}
+ for index, act in enumerate(activities_count):
+ result = ""
+ while index >= 0:
+ result = chr((index % 26) + ord("A")) + result
+ index = index // 26 - 1
+ remap_dict[act] = result
+ dataframe[activity_key] = dataframe[activity_key].map(remap_dict)
+ if return_mapping:
+ inverse_dct = {y: x for x, y in remap_dict.items()}
+ return dataframe, inverse_dct
+ return dataframe
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/artificial.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/artificial.py
new file mode 100644
index 0000000000000000000000000000000000000000..329467e4b56a8b43a6ee0ba5ae81b0474eaa3ede
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/artificial.py
@@ -0,0 +1,99 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.log.obj import Event
+from pm4py.objects.log.obj import EventLog
+from pm4py.util import constants
+from pm4py.util import exec_utils
+from pm4py.util import xes_constants
+import datetime
+
+
+class Parameters(Enum):
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ PARAM_ARTIFICIAL_START_ACTIVITY = constants.PARAM_ARTIFICIAL_START_ACTIVITY
+ PARAM_ARTIFICIAL_END_ACTIVITY = constants.PARAM_ARTIFICIAL_END_ACTIVITY
+
+
+def insert_artificial_start_end(
+ log: EventLog, parameters: Optional[Dict[Any, Any]] = None
+) -> EventLog:
+ """
+ Inserts the artificial start/end activities in an event log.
+
+ Parameters
+ ----------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm, including:
+
+ - Parameters.ACTIVITY_KEY: the activity
+ - Parameters.TIMESTAMP_KEY: the timestamp
+
+ Returns
+ -------
+ log
+ Enriched log
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+
+ artificial_start_activity = exec_utils.get_param_value(
+ Parameters.PARAM_ARTIFICIAL_START_ACTIVITY,
+ parameters,
+ constants.DEFAULT_ARTIFICIAL_START_ACTIVITY,
+ )
+ artificial_end_activity = exec_utils.get_param_value(
+ Parameters.PARAM_ARTIFICIAL_END_ACTIVITY,
+ parameters,
+ constants.DEFAULT_ARTIFICIAL_END_ACTIVITY,
+ )
+
+ for trace in log:
+ start_event = Event({activity_key: artificial_start_activity})
+ end_event = Event({activity_key: artificial_end_activity})
+ if trace:
+ if timestamp_key in trace[0]:
+ start_event[timestamp_key] = trace[0][
+ timestamp_key
+ ] - datetime.timedelta(seconds=1)
+ if timestamp_key in trace[-1]:
+ end_event[timestamp_key] = trace[-1][
+ timestamp_key
+ ] + datetime.timedelta(seconds=1)
+ trace.insert(0, start_event)
+ trace.append(end_event)
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/basic_filter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/basic_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..29aecb71c4c0a2388a8b538ff201b7fa8afdfbc9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/basic_filter.py
@@ -0,0 +1,142 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util.constants import PARAMETER_CONSTANT_ATTRIBUTE_KEY
+from pm4py.util.xes_constants import DEFAULT_NAME_KEY
+from pm4py.objects.log.obj import EventLog, Trace, EventStream
+from pm4py.objects.conversion.log import converter as log_converter
+from enum import Enum
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ ATTRIBUTE_KEY = PARAMETER_CONSTANT_ATTRIBUTE_KEY
+ POSITIVE = "positive"
+
+
+def filter_log_events_attr(log, values, parameters=None):
+ """
+ Filter log by keeping only events with an attribute value that belongs to the provided values list
+
+ Parameters
+ -----------
+ log
+ log
+ values
+ Allowed attributes
+ parameters
+ Parameters of the algorithm, including:
+ activity_key -> Attribute identifying the activity in the log
+ positive -> Indicate if events should be kept/removed
+
+ Returns
+ -----------
+ filtered_log
+ Filtered log
+ """
+
+ # CODE SAVING FROM FILTERS
+
+ if parameters is None:
+ parameters = {}
+
+ attribute_key = exec_utils.get_param_value(
+ Parameters.ATTRIBUTE_KEY, parameters, DEFAULT_NAME_KEY
+ )
+ positive = exec_utils.get_param_value(
+ Parameters.POSITIVE, parameters, True
+ )
+
+ stream = log_converter.apply(
+ log,
+ variant=log_converter.TO_EVENT_STREAM,
+ parameters={"deepcopy": False},
+ )
+ if positive:
+ stream = EventStream(
+ list(filter(lambda x: x[attribute_key] in values, stream))
+ )
+ else:
+ stream = EventStream(
+ list(filter(lambda x: x[attribute_key] not in values, stream))
+ )
+
+ filtered_log = log_converter.apply(
+ stream, variant=log_converter.Variants.TO_EVENT_LOG
+ )
+
+ return filtered_log
+
+
+def filter_log_traces_attr(log, values, parameters=None):
+ """
+ Filter log by keeping only traces that has/has not events with an attribute value that belongs to the provided
+ values list
+
+ Parameters
+ -----------
+ log
+ Trace log
+ values
+ Allowed attributes
+ parameters
+ Parameters of the algorithm, including:
+ activity_key -> Attribute identifying the activity in the log
+ positive -> Indicate if events should be kept/removed
+
+ Returns
+ -----------
+ filtered_log
+ Filtered log
+ """
+
+ # CODE SAVING FROM FILTERS
+
+ if parameters is None:
+ parameters = {}
+
+ attribute_key = exec_utils.get_param_value(
+ Parameters.ATTRIBUTE_KEY, parameters, DEFAULT_NAME_KEY
+ )
+ positive = exec_utils.get_param_value(
+ Parameters.POSITIVE, parameters, True
+ )
+
+ filtered_log = EventLog()
+ for trace in log:
+ new_trace = Trace()
+
+ found = False
+ for j in range(len(trace)):
+ if attribute_key in trace[j]:
+ attribute_value = trace[j][attribute_key]
+ if attribute_value in values:
+ found = True
+
+ if (found and positive) or (not found and not positive):
+ new_trace = trace
+ else:
+ for attr in trace.attributes:
+ new_trace.attributes[attr] = trace.attributes[attr]
+
+ if len(new_trace) > 0:
+ filtered_log.append(new_trace)
+ return filtered_log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/dataframe_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/dataframe_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e225373a8eb014e1485c599942124e1b7b71483
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/dataframe_utils.py
@@ -0,0 +1,437 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+
+from pm4py.objects.conversion.log import converter as log_converter
+from pm4py.objects.log.obj import EventStream
+from pm4py.util import constants
+from pm4py.util import exec_utils
+from pm4py.util import points_subset
+from pm4py.util import xes_constants, pandas_utils
+from pm4py.util.dt_parsing.variants import strpfromiso
+import random
+import traceback
+
+
+LEGACY_PARQUET_TP_REPLACER = "AAA"
+LEGACY_PARQUET_CASECONCEPTNAME = "caseAAAconceptAAAname"
+
+
+class Parameters(Enum):
+ PARTITION_COLUMN = "partition_column"
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ CASE_PREFIX = constants.CASE_ATTRIBUTE_PREFIX
+ CASE_ATTRIBUTES = "case_attributes"
+ CONSIDER_ALL_ATTRIBUTES = "consider_all_attributes"
+ MANDATORY_ATTRIBUTES = "mandatory_attributes"
+ MAX_NO_CASES = "max_no_cases"
+ MIN_DIFFERENT_OCC_STR_ATTR = "min_different_occ_str_attr"
+ MAX_DIFFERENT_OCC_STR_ATTR = "max_different_occ_str_attr"
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ PARAM_ARTIFICIAL_START_ACTIVITY = constants.PARAM_ARTIFICIAL_START_ACTIVITY
+ PARAM_ARTIFICIAL_END_ACTIVITY = constants.PARAM_ARTIFICIAL_END_ACTIVITY
+ INDEX_KEY = "index_key"
+ CASE_INDEX_KEY = "case_index_key"
+ USE_EXTREMES_TIMESTAMP = "use_extremes_timestamp"
+ ADD_CASE_IDENTIFIER_COLUMN = "add_case_identifier_column"
+ DETERMINISTIC = "deterministic"
+ COUNT_OCCURRENCES = "count_occurrences"
+ ENABLE_NUMERIC_ATTRIBUTE_STATISTICS = "enable_numeric_attribute_statistics"
+ NUMERIC_ATTRIBUTE_AGGREGATIONS = "numeric_attribute_aggregations"
+
+
+from pm4py.objects.log.util.df_features_utils import * # noqa: F401,F403
+
+
+def insert_partitioning(df, num_partitions, parameters=None):
+ """
+ Insert the partitioning in the specified dataframe
+
+ Parameters
+ -------------
+ df
+ Dataframe
+ num_partitions
+ Number of partitions
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ df
+ Partitioned dataframe
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_index_key = exec_utils.get_param_value(
+ Parameters.CASE_INDEX_KEY, parameters, constants.DEFAULT_CASE_INDEX_KEY
+ )
+ partition_column = exec_utils.get_param_value(
+ Parameters.PARTITION_COLUMN, parameters, "@@partitioning"
+ )
+
+ if case_index_key not in df.columns:
+ from pm4py.util import pandas_utils
+
+ df = pandas_utils.insert_case_index(df, case_index_key)
+
+ df[partition_column] = df[case_index_key] % num_partitions
+
+ return df
+
+
+def legacy_parquet_support(df, parameters=None):
+ """
+ For legacy support, Parquet files columns could not contain
+ a ":" that has been arbitrarily replaced by a replacer string.
+ This string substitutes the replacer to the :
+
+ Parameters
+ ---------------
+ dataframe
+ Dataframe
+ parameters
+ Parameters of the algorithm
+ """
+ if parameters is None:
+ parameters = {}
+
+ df.columns = [
+ x.replace(LEGACY_PARQUET_TP_REPLACER, ":") for x in df.columns
+ ]
+
+ return df
+
+
+def table_to_stream(table, parameters=None):
+ """
+ Converts a Pyarrow table to an event stream
+
+ Parameters
+ ------------
+ table
+ Pyarrow table
+ parameters
+ Possible parameters of the algorithm
+ """
+ if parameters is None:
+ parameters = {}
+
+ dict0 = table.to_pydict()
+ keys = list(dict0.keys())
+ # for legacy format support
+ if LEGACY_PARQUET_CASECONCEPTNAME in keys:
+ for key in keys:
+ dict0[key.replace(LEGACY_PARQUET_TP_REPLACER, ":")] = dict0.pop(
+ key
+ )
+
+ stream = EventStream([dict(zip(dict0, i)) for i in zip(*dict0.values())])
+
+ return stream
+
+
+def table_to_log(table, parameters=None):
+ """
+ Converts a Pyarrow table to an event log
+
+ Parameters
+ ------------
+ table
+ Pyarrow table
+ parameters
+ Possible parameters of the algorithm
+ """
+ if parameters is None:
+ parameters = {}
+
+ stream = table_to_stream(table, parameters=parameters)
+
+ return log_converter.apply(stream, parameters=parameters)
+
+
+def convert_timestamp_columns_in_df(
+ df, timest_format=None, timest_columns=None
+):
+ """
+ Convert all dataframe columns in a dataframe
+
+ Parameters
+ -----------
+ df
+ Dataframe
+ timest_format
+ (If provided) Format of the timestamp columns in the CSV file
+ timest_columns
+ Columns of the CSV that shall be converted into timestamp
+
+ Returns
+ ------------
+ df
+ Dataframe with timestamp columns converted
+
+ """
+ if df is None:
+ return df
+
+ df = df.copy()
+
+ if timest_format is None:
+ timest_format = constants.DEFAULT_TIMESTAMP_PARSE_FORMAT
+
+ if timest_format is None:
+ timest_format = "mixed"
+
+ for col in df.columns:
+ if timest_columns is None or col in timest_columns:
+ if "obj" in str(df[col].dtype) or "str" in str(df[col].dtype):
+ try:
+ df[col] = pandas_utils.dataframe_column_string_to_datetime(
+ df[col], format=timest_format, utc=True
+ )
+ except BaseException:
+ try:
+ df[col] = (
+ pandas_utils.dataframe_column_string_to_datetime(
+ df[col],
+ format=timest_format,
+ exact=False,
+ utc=True,
+ )
+ )
+ except BaseException:
+ try:
+ df[col] = (
+ pandas_utils.dataframe_column_string_to_datetime(
+ df[col], format=timest_format))
+ except BaseException:
+ pass
+
+ for col in df.columns:
+ if "date" in str(df[col].dtype) or "time" in str(df[col].dtype):
+ df[col] = strpfromiso.fix_dataframe_column(df[col])
+
+ return df
+
+
+def sample_dataframe(df, parameters=None):
+ """
+ Sample a dataframe on a given number of cases
+
+ Parameters
+ --------------
+ df
+ Dataframe
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.CASE_ID_KEY
+ - Parameters.CASE_ID_TO_RETAIN
+
+ Returns
+ -------------
+ sampled_df
+ Sampled dataframe
+ """
+ if parameters is None:
+ parameters = {}
+
+ deterministic = exec_utils.get_param_value(
+ Parameters.DETERMINISTIC, parameters, False
+ )
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ max_no_cases = exec_utils.get_param_value(
+ Parameters.MAX_NO_CASES, parameters, 100
+ )
+
+ case_ids = pandas_utils.format_unique(df[case_id_key].unique())
+ case_ids = list(case_ids)
+
+ if not deterministic:
+ random.shuffle(case_ids)
+
+ case_id_to_retain = points_subset.pick_chosen_points_list(
+ min(max_no_cases, len(case_ids)), case_ids
+ )
+
+ return df[df[case_id_key].isin(case_id_to_retain)]
+
+
+def insert_artificial_start_end(
+ df0: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None
+) -> pd.DataFrame:
+ """
+ Inserts the artificial start/end activities in a Pandas dataframe
+
+ Parameters
+ ------------------
+ df0
+ Dataframe
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.CASE_ID_KEY: the case identifier
+ - Parameters.TIMESTAMP_KEY: the timestamp
+ - Parameters.ACTIVITY_KEY: the activity
+
+ Returns
+ -----------------
+ enriched_df
+ Dataframe with artificial start/end activities
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ use_extremes_timestamp = exec_utils.get_param_value(
+ Parameters.USE_EXTREMES_TIMESTAMP, parameters, False
+ )
+
+ artificial_start_activity = exec_utils.get_param_value(
+ Parameters.PARAM_ARTIFICIAL_START_ACTIVITY,
+ parameters,
+ constants.DEFAULT_ARTIFICIAL_START_ACTIVITY,
+ )
+ artificial_end_activity = exec_utils.get_param_value(
+ Parameters.PARAM_ARTIFICIAL_END_ACTIVITY,
+ parameters,
+ constants.DEFAULT_ARTIFICIAL_END_ACTIVITY,
+ )
+
+ index_key = exec_utils.get_param_value(
+ Parameters.INDEX_KEY, parameters, constants.DEFAULT_INDEX_KEY
+ )
+
+ df = df0.copy()
+ df = pandas_utils.insert_index(df, index_key)
+ df = df.sort_values([case_id_key, timestamp_key, index_key])
+
+ start_df = (
+ df[[case_id_key, timestamp_key]]
+ .groupby(case_id_key)
+ .first()
+ .reset_index()
+ )
+ end_df = (
+ df[[case_id_key, timestamp_key]]
+ .groupby(case_id_key)
+ .last()
+ .reset_index()
+ )
+ # stability trick: remove 1ms from the artificial start activity
+ # timestamp, add 1ms to the artificial end activity timestamp
+ if use_extremes_timestamp:
+ start_df[timestamp_key] = pd.Timestamp.min
+ end_df[timestamp_key] = pd.Timestamp.max
+ start_df[timestamp_key] = start_df[timestamp_key].dt.tz_localize("utc")
+ end_df[timestamp_key] = end_df[timestamp_key].dt.tz_localize("utc")
+ else:
+ start_df[timestamp_key] = start_df[timestamp_key] - pd.Timedelta(
+ "1 ms"
+ )
+ end_df[timestamp_key] = end_df[timestamp_key] + pd.Timedelta("1 ms")
+
+ start_df[activity_key] = artificial_start_activity
+ end_df[activity_key] = artificial_end_activity
+
+ df = pandas_utils.concat([start_df, df, end_df])
+ df = pandas_utils.insert_index(df, index_key)
+ df = df.sort_values([case_id_key, timestamp_key, index_key])
+
+ df.attrs = df0.attrs
+
+ return df
+
+
+def dataframe_to_activity_case_table(
+ df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None
+):
+ """
+ Transforms a Pandas dataframe into:
+ - an "activity" table, containing the events and their attributes
+ - a "case" table, containing the cases and their attributes
+
+ Parameters
+ ----------
+ df
+ Dataframe
+ parameters
+ Parameters of the algorithm that should be used, including:
+
+ - Parameters.CASE_ID_KEY => the column to be used as case ID (shall be included both in the activity table and the case table)
+ - Parameters.CASE_PREFIX => if a list of attributes at the case level is not provided, then all the ones of the dataframe starting with one of these are considered.
+ - Parameters.CASE_ATTRIBUTES => the attributes of the dataframe to be used as case columns
+
+ Returns
+ ---------------
+ activity_table
+ Activity table
+ case_table
+ Case table
+
+ """
+ if parameters is None:
+ parameters = {}
+
+ # make sure we start from a dataframe object
+ df = log_converter.apply(
+ df, variant=log_converter.Variants.TO_DATA_FRAME, parameters=parameters
+ )
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ case_id_prefix = exec_utils.get_param_value(
+ Parameters.CASE_PREFIX, parameters, constants.CASE_ATTRIBUTE_PREFIX
+ )
+
+ case_attributes = exec_utils.get_param_value(
+ Parameters.CASE_ATTRIBUTES,
+ parameters,
+ set([x for x in df.columns if x.startswith(case_id_prefix)]),
+ )
+ event_attributes = set([x for x in df.columns if x not in case_attributes])
+
+ activity_table = df[event_attributes.union({case_id_key})]
+ case_table = (
+ df[case_attributes.union({case_id_key})]
+ .groupby(case_id_key)
+ .first()
+ .reset_index()
+ )
+
+ return activity_table, case_table
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/df_extra_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/df_extra_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..26251ec73cd3ab5850819d63b99e58a88fc87869
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/df_extra_utils.py
@@ -0,0 +1,99 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any
+from enum import Enum
+from pm4py.util import constants, xes_constants, exec_utils
+import pandas as pd
+
+
+class Parameters(Enum):
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ COMPUTE_EXTRA_TEMPORAL_FEATURES = "compute_extra_temporal_features"
+
+
+def compute_extra_columns(dataframe: pd.DataFrame, parameters: Optional[Dict[Any, Any]]=None):
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME)
+ start_timestamp_key = exec_utils.get_param_value(Parameters.START_TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY)
+ timestamp_key = exec_utils.get_param_value(Parameters.TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY)
+ compute_extra_temporal_features = exec_utils.get_param_value(Parameters.COMPUTE_EXTRA_TEMPORAL_FEATURES, parameters, True)
+
+ # Drop previously computed helper columns so re-running the enrichment doesn't duplicate them
+ columns_to_drop = ["@@count", "@@case_throughput"]
+ if compute_extra_temporal_features:
+ columns_to_drop.extend([
+ "@@case_start_year",
+ "@@case_start_ymonth",
+ "@@case_start_month",
+ "@@case_start_week",
+ "@@case_end_year",
+ "@@case_end_ymonth",
+ "@@case_end_month",
+ "@@case_end_week",
+ ])
+ dataframe.drop(columns=columns_to_drop, inplace=True, errors="ignore")
+
+ dataframe["@@count"] = 1
+
+ # Calculate first and last timestamps for each case
+ case_first_timestamp = dataframe.groupby(case_id_key)[start_timestamp_key].first()
+ case_last_timestamp = dataframe.groupby(case_id_key)[timestamp_key].last()
+
+ # Calculate case throughput using the already computed timestamps
+ case_throughput = (case_last_timestamp - case_first_timestamp).dt.total_seconds()
+
+ # Map the throughput back to the dataframe
+ dataframe["@@case_throughput"] = dataframe[case_id_key].map(case_throughput)
+
+ # Only compute extra temporal features if the parameter is True
+ if compute_extra_temporal_features:
+ # Compute all start temporal attributes at once on the Series level
+ start_years = case_first_timestamp.dt.year.astype(str)
+ start_months = case_first_timestamp.dt.month
+ start_ymonths = start_years + '-' + start_months.astype(str).str.zfill(2)
+ start_month_labels = 'M' + start_months.astype(str).str.zfill(2)
+ start_weeks = 'W' + case_first_timestamp.apply(lambda x: str(x.isocalendar()[1]).zfill(2))
+
+ # Compute all end temporal attributes at once on the Series level
+ end_years = case_last_timestamp.dt.year.astype(str)
+ end_months = case_last_timestamp.dt.month
+ end_ymonths = end_years + '-' + end_months.astype(str).str.zfill(2)
+ end_month_labels = 'M' + end_months.astype(str).str.zfill(2)
+ end_weeks = 'W' + case_last_timestamp.apply(lambda x: str(x.isocalendar()[1]).zfill(2))
+
+ # Map all computed values back to the dataframe in one go for each attribute
+ case_col = dataframe[case_id_key]
+ dataframe["@@case_start_year"] = case_col.map(start_years)
+ dataframe["@@case_start_ymonth"] = case_col.map(start_ymonths)
+ dataframe["@@case_start_month"] = case_col.map(start_month_labels)
+ dataframe["@@case_start_week"] = case_col.map(start_weeks)
+
+ dataframe["@@case_end_year"] = case_col.map(end_years)
+ dataframe["@@case_end_ymonth"] = case_col.map(end_ymonths)
+ dataframe["@@case_end_month"] = case_col.map(end_month_labels)
+ dataframe["@@case_end_week"] = case_col.map(end_weeks)
+
+ return dataframe
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/df_features_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/df_features_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..df57ad88cb3f416549dd99918cc6824425579996
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/df_features_utils.py
@@ -0,0 +1,597 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any, List, Set, Collection
+
+import numpy as np
+import pandas as pd
+
+from pm4py.objects.log.util.dataframe_utils import Parameters
+from pm4py.util import constants, exec_utils, pandas_utils
+from pm4py.util import xes_constants
+
+
+def _sanitize_feature_name(
+ prefix: str, value: Any, used_names: Optional[Set[str]] = None
+) -> str:
+ """
+ Build a deterministic feature column name and ensure uniqueness when requested.
+ """
+ sanitized = (
+ str(value)
+ .encode("ascii", errors="ignore")
+ .decode("ascii")
+ )
+ if sanitized == "":
+ sanitized = "value"
+ base_name = f"{prefix}_{sanitized}"
+
+ if used_names is None:
+ return base_name
+
+ candidate = base_name
+ suffix = 1
+ while candidate in used_names:
+ candidate = f"{base_name}__{suffix}"
+ suffix += 1
+ used_names.add(candidate)
+ return candidate
+
+
+_DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS = (
+ "last",
+ "first",
+ "min",
+ "max",
+ "mean",
+ "median",
+ "stdev",
+ "sum",
+)
+
+_NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES = {
+ "last": "LAST",
+ "first": "FIRST",
+ "min": "MIN",
+ "max": "MAX",
+ "mean": "MEAN",
+ "median": "MEDIAN",
+ "stdev": "STDEV",
+ "sum": "SUM",
+}
+
+_NUMERIC_ATTRIBUTE_AGGREGATION_ALIASES = {
+ "std": "stdev",
+ "standard_deviation": "stdev",
+}
+
+
+def _is_internal_attribute(column: str) -> bool:
+ return str(column).startswith("@@")
+
+
+def _normalize_numeric_attribute_aggregations(
+ aggregations: Optional[Collection[str]],
+) -> List[str]:
+ if aggregations is None:
+ values = list(_DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS)
+ elif isinstance(aggregations, str):
+ values = [aggregations]
+ else:
+ values = list(aggregations)
+
+ normalized = []
+ seen = set()
+ for value in values:
+ aggregation = str(value).lower()
+ aggregation = _NUMERIC_ATTRIBUTE_AGGREGATION_ALIASES.get(
+ aggregation, aggregation
+ )
+ if aggregation not in _NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES:
+ supported = ", ".join(_DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS)
+ raise ValueError(
+ f"Unsupported numeric attribute aggregation: {value}. "
+ f"Supported values are: {supported}."
+ )
+ if aggregation not in seen:
+ normalized.append(aggregation)
+ seen.add(aggregation)
+
+ if isinstance(aggregations, (set, frozenset)):
+ normalized_set = set(normalized)
+ normalized = [
+ aggregation
+ for aggregation in _DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS
+ if aggregation in normalized_set
+ ]
+
+ return normalized
+
+
+def _get_numeric_features_df(
+ df: pd.DataFrame,
+ numeric_columns: List[str],
+ case_id_key: str,
+ enable_numeric_attribute_statistics: bool,
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
+) -> pd.DataFrame:
+ if (
+ not enable_numeric_attribute_statistics
+ and numeric_attribute_aggregations is None
+ ):
+ return (
+ df[[case_id_key] + numeric_columns]
+ .copy()
+ .groupby(case_id_key)
+ .last()
+ .reset_index()
+ )
+
+ numeric_attribute_aggregations = _normalize_numeric_attribute_aggregations(
+ numeric_attribute_aggregations
+ )
+ non_internal_columns = [
+ col for col in numeric_columns if not _is_internal_attribute(col)
+ ]
+ internal_columns = [
+ col for col in numeric_columns if _is_internal_attribute(col)
+ ]
+ if not numeric_attribute_aggregations and not internal_columns:
+ return df[[case_id_key]].drop_duplicates().reset_index(drop=True)
+
+ aggregations = {}
+ for col in numeric_columns:
+ if _is_internal_attribute(col):
+ aggregations[col] = pd.NamedAgg(column=col, aggfunc="last")
+ continue
+
+ aggregation_functions = {
+ "last": "last",
+ "first": "first",
+ "min": "min",
+ "max": "max",
+ "mean": "mean",
+ "median": "median",
+ "stdev": lambda values: values.std(ddof=0),
+ "sum": lambda values: values.sum(min_count=1),
+ }
+ for aggregation in numeric_attribute_aggregations:
+ suffix = _NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES[aggregation]
+ aggregations[f"{col}_{suffix}"] = pd.NamedAgg(
+ column=col, aggfunc=aggregation_functions[aggregation]
+ )
+
+ return (
+ df[[case_id_key] + internal_columns + non_internal_columns]
+ .copy()
+ .groupby(case_id_key)
+ .agg(**aggregations)
+ .reset_index()
+ )
+
+
+def _get_numeric_feature_columns(
+ numeric_columns: List[str],
+ enable_numeric_attribute_statistics: bool,
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
+) -> List[str]:
+ if (
+ not enable_numeric_attribute_statistics
+ and numeric_attribute_aggregations is None
+ ):
+ return numeric_columns
+ numeric_attribute_aggregations = _normalize_numeric_attribute_aggregations(
+ numeric_attribute_aggregations
+ )
+ feature_columns = []
+ for col in numeric_columns:
+ if _is_internal_attribute(col):
+ feature_columns.append(col)
+ else:
+ feature_columns.extend(
+ f"{col}_{_NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES[aggregation]}"
+ for aggregation in numeric_attribute_aggregations
+ )
+ return feature_columns
+
+
+def automatic_feature_selection_df(df, parameters=None):
+ """
+ Performs an automatic feature selection on dataframes,
+ keeping the features useful for ML purposes
+
+ Parameters
+ ---------------
+ df
+ Dataframe
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ---------------
+ featured_df
+ Dataframe with only the features that have been selected
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+
+ mandatory_attributes = exec_utils.get_param_value(
+ Parameters.MANDATORY_ATTRIBUTES,
+ parameters,
+ set(df.columns).intersection(
+ {case_id_key, activity_key, timestamp_key}
+ ),
+ )
+
+ min_different_occ_str_attr = exec_utils.get_param_value(
+ Parameters.MIN_DIFFERENT_OCC_STR_ATTR, parameters, 5
+ )
+ max_different_occ_str_attr = exec_utils.get_param_value(
+ Parameters.MAX_DIFFERENT_OCC_STR_ATTR, parameters, 50
+ )
+ consider_all_attributes = exec_utils.get_param_value(
+ Parameters.CONSIDER_ALL_ATTRIBUTES, parameters, True
+ )
+
+ cols_dtypes = {x: str(df[x].dtype) for x in df.columns}
+ other_attributes_to_retain = set()
+
+ no_all_cases = df[case_id_key].nunique()
+ for x, y in cols_dtypes.items():
+ attr_df = df.dropna(subset=[x])
+ this_cases = attr_df[case_id_key].nunique()
+ attr_in_all_cases = this_cases == no_all_cases
+
+ # in any case, keep attributes that appears at least once per case
+ if attr_in_all_cases or consider_all_attributes:
+ if "float" in y or "int" in y:
+ # (as in the classic log version) retain always float/int attributes
+ other_attributes_to_retain.add(x)
+ elif "obj" in y or "str" in y:
+ # (as in the classic log version) keep string attributes if they have enough variability, but not too much
+ # (that would be hard to explain)
+ unique_val_count = df[x].nunique()
+ if (
+ min_different_occ_str_attr
+ <= unique_val_count
+ <= max_different_occ_str_attr
+ ):
+ other_attributes_to_retain.add(x)
+ else:
+ # not consider the attribute after this feature selection if it
+ # has other types (for example, date)
+ pass
+
+ attributes_to_retain = mandatory_attributes.union(
+ other_attributes_to_retain
+ )
+
+ return df[list(attributes_to_retain)]
+
+
+def select_number_column(
+ df: pd.DataFrame,
+ fea_df: pd.DataFrame,
+ col: str,
+ case_id_key=constants.CASE_CONCEPT_NAME,
+ enable_numeric_attribute_statistics=False,
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
+) -> pd.DataFrame:
+ """
+ Extract a column for the features dataframe for the given numeric attribute
+
+ Parameters
+ --------------
+ df
+ Dataframe
+ fea_df
+ Feature dataframe
+ col
+ Numeric column
+ case_id_key
+ Case ID key
+ enable_numeric_attribute_statistics
+ If True, extract numeric aggregation columns.
+ numeric_attribute_aggregations
+ Aggregations to compute for numeric attributes. Supported values are
+ last, first, min, max, mean, median, stdev, and sum. Applied only to
+ attributes whose names do not start with @@.
+
+ Returns
+ --------------
+ fea_df
+ Feature dataframe (desidered output)
+ """
+ numeric_columns = [col]
+ df_numeric = _get_numeric_features_df(
+ df,
+ numeric_columns,
+ case_id_key,
+ enable_numeric_attribute_statistics,
+ numeric_attribute_aggregations,
+ )
+ numeric_feature_columns = _get_numeric_feature_columns(
+ numeric_columns,
+ enable_numeric_attribute_statistics,
+ numeric_attribute_aggregations,
+ )
+ fea_df = fea_df.merge(
+ df_numeric, on=[case_id_key], how="left", suffixes=("", "_y")
+ )
+ if numeric_feature_columns:
+ fea_df[numeric_feature_columns] = fea_df[
+ numeric_feature_columns
+ ].astype(np.float32)
+ return fea_df
+
+
+def select_string_column(
+ df: pd.DataFrame,
+ fea_df: pd.DataFrame,
+ col: str,
+ case_id_key=constants.CASE_CONCEPT_NAME,
+ count_occurrences=False,
+) -> pd.DataFrame:
+ """
+ Extract N columns (for N different attribute values; hotencoding) for the features dataframe for the given string attribute
+
+ Parameters
+ --------------
+ df
+ Dataframe
+ fea_df
+ Feature dataframe
+ col
+ String column
+ case_id_key
+ Case ID key
+ count_occurrences
+ If True, count the number of occurrences of the attribute value in each case.
+ If False (default), use binary encoding (1 if present, 0 if not present)
+
+ Returns
+ --------------
+ fea_df
+ Feature dataframe (desidered output)
+ """
+ # Filter out None values once
+ df_filtered = df[[case_id_key, col]].dropna(subset=[col])
+ existing_cols = set(fea_df.columns)
+
+ if count_occurrences:
+ # Use crosstab for efficient counting
+ crosstab = pd.crosstab(df_filtered[case_id_key], df_filtered[col])
+ # Rename columns efficiently while avoiding duplicates
+ rename_map = {
+ original: _sanitize_feature_name(col, original, existing_cols)
+ for original in crosstab.columns
+ }
+ crosstab = crosstab.rename(columns=rename_map)
+ # Merge once with all columns
+ fea_df = fea_df.merge(
+ crosstab, left_on=case_id_key, right_index=True, how="left"
+ )
+ # Fill NaN and convert to float32 for all new columns at once
+ new_cols = list(rename_map.values())
+ if new_cols:
+ fea_df[new_cols] = fea_df[new_cols].astype(np.float32)
+ else:
+ # Use pivot_table for binary encoding - much faster than loop
+ # Create a dummy column for aggregation
+ df_filtered = df_filtered.copy()
+ df_filtered["_dummy"] = 1
+ cases_with_values = df_filtered[case_id_key].unique()
+
+ # Get unique values
+ unique_vals = pandas_utils.format_unique(df_filtered[col].unique())
+ unique_vals = [v for v in unique_vals if v is not None]
+
+ if len(unique_vals) > 0:
+ # Create pivot table
+ pivot = df_filtered.pivot_table(
+ index=case_id_key,
+ columns=col,
+ values="_dummy",
+ aggfunc="max",
+ )
+
+ # Rename columns (ensuring uniqueness when sanitization collides)
+ rename_map = {
+ original: _sanitize_feature_name(col, original, existing_cols)
+ for original in pivot.columns
+ }
+ pivot = pivot.rename(columns=rename_map)
+
+ # Merge once with all columns
+ fea_df = fea_df.merge(
+ pivot, left_on=case_id_key, right_index=True, how="left"
+ )
+ # Fill NaN only for cases having at least one value and convert to float32
+ new_cols = list(rename_map.values())
+ if new_cols:
+ mask = (
+ fea_df[case_id_key].isin(cases_with_values)
+ if case_id_key in fea_df.columns
+ else None
+ )
+ for col_name in new_cols:
+ if col_name in fea_df.columns:
+ if mask is not None:
+ fea_df.loc[mask, col_name] = (
+ fea_df.loc[mask, col_name].fillna(0)
+ )
+ fea_df[col_name] = fea_df[col_name].astype(np.float32)
+
+ return fea_df
+
+
+def get_features_df(
+ df: pd.DataFrame,
+ list_columns: List[str],
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> pd.DataFrame:
+ """
+ Given a dataframe and a list of columns, performs an automatic feature extraction
+
+ Parameters
+ ---------------
+ df
+ Dataframe
+ list_column
+ List of column to consider in the feature extraction
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.CASE_ID_KEY: the case ID
+ - Parameters.COUNT_OCCURRENCES: if True, count occurrences of string attributes instead of binary encoding
+ - Parameters.ENABLE_NUMERIC_ATTRIBUTE_STATISTICS: if True, extract aggregation statistics for numeric attributes
+ - Parameters.NUMERIC_ATTRIBUTE_AGGREGATIONS: collection of aggregations to compute for numeric attributes
+ whose names do not start with @@
+
+ Returns
+ ---------------
+ fea_df
+ Feature dataframe (desidered output)
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ add_case_identifier_column = exec_utils.get_param_value(
+ Parameters.ADD_CASE_IDENTIFIER_COLUMN, parameters, False
+ )
+ count_occurrences = exec_utils.get_param_value(
+ Parameters.COUNT_OCCURRENCES, parameters, False
+ )
+ enable_numeric_attribute_statistics = exec_utils.get_param_value(
+ Parameters.ENABLE_NUMERIC_ATTRIBUTE_STATISTICS, parameters, False
+ )
+ numeric_attribute_aggregations = exec_utils.get_param_value(
+ Parameters.NUMERIC_ATTRIBUTE_AGGREGATIONS, parameters, None
+ )
+
+ # Start with unique case IDs
+ unique_cases = sorted(pandas_utils.format_unique(df[case_id_key].unique()))
+ fea_df = pandas_utils.instantiate_dataframe({case_id_key: unique_cases})
+
+ # Separate columns by type for batch processing
+ string_columns = []
+ numeric_columns = []
+
+ for col in list_columns:
+ dtype_str = str(df[col].dtype)
+ if "obj" in dtype_str or "str" in dtype_str:
+ string_columns.append(col)
+ elif "float" in dtype_str or "int" in dtype_str:
+ numeric_columns.append(col)
+
+ # Process numeric columns (can be done more efficiently in batch)
+ if numeric_columns:
+ df_numeric = _get_numeric_features_df(
+ df,
+ numeric_columns,
+ case_id_key,
+ enable_numeric_attribute_statistics,
+ numeric_attribute_aggregations,
+ )
+ numeric_feature_columns = _get_numeric_feature_columns(
+ numeric_columns,
+ enable_numeric_attribute_statistics,
+ numeric_attribute_aggregations,
+ )
+ # Merge once for all numeric columns
+ fea_df = fea_df.merge(df_numeric, on=case_id_key, how="left")
+ # Convert all numeric columns to float32 at once
+ if numeric_feature_columns:
+ fea_df[numeric_feature_columns] = fea_df[
+ numeric_feature_columns
+ ].astype(np.float32)
+
+ # Process string columns one by one (still needed due to hot encoding)
+ for col in string_columns:
+ fea_df = select_string_column(
+ df, fea_df, col, case_id_key=case_id_key, count_occurrences=count_occurrences
+ )
+
+ # Sort and optionally remove case ID
+ fea_df = fea_df.sort_values(case_id_key)
+ if not add_case_identifier_column:
+ del fea_df[case_id_key]
+
+ return fea_df
+
+
+def automatic_feature_extraction_df(
+ df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None
+) -> pd.DataFrame:
+ """
+ Performs an automatic feature extraction given a dataframe
+
+ Parameters
+ --------------
+ df
+ Dataframe
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.CASE_ID_KEY: the case ID
+ - Parameters.MIN_DIFFERENT_OCC_STR_ATTR
+ - Parameters.MAX_DIFFERENT_OCC_STR_ATTR
+
+ Returns
+ --------------
+ fea_df
+ Dataframe with the features
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+
+ fea_sel_df = automatic_feature_selection_df(df, parameters=parameters)
+ columns = set(fea_sel_df.columns)
+
+ if case_id_key in columns:
+ columns.remove(case_id_key)
+
+ if timestamp_key in columns:
+ columns.remove(timestamp_key)
+
+ return get_features_df(fea_sel_df, list(columns), parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/filtering_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/filtering_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..246b4af24cf163ed6bc91b91319a6f445fff975e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/filtering_utils.py
@@ -0,0 +1,80 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from copy import copy
+
+
+def keep_one_trace_per_variant(log, parameters=None):
+ """
+ Keeps only one trace per variant (does not matter for basic inductive miner)
+
+ Parameters
+ --------------
+ log
+ Log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ --------------
+ new_log
+ Log (with one trace per variant)
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.statistics.variants.log import get as variants_module
+
+ new_log = EventLog()
+ if log is not None:
+ variants = variants_module.get_variants(log, parameters=parameters)
+ for var in variants:
+ curr_trace = variants[var][0]
+ new_trace = Trace(attributes=copy(curr_trace.attributes))
+ new_trace.attributes["@@num_traces"] = len(variants[var])
+ for ev in curr_trace:
+ new_trace.append(ev)
+ new_log.append(new_trace)
+
+ return new_log
+
+
+def keep_only_one_attribute_per_event(log, attribute_key):
+ """
+ Keeps only one attribute per event
+
+ Parameters
+ ---------------
+ log
+ Event log
+ attribute_key
+ Attribute key
+ """
+ new_log = EventLog()
+ if log is not None:
+ for trace in log:
+ new_trace = Trace()
+ for ev in trace:
+ new_trace.append(Event({attribute_key: ev[attribute_key]}))
+ new_log.append(new_trace)
+
+ return new_log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_class_representation.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_class_representation.py
new file mode 100644
index 0000000000000000000000000000000000000000..cce3db019fe1a17fc1d75aa5c6aed4e3d28d5904
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_class_representation.py
@@ -0,0 +1,180 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import numpy as np
+from pm4py.util.business_hours import BusinessHours
+from pm4py.util import constants
+
+
+def get_class_representation_by_str_ev_attr_value_presence(
+ log, str_attr_name, str_attr_value
+):
+ """
+ Get the representation for the target part of the decision tree learning
+ if the focus is on the presence of a given value of a (string) event attribute
+
+ Parameters
+ -------------
+ log
+ Trace log
+ str_attr_name
+ Attribute name to consider
+ str_attr_value
+ Attribute value to consider
+
+ Returns
+ -------------
+ target
+ Target part for decision tree learning
+ classes
+ Name of the classes, in order
+ """
+ count = 0
+ dictionary = {}
+ target = []
+ classes = []
+
+ for trace in log:
+ value = False
+ for event in trace:
+ if (
+ str_attr_name in event
+ and event[str_attr_name] == str_attr_value
+ ):
+ value = True
+ if str(value) not in dictionary:
+ dictionary[str(value)] = count
+ classes.append(str(value))
+ count = count + 1
+ target.append(dictionary[str(value)])
+
+ target = np.array(target)
+ return target, classes
+
+
+def get_class_representation_by_str_ev_attr_value_value(log, str_attr_name):
+ """
+ Get the representation for the target part of the decision tree learning
+ if the focus is on all (string) values of an event attribute
+
+ Parameters
+ ------------
+ log
+ Trace log
+ str_attr_name
+ Attribute name to consider
+
+ Returns
+ ------------
+ target
+ Target part for decision tree learning
+ classes
+ Name of the classes, in order
+ """
+ count = 0
+ dictionary = {}
+ target = []
+ classes = []
+
+ for trace in log:
+ value = "UNDEFINED"
+ for event in trace:
+ if str_attr_name in event and event[str_attr_name]:
+ value = event[str_attr_name]
+ if str(value) not in dictionary:
+ dictionary[str(value)] = count
+ classes.append(str(value))
+ count = count + 1
+ target.append(dictionary[str(value)])
+
+ target = np.array(target)
+ return target, classes
+
+
+def get_class_representation_by_trace_duration(
+ log, target_trace_duration, timestamp_key="time:timestamp", parameters=None
+):
+ """
+ Get class representation by splitting traces according to trace duration
+
+ Parameters
+ ------------
+ log
+ Trace log
+ target_trace_duration
+ Target trace duration
+ timestamp_key
+ Timestamp key
+
+ Returns
+ ------------
+ target
+ Target part for decision tree learning
+ classes
+ Name of the classes, in order
+ """
+ if parameters is None:
+ parameters = {}
+
+ business_hours = (
+ parameters["business_hours"]
+ if "business_hours" in parameters
+ else False
+ )
+ business_hours_slots = (
+ parameters["business_hour_slots"]
+ if "business_hour_slots" in parameters
+ else constants.DEFAULT_BUSINESS_HOUR_SLOTS
+ )
+
+ count = 0
+ dictionary = {}
+ target = []
+ classes = []
+
+ for trace in log:
+ value = "LESSEQUAL"
+ if (
+ len(trace) > 0
+ and timestamp_key in trace[0]
+ and timestamp_key in trace[-1]
+ ):
+ timestamp_st = trace[0][timestamp_key]
+ timestamp_et = trace[-1][timestamp_key]
+ if business_hours:
+ bh = BusinessHours(
+ timestamp_st,
+ timestamp_et,
+ business_hour_slots=business_hours_slots,
+ )
+ diff = bh.get_seconds()
+ else:
+ diff = (timestamp_et - timestamp_st).total_seconds()
+ if diff > target_trace_duration:
+ value = "GREATER"
+ if str(value) not in dictionary:
+ dictionary[str(value)] = count
+ classes.append(str(value))
+ count = count + 1
+ target.append(dictionary[str(value)])
+
+ target = np.array(target)
+ return target, classes
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_log_encoded.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_log_encoded.py
new file mode 100644
index 0000000000000000000000000000000000000000..a04d2933d926be6da72c7a65feeacd9ac9bad2da
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_log_encoded.py
@@ -0,0 +1,104 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import numpy as np
+
+
+def get_log_encoded(
+ event_log, trace_attributes=[], event_attributes=[], concatenate=False
+):
+ """
+ Get event log encoded into matrix.
+
+ Parameters
+ ------------
+ event_log
+ Trace log
+ trace_attributes
+ Attributes of the trace to be encoded
+ event_attributes
+ Attributes of the events to be encoded
+ concatenate
+ Boolean indicating if to generate all sub-sequences of events in a trace
+
+ Returns
+ ------------
+ dataset
+ A numpy matrix with the event log
+ columns
+ The names of the columns in the dataset
+ """
+ columns = []
+ dataset = []
+
+ max_trace_len = 0
+
+ for trace_index, trace in enumerate(event_log):
+ trace_encoding = []
+ tr_columns = []
+
+ for trace_attribute in trace_attributes:
+ tr_columns.append(trace_attribute)
+
+ try:
+ attr = trace.attributes[trace_attribute]
+ except BaseException:
+ attr = None
+ trace_encoding.append(attr)
+
+ for event_index, event in enumerate(trace):
+ for event_attribute in event_attributes:
+ tr_columns.append(event_attribute)
+
+ try:
+ attr = event[event_attribute]
+ except BaseException:
+ attr = None
+ trace_encoding.append(attr)
+
+ # For each trace in the event log, sequentially append the
+ # event sequence until that event
+ if concatenate is True:
+ if len(trace_encoding) > max_trace_len:
+ max_trace_len = len(trace_encoding)
+ columns = tr_columns
+
+ dataset.append(np.asarray(trace_encoding))
+
+ if concatenate is not True:
+ if len(trace_encoding) > max_trace_len:
+ max_trace_len = len(trace_encoding)
+ columns = tr_columns
+
+ dataset.append(np.asarray(trace_encoding))
+
+ dataset = np.asarray(
+ [
+ np.pad(
+ a, (0, max_trace_len - len(a)), "constant", constant_values=0
+ )
+ for a in dataset
+ ]
+ )
+
+ columns = np.asarray(columns)
+
+ return dataset, columns
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_prefixes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_prefixes.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cc58e68615fe1522adc4a4f02c8d890bc663ebb
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/get_prefixes.py
@@ -0,0 +1,274 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from copy import deepcopy
+
+from pm4py.objects.log.obj import EventLog, Trace
+from pm4py.objects.log.util import basic_filter
+from pm4py.util import xes_constants as xes
+from pm4py.util import constants
+import logging
+
+
+def get_prefixes_from_log(log: EventLog, length: int) -> EventLog:
+ """
+ Gets the prefixes of a log of a given length
+
+ Parameters
+ ----------------
+ log
+ Event log
+ length
+ Length
+
+ Returns
+ ----------------
+ prefix_log
+ Log contain the prefixes:
+ - if a trace has lower or identical length, it is included as-is
+ - if a trace has greater length, it is cut
+ """
+ prefix_log = EventLog(
+ list(),
+ attributes=log.attributes,
+ extensions=log.extensions,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ properties=log.properties,
+ )
+ for trace in log:
+ if len(trace) <= length:
+ prefix_log.append(trace)
+ else:
+ new_trace = Trace(attributes=trace.attributes)
+ for i in range(length):
+ new_trace.append(trace[i])
+ prefix_log.append(new_trace)
+ return prefix_log
+
+
+def get_log_with_log_prefixes(log, parameters=None):
+ """
+ Gets an extended log that contains, in order, all the prefixes for a case of the original log
+
+ Parameters
+ --------------
+ log
+ Original log
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ -------------
+ all_prefixes_log
+ Log with all the prefixes
+ change_indexes
+ Indexes of the extended log where there was a change between cases
+ """
+ all_prefixes_log = EventLog()
+ change_indexes = []
+
+ for trace in log:
+ cumulative_trace = Trace()
+ for event in trace:
+ all_prefixes_log.append(deepcopy(cumulative_trace))
+ cumulative_trace.append(event)
+ all_prefixes_log.append(deepcopy(cumulative_trace))
+ change_indexes.append([len(all_prefixes_log) - 1] * len(trace))
+
+ return all_prefixes_log, change_indexes
+
+
+def get_log_traces_to_activities(log, activities, parameters=None):
+ """
+ Get sublogs taking to each one of the specified activities
+
+ Parameters
+ -------------
+ log
+ Trace log object
+ activities
+ List of activities in the log
+ parameters
+ Possible parameters of the algorithm, including:
+ PARAMETER_CONSTANT_ACTIVITY_KEY -> activity
+ PARAMETER_CONSTANT_TIMESTAMP_KEY -> timestamp
+
+ Returns
+ -------------
+ list_logs
+ List of event logs taking to the first occurrence of each activity
+ considered_activities
+ All activities that are effectively have been inserted in the list of logs (in some of them, the resulting log
+ may be empty)
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = (
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+ parameters[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = activity_key
+
+ list_logs = []
+ considered_activities = []
+ for act in activities:
+ other_acts = [ac for ac in activities if not ac == act]
+ parameters_filt1 = deepcopy(parameters)
+ parameters_filt2 = deepcopy(parameters)
+ parameters_filt1["positive"] = True
+ parameters_filt2["positive"] = False
+ filtered_log = basic_filter.filter_log_traces_attr(
+ log, [act], parameters=parameters_filt1
+ )
+ logging.info(
+ "get_log_traces_to_activities activities="
+ + str(activities)
+ + " act="
+ + str(act)
+ + " 0 len(filtered_log)="
+ + str(len(filtered_log))
+ )
+ filtered_log = basic_filter.filter_log_traces_attr(
+ filtered_log, other_acts, parameters=parameters_filt2
+ )
+ logging.info(
+ "get_log_traces_to_activities activities="
+ + str(activities)
+ + " act="
+ + str(act)
+ + " 1 len(filtered_log)="
+ + str(len(filtered_log))
+ )
+ filtered_log, act_durations = get_log_traces_until_activity(
+ filtered_log, act, parameters=parameters
+ )
+ logging.info(
+ "get_log_traces_to_activities activities="
+ + str(activities)
+ + " act="
+ + str(act)
+ + " 2 len(filtered_log)="
+ + str(len(filtered_log))
+ )
+ if filtered_log:
+ list_logs.append(filtered_log)
+ considered_activities.append(act)
+
+ return list_logs, considered_activities
+
+
+def get_log_traces_until_activity(log, activity, parameters=None):
+ """
+ Gets a reduced version of the log containing, for each trace, only the events before a
+ specified activity
+
+ Parameters
+ -------------
+ log
+ Trace log
+ activity
+ Activity to reach
+ parameters
+ Possible parameters of the algorithm, including:
+ PARAMETER_CONSTANT_ACTIVITY_KEY -> activity
+ PARAMETER_CONSTANT_TIMESTAMP_KEY -> timestamp
+
+ Returns
+ -------------
+ new_log
+ New log
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = (
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+ timestamp_key = (
+ parameters[constants.PARAMETER_CONSTANT_TIMESTAMP_KEY]
+ if constants.PARAMETER_CONSTANT_TIMESTAMP_KEY in parameters
+ else xes.DEFAULT_TIMESTAMP_KEY
+ )
+ duration_attribute = (
+ parameters["duration"] if "duration" in parameters else None
+ )
+ use_future_attributes = (
+ parameters["use_future_attributes"]
+ if "use_future_attributes" in parameters
+ else False
+ )
+
+ new_log = EventLog()
+ traces_interlapsed_time_to_act = []
+
+ i = 0
+ while i < len(log):
+ ev_in_tr_w_act = sorted(
+ [
+ j
+ for j in range(len(log[i]))
+ if log[i][j][activity_key] == activity
+ ]
+ )
+ if ev_in_tr_w_act and ev_in_tr_w_act[0] > 0:
+ new_trace = Trace(log[i][0: ev_in_tr_w_act[0]])
+ for attr in log[i].attributes:
+ new_trace.attributes[attr] = log[i].attributes[attr]
+
+ if duration_attribute is None:
+ try:
+ curr_trace_interlapsed_time_to_act = (
+ log[i][ev_in_tr_w_act[0]][timestamp_key].timestamp()
+ - log[i][ev_in_tr_w_act[0] - 1][
+ timestamp_key
+ ].timestamp()
+ )
+ except BaseException:
+ curr_trace_interlapsed_time_to_act = (
+ log[i][ev_in_tr_w_act[0]][timestamp_key]
+ - log[i][ev_in_tr_w_act[0] - 1][timestamp_key]
+ )
+ logging.error("timestamp_key not timestamp")
+ else:
+ curr_trace_interlapsed_time_to_act = log[i][ev_in_tr_w_act[0]][
+ duration_attribute
+ ]
+
+ traces_interlapsed_time_to_act.append(
+ curr_trace_interlapsed_time_to_act
+ )
+
+ if use_future_attributes:
+ for j in range(ev_in_tr_w_act[0] + 1, len(log[i])):
+ new_ev = deepcopy(log[i][j])
+ if activity_key in new_ev:
+ del new_ev[activity_key]
+ new_trace.append(new_ev)
+
+ new_log.append(new_trace)
+ i = i + 1
+
+ return new_log, traces_interlapsed_time_to_act
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/index_attribute.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/index_attribute.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebb8ebd0efce8a1a9d15068b2feda8f005014dda
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/index_attribute.py
@@ -0,0 +1,64 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog
+
+
+def insert_event_index_as_event_attribute(
+ stream, event_index_attr_name="@@eventindex"
+):
+ """
+ Insert the current event index as event attribute
+
+ Parameters
+ -----------
+ stream
+ Stream
+ event_index_attr_name
+ Attribute name given to the event index
+ """
+
+ if not type(stream) is EventLog:
+ for i in range(0, len(stream._list)):
+ stream._list[i][event_index_attr_name] = i + 1
+
+ return stream
+
+
+def insert_trace_index_as_event_attribute(
+ log, trace_index_attr_name="@@traceindex"
+):
+ """
+ Inserts the current trace index as event attribute
+ (overrides previous values if needed)
+
+ Parameters
+ -----------
+ log
+ Log
+ trace_index_attr_name
+ Attribute name given to the trace index
+ """
+ for i in range(len(log._list)):
+ for j in range(len(log._list[i])):
+ log._list[i][j][trace_index_attr_name] = i + 1
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/insert_classifier.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/insert_classifier.py
new file mode 100644
index 0000000000000000000000000000000000000000..dad9b5f827314830b6f3f734ec02ac155e780437
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/insert_classifier.py
@@ -0,0 +1,134 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+def search_act_class_attr(log, force_activity_transition_insertion=False):
+ """
+ Search among classifiers expressed in the log one that is good for the process model extraction
+
+ Parameters
+ -----------
+ log
+ Trace log
+ force_activity_transition_insertion
+ Optionally force the activitiy+transition classifier insertion
+
+ Returns
+ -----------
+ log
+ Trace log (plus eventually one additional event attribute as the classifier)
+ """
+ classifier = None
+ if (
+ log.classifiers
+ and "Activity classifier" in log.classifiers
+ and log.classifiers["Activity classifier"]
+ ):
+ classifier = "Activity classifier"
+ elif (
+ log.classifiers
+ and "MXML Legacy Classifier" in log.classifiers
+ and log.classifiers["MXML Legacy Classifier"]
+ ):
+ classifier = "MXML Legacy Classifier"
+ return insert_activity_classifier_attribute(
+ log,
+ classifier,
+ force_activity_transition_insertion=force_activity_transition_insertion,
+ )
+
+
+def insert_activity_classifier_attribute(
+ log, classifier, force_activity_transition_insertion=False
+):
+ """
+ Insert the specified classifier as additional event attribute in the log
+
+ Parameters
+ -----------
+ log
+ Trace log
+ classifier
+ Event classifier
+ force_activity_transition_insertion
+ Optionally force the activitiy+transition classifier insertion
+
+ Returns
+ --------
+ log
+ Trace log (plus eventually one additional event attribute as the classifier)
+ classifier_attr_key
+ Attribute name of the attribute that contains the classifier value
+ """
+ classifier_attr_key = None
+ if classifier is not None:
+ classifier_attr_key = "@@classifier"
+ for trace in log:
+ for event in trace:
+ classifier_value = "+".join(
+ [event[x] for x in log.classifiers[classifier]]
+ )
+ event[classifier_attr_key] = classifier_value
+ elif force_activity_transition_insertion:
+ if (
+ len(log) > 0
+ and len(log[0]) > 0
+ and "concept:name" in log[0][0]
+ and "lifecycle:transition" in log[0][0]
+ ):
+ classifier_attr_key = "@@classifier"
+ for trace in log:
+ for event in trace:
+ classifier_value = (
+ event["concept:name"]
+ + "+"
+ + event["lifecycle:transition"]
+ )
+ event[classifier_attr_key] = classifier_value
+ return log, classifier_attr_key
+
+
+def insert_trace_classifier_attribute(log, classifier):
+ """
+ Insert the specified classifier as additional trace attribute in the log
+
+ Parameter
+ -----------
+ log
+ Trace log
+ classifier
+ Event classifier
+
+ Returns
+ -----------
+ log
+ Trace log (plus eventually one additional event attribute as the classifier)
+ classifier_attr_key
+ Attribute name of the attribute that contains the classifier value
+ """
+ classifier_attr_key = None
+ if classifier is not None:
+ classifier_attr_key = "@@traceClassifier"
+ for trace in log:
+ classifier_value = "+".join(
+ [trace.attributes[x] for x in log.classifiers[classifier]]
+ )
+ trace.attributes[classifier_attr_key] = classifier_value
+ return log, classifier_attr_key
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/interval_lifecycle.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/interval_lifecycle.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f96f8dc8d612322c90f5ba06cdd7b4e91ccec9f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/interval_lifecycle.py
@@ -0,0 +1,377 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util.business_hours import BusinessHours
+from pm4py.objects.log.util import sorting
+from pm4py.util import constants
+from pm4py.util import xes_constants as xes
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from copy import copy
+from enum import Enum
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
+ TRANSITION_KEY = constants.PARAMETER_CONSTANT_TRANSITION_KEY
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ LIFECYCLE_INSTANCE_KEY = "pm4py:param:lifecycle:instance:key"
+ BUSINESS_HOURS = "business_hours"
+ BUSINESS_HOUR_SLOTS = "business_hour_slots"
+ WORKCALENDAR = "workcalendar"
+
+
+def to_interval(log, parameters=None):
+ """
+ Converts a log to interval format (e.g. an event has two timestamps)
+ from lifecycle format (an event has only a timestamp, and a transition lifecycle)
+
+ Parameters
+ -------------
+ log
+ Log (expressed in the lifecycle format)
+ parameters
+ Possible parameters of the method (activity, timestamp key, start timestamp key, transition ...)
+
+ Returns
+ -------------
+ log
+ Interval event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes.DEFAULT_START_TIMESTAMP_KEY,
+ )
+ transition_key = exec_utils.get_param_value(
+ Parameters.TRANSITION_KEY, parameters, xes.DEFAULT_TRANSITION_KEY
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY
+ )
+ lifecycle_instance_key = exec_utils.get_param_value(
+ Parameters.LIFECYCLE_INSTANCE_KEY, parameters, xes.DEFAULT_INSTANCE_KEY
+ )
+ business_hours = exec_utils.get_param_value(
+ Parameters.BUSINESS_HOURS, parameters, False
+ )
+ business_hours_slots = exec_utils.get_param_value(
+ Parameters.BUSINESS_HOUR_SLOTS,
+ parameters,
+ constants.DEFAULT_BUSINESS_HOUR_SLOTS,
+ )
+
+ if log is not None and len(log) > 0:
+ if (
+ "PM4PY_TYPE" in log.attributes
+ and log.attributes["PM4PY_TYPE"] == "interval"
+ ):
+ return log
+ if log[0] is not None and len(log[0]) > 0:
+ first_event = log[0][0]
+ if start_timestamp_key in first_event:
+ return log
+
+ new_log = EventLog(
+ attributes=copy(log.attributes),
+ extensions=copy(log.extensions),
+ classifiers=copy(log.classifiers),
+ omni_present=copy(log.omni_present),
+ properties=copy(log.properties),
+ )
+ new_log.attributes["PM4PY_TYPE"] = "interval"
+ new_log.properties[
+ constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
+ ] = xes.DEFAULT_START_TIMESTAMP_KEY
+
+ for trace in log:
+ new_trace = Trace()
+ for attr in trace.attributes:
+ new_trace.attributes[attr] = trace.attributes[attr]
+ activities_start = {}
+ for event in trace:
+ activity = event[activity_key]
+ instance = (
+ event[lifecycle_instance_key]
+ if lifecycle_instance_key in event
+ else None
+ )
+ activity = (activity, instance)
+ transition = (
+ event[transition_key]
+ if transition_key in event
+ else "complete"
+ )
+ timestamp = event[timestamp_key]
+ if transition.lower() == "start":
+ if activity not in activities_start:
+ activities_start[activity] = list()
+ activities_start[activity].append(event)
+ elif transition.lower() == "complete":
+ start_event = None
+ start_timestamp = event[timestamp_key]
+ if (
+ activity in activities_start
+ and len(activities_start[activity]) > 0
+ ):
+ start_event = activities_start[activity].pop(0)
+ start_timestamp = start_event[timestamp_key]
+ new_event = Event()
+ for attr in event:
+ if (
+ not attr == timestamp_key
+ and not attr == transition_key
+ ):
+ new_event[attr] = event[attr]
+ if start_event is not None:
+ for attr in start_event:
+ if (
+ not attr == timestamp_key
+ and not attr == transition_key
+ ):
+ new_event["@@startevent_" + attr] = (
+ start_event[attr]
+ )
+ new_event[start_timestamp_key] = start_timestamp
+ new_event[timestamp_key] = timestamp
+ new_event["@@duration"] = (
+ timestamp - start_timestamp
+ ).total_seconds()
+
+ if business_hours:
+ bh = BusinessHours(
+ start_timestamp,
+ timestamp,
+ business_hour_slots=business_hours_slots,
+ )
+ new_event["@@approx_bh_duration"] = bh.get_seconds()
+
+ new_trace.append(new_event)
+ new_trace = sorting.sort_timestamp_trace(
+ new_trace, start_timestamp_key
+ )
+ new_log.append(new_trace)
+ return new_log
+
+ return log
+
+
+def to_lifecycle(log, parameters=None):
+ """
+ Converts a log from interval format (e.g. an event has two timestamps)
+ to lifecycle format (an event has only a timestamp, and a transition lifecycle)
+
+ Parameters
+ -------------
+ log
+ Log (expressed in the interval format)
+ parameters
+ Possible parameters of the method (activity, timestamp key, start timestamp key, transition ...)
+
+ Returns
+ -------------
+ log
+ Lifecycle event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes.DEFAULT_START_TIMESTAMP_KEY,
+ )
+ transition_key = exec_utils.get_param_value(
+ Parameters.TRANSITION_KEY, parameters, xes.DEFAULT_TRANSITION_KEY
+ )
+
+ if log is not None and len(log) > 0:
+ if (
+ "PM4PY_TYPE" in log.attributes
+ and log.attributes["PM4PY_TYPE"] == "lifecycle"
+ ):
+ return log
+ if log[0] is not None and len(log[0]) > 0:
+ first_event = log[0][0]
+ if transition_key in first_event:
+ return log
+
+ new_log = EventLog(
+ attributes=copy(log.attributes),
+ extensions=copy(log.extensions),
+ classifiers=copy(log.classifiers),
+ omni_present=copy(log.omni_present),
+ properties=copy(log.properties),
+ )
+ new_log.attributes["PM4PY_TYPE"] = "lifecycle"
+
+ for trace in log:
+ new_trace = Trace()
+ for attr in trace.attributes:
+ new_trace.attributes[attr] = trace.attributes[attr]
+ list_events = []
+ for index, event in enumerate(trace):
+ new_event_start = Event()
+ new_event_complete = Event()
+ for attr in event:
+ if (
+ not attr == timestamp_key
+ and not attr == start_timestamp_key
+ ):
+ new_event_start[attr] = event[attr]
+ new_event_complete[attr] = event[attr]
+ new_event_start[timestamp_key] = event[start_timestamp_key]
+ new_event_start[transition_key] = "start"
+ new_event_start["@@custom_lif_id"] = 0
+ new_event_start["@@origin_ev_idx"] = index
+ new_event_complete[timestamp_key] = event[timestamp_key]
+ new_event_complete[transition_key] = "complete"
+ new_event_complete["@@custom_lif_id"] = 1
+ new_event_complete["@@origin_ev_idx"] = index
+ list_events.append(new_event_start)
+ list_events.append(new_event_complete)
+ list_events = sorted(
+ list_events,
+ key=lambda x: (
+ x[timestamp_key],
+ x["@@origin_ev_idx"],
+ x["@@custom_lif_id"],
+ ),
+ )
+ for ev in list_events:
+ new_trace.append(ev)
+ new_log.append(new_trace)
+ return new_log
+ return log
+
+
+def assign_lead_cycle_time(log, parameters=None):
+ """
+ Assigns the lead and cycle time to an interval log
+
+ Parameters
+ -------------
+ log
+ Interval log
+ parameters
+ Parameters of the algorithm, including: start_timestamp_key, timestamp_key, business_hour_slots
+ """
+ if parameters is None:
+ parameters = {}
+
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes.DEFAULT_START_TIMESTAMP_KEY,
+ )
+ business_hours_slots = exec_utils.get_param_value(
+ Parameters.BUSINESS_HOUR_SLOTS,
+ parameters,
+ constants.DEFAULT_BUSINESS_HOUR_SLOTS,
+ )
+
+ interval_log = to_interval(log, parameters=parameters)
+
+ for trace in interval_log:
+ approx_partial_lead_time = 0
+ approx_partial_cycle_time = 0
+ approx_wasted_time = 0
+ max_et = None
+ max_et_seconds = 0
+ for i in range(len(trace)):
+ this_wasted_time = 0
+ st = trace[i][start_timestamp_key]
+ st_seconds = st.timestamp()
+ et = trace[i][timestamp_key]
+ et_seconds = et.timestamp()
+
+ if max_et_seconds > 0 and st_seconds > max_et_seconds:
+ bh_unworked = BusinessHours(
+ max_et, st, business_hour_slots=business_hours_slots
+ )
+ unworked_sec = bh_unworked.get_seconds()
+ approx_partial_lead_time = (
+ approx_partial_lead_time + unworked_sec
+ )
+ approx_wasted_time = approx_wasted_time + unworked_sec
+ this_wasted_time = unworked_sec
+
+ if st_seconds >= max_et_seconds:
+ bh = BusinessHours(
+ st, et, business_hour_slots=business_hours_slots
+ )
+ approx_bh_duration = bh.get_seconds()
+
+ approx_partial_cycle_time = (
+ approx_partial_cycle_time + approx_bh_duration
+ )
+ approx_partial_lead_time = (
+ approx_partial_lead_time + approx_bh_duration
+ )
+ elif st_seconds < max_et_seconds and et_seconds > max_et_seconds:
+ bh = BusinessHours(
+ max_et, et, business_hour_slots=business_hours_slots
+ )
+ approx_bh_duration = bh.get_seconds()
+
+ approx_partial_cycle_time = (
+ approx_partial_cycle_time + approx_bh_duration
+ )
+ approx_partial_lead_time = (
+ approx_partial_lead_time + approx_bh_duration
+ )
+
+ if et_seconds > max_et_seconds:
+ max_et_seconds = et_seconds
+ max_et = et
+
+ ratio_cycle_lead_time = 1
+ if approx_partial_lead_time > 0:
+ ratio_cycle_lead_time = (
+ approx_partial_cycle_time / approx_partial_lead_time
+ )
+
+ trace[i][
+ "@@approx_bh_partial_cycle_time"
+ ] = approx_partial_cycle_time
+ trace[i][
+ "@@approx_bh_partial_lead_time"
+ ] = approx_partial_lead_time
+ trace[i]["@@approx_bh_overall_wasted_time"] = approx_wasted_time
+ trace[i]["@@approx_bh_this_wasted_time"] = this_wasted_time
+ trace[i][
+ "@approx_bh_ratio_cycle_lead_time"
+ ] = ratio_cycle_lead_time
+
+ return interval_log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/log.py
new file mode 100644
index 0000000000000000000000000000000000000000..2712e91f28f5d4294819300525b891f13aeb1950
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/log.py
@@ -0,0 +1,179 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import xes_constants as xes_util
+
+
+# TODO: we can do some instance checking and then support both trace level
+# and event level logs..
+def get_event_labels(event_log, key):
+ """
+ Fetches the labels present in a log, given a key to use within the events.
+
+ Parameters
+ ----------
+ :param event_log: log to use
+ :param key: to use for event identification, can for example be "concept:name"
+
+ Returns
+ -------
+ :return: a list of labels
+ """
+ labels = []
+ for t in event_log:
+ for e in t:
+ if key in e and e[key] not in labels:
+ labels.append(e[key])
+ return labels
+
+
+def get_event_labels_counted(event_log, key):
+ """
+ Fetches the labels (and their frequency) present in a log, given a key to use within the events.
+
+ Parameters
+ ----------
+ :param event_log: log to use
+ :param key: to use for event identification, can for example be "concept:name"
+
+ Returns
+ -------
+ :return: a list of labels
+ """
+ labels = dict()
+ for t in event_log:
+ for e in t:
+ if key in e:
+ if e[key] not in labels:
+ labels[e[key]] = 0
+ labels[e[key]] = labels[e[key]] + 1
+ return labels
+
+
+def get_trace_variants(event_log, key=xes_util.DEFAULT_NAME_KEY):
+ """
+ Returns a pair of a list of (variants, dict[index -> trace]) where the index of a variant maps to all traces
+ describing that variant, with that key.
+
+ Parameters
+ ---------
+ :param event_log: log
+ :param key: key to use to identify the label of an event
+
+ Returns
+ -------
+ :return:
+ """
+ variants = []
+ variant_map = dict()
+ for t in event_log:
+ variant = list(map(lambda e: e[key], t))
+ new = True
+ for i in range(0, len(variants)):
+ if variants[i] == variant:
+ variant_map[i].append(t)
+ new = False
+ break
+ if new:
+ variant_map[len(variants)] = [t]
+ variants.append(variant)
+ return variants, variant_map
+
+
+def project_traces(event_log, keys=xes_util.DEFAULT_NAME_KEY):
+ """
+ projects traces on a (set of) event attribute key(s).
+ If the key provided is of type string, each trace is converted into a list of strings.
+ If the key provided is a collection, each trace is converted into a list of (smaller) dicts of key value pairs
+
+ :param event_log:
+ :param keys:
+ :return:
+ """
+ if isinstance(keys, str):
+ return list(map(lambda t: list(map(lambda e: e[keys], t)), event_log))
+ else:
+ return list(
+ map(
+ lambda t: list(
+ map(lambda e: {key: e[key] for key in keys}, t)
+ ),
+ event_log,
+ )
+ )
+
+
+def derive_and_lift_trace_attributes_from_event_attributes(
+ trlog, ignore=None, retain_on_event_level=False, verbose=False
+):
+ if ignore is None:
+ ignore = set()
+ candidates = set(trlog[0][0].keys())
+ for i in ignore:
+ candidates.remove(i)
+ if verbose:
+ print("candidates: %s" % candidates)
+ for t in trlog:
+ attr = dict(t[0])
+ for e in t:
+ for k in candidates.copy():
+ if k not in e:
+ if verbose:
+ print("removing %s, was not present in event" % k)
+ candidates.remove(k)
+ continue
+ if e[k] != attr[k]:
+ if verbose:
+ print(
+ "removing "
+ + k
+ + " for trace with id "
+ + t.attributes["concept:name"]
+ + ", mismatch "
+ + str(e[k])
+ + " != "
+ + str(attr[k])
+ )
+ candidates.remove(k)
+ continue
+ if len(candidates) == 0:
+ return trlog
+
+ for t in trlog:
+ for key in candidates:
+ t.attributes[key] = t[0][key]
+ if not retain_on_event_level:
+ for e in t:
+ del e[key]
+
+ return trlog
+
+
+def add_artficial_start_and_end(
+ event_log,
+ start="[start>",
+ end="[end]",
+ activity_key=xes_util.DEFAULT_NAME_KEY,
+):
+ for trace in event_log:
+ trace.insert(0, event_log.Event({activity_key: start}))
+ trace.append(event_log.Event({activity_key: end}))
+ return event_log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/log_regex.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/log_regex.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcacf8d97720ffdac357357c4dc53d66f94f2a2c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/log_regex.py
@@ -0,0 +1,186 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Dict
+
+from pm4py.objects.log.obj import EventLog
+from pm4py.util import xes_constants as xes
+from pm4py.util.constants import PARAMETER_CONSTANT_ACTIVITY_KEY
+from pm4py.util.regex import SharedObj, get_new_char
+
+
+def get_encoded_trace(trace, mapping, parameters=None):
+ """
+ Gets the encoding of the provided trace
+
+ Parameters
+ -------------
+ trace
+ Trace of the event log
+ mapping
+ Mapping (activity to symbol)
+
+ Returns
+ -------------
+ trace_str
+ Trace string
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = (
+ parameters[PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+
+ trace_str = "".join(
+ [mapping[x[activity_key]] for x in trace if x[activity_key] in mapping]
+ )
+
+ return trace_str
+
+
+def get_encoded_log(log, mapping, parameters=None):
+ """
+ Gets the encoding of the provided log
+
+ Parameters
+ -------------
+ log
+ Event log
+ mapping
+ Mapping (activity to symbol)
+
+ Returns
+ -------------
+ list_str
+ List of encoded strings
+ """
+ if parameters is None:
+ parameters = {}
+
+ list_str = list()
+
+ for trace in log:
+ list_str.append(
+ get_encoded_trace(trace, mapping, parameters=parameters)
+ )
+
+ return list_str
+
+
+def form_encoding_dictio_from_log(log, parameters=None):
+ """
+ Forms the encoding dictionary from the current log
+
+ Parameters
+ -------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ encoding_dictio
+ Encoding dictionary
+ """
+ from pm4py.statistics.attributes.log import get as attributes_get
+
+ if parameters is None:
+ parameters = {}
+
+ activity_key = (
+ parameters[PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+
+ shared_obj = SharedObj()
+
+ activities = attributes_get.get_attribute_values(
+ log, activity_key, parameters=parameters
+ )
+
+ mapping = {}
+
+ for act in activities:
+ get_new_char(act, shared_obj)
+ mapping[act] = shared_obj.mapping_dictio[act]
+
+ return mapping
+
+
+def form_encoding_dictio_from_two_logs(
+ log1: EventLog, log2: EventLog, parameters=None
+) -> Dict[str, str]:
+ """
+ Forms the encoding dictionary from a couple of logs
+
+ Parameters
+ ----------------
+ log1
+ First log
+ log2
+ Second log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ encoding_dictio
+ Encoding dictionary
+ """
+ from pm4py.statistics.attributes.log import get as attributes_get
+
+ if parameters is None:
+ parameters = {}
+
+ activity_key = (
+ parameters[PARAMETER_CONSTANT_ACTIVITY_KEY]
+ if PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
+ else xes.DEFAULT_NAME_KEY
+ )
+
+ shared_obj = SharedObj()
+
+ activities_log_1 = attributes_get.get_attribute_values(
+ log1, activity_key, parameters=parameters
+ )
+ activities_log_2 = attributes_get.get_attribute_values(
+ log2, activity_key, parameters=parameters
+ )
+
+ mapping = {}
+
+ for act in activities_log_1:
+ if act not in mapping:
+ get_new_char(act, shared_obj)
+ mapping[act] = shared_obj.mapping_dictio[act]
+
+ for act in activities_log_2:
+ if act not in mapping:
+ get_new_char(act, shared_obj)
+ mapping[act] = shared_obj.mapping_dictio[act]
+
+ return mapping
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/move_attrs_to_trace.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/move_attrs_to_trace.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d614f59eca0bdb54da2db46502f6946b41a6397
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/move_attrs_to_trace.py
@@ -0,0 +1,95 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog, XESExtension
+from typing import Optional, Dict, Any, Union
+from enum import Enum
+from pm4py.util import exec_utils
+from copy import deepcopy
+
+
+class Parameters(Enum):
+ ENABLE_DEEPCOPY = "enable_deepcopy"
+
+
+def apply(
+ log: EventLog,
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
+) -> EventLog:
+ """
+ Moves the attributes that are constant for all the events of the trace, and they
+ do not belong to a standard extension, to the trace level
+
+ Parameters
+ ----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.DEEPCOPY => enables the deepcopy of the event log
+
+ Returns
+ ----------------
+ log
+ Event log, where some attribute has been possibly moved from the event to the trace level
+ """
+ if parameters is None:
+ parameters = {}
+
+ enable_deepcopy = exec_utils.get_param_value(
+ Parameters.ENABLE_DEEPCOPY, parameters, False
+ )
+ if enable_deepcopy:
+ log = deepcopy(log)
+
+ main_extensions = set()
+ for e in XESExtension:
+ main_extensions.add(e.value[1])
+
+ candidates = None
+ for trace in log:
+ values_count = {}
+ for eve in trace:
+ for attr in eve:
+ if attr.split(":")[0] not in main_extensions:
+ if attr not in trace.attributes:
+ if attr not in values_count:
+ values_count[attr] = [eve[attr]]
+ else:
+ values_count[attr].append(eve[attr])
+ trace_candidates = set(
+ x
+ for x in values_count
+ if len(values_count[x]) == len(trace)
+ and len(set(values_count[x])) == 1
+ )
+ if candidates is not None:
+ candidates = trace_candidates.intersection(candidates)
+ else:
+ candidates = trace_candidates
+
+ for attr in candidates:
+ for trace in log:
+ trace.attributes[attr] = trace[0][attr]
+ for ev in trace:
+ del ev[attr]
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pandas_log_wrapper.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pandas_log_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..92ca532877cafcfb9aa26cc494695a77cbe14014
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pandas_log_wrapper.py
@@ -0,0 +1,156 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import pandas as pd
+from typing import Optional, Dict, Any
+from pm4py.util import constants, exec_utils
+from enum import Enum
+from collections.abc import Sequence
+
+
+class Parameters(Enum):
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ CASE_ATTRIBUTE_PREFIX = constants.CASE_ATTRIBUTE_PREFIX
+
+
+class PandasTraceWrapper(Sequence):
+ def __init__(
+ self,
+ dataframe: pd.DataFrame,
+ parameters: Optional[Dict[Any, Any]] = None,
+ ):
+ if parameters is None:
+ parameters = {}
+
+ self.parameters = parameters
+ self.dataframe = dataframe
+ self.case_attribute_prefix = exec_utils.get_param_value(
+ Parameters.CASE_ATTRIBUTE_PREFIX,
+ parameters,
+ constants.CASE_ATTRIBUTE_PREFIX,
+ )
+
+ self.attributes = self.dataframe.loc[0].to_dict()
+ self.attributes = {
+ x.split(self.case_attribute_prefix)[-1]: y
+ for x, y in self.attributes.items()
+ if x.startswith(self.case_attribute_prefix)
+ }
+
+ def __getitem__(self, key):
+ if type(key) is slice:
+ start = key.start % len(self.dataframe)
+ stop = key.stop % len(self.dataframe)
+ sli = slice(start, stop - 1, key.step)
+ return self.dataframe.loc[sli].to_dict(orient="records")
+ key = key % len(self.dataframe)
+ return self.dataframe.loc[key].to_dict()
+
+ def __iter__(self):
+ return iter(self.dataframe.to_dict(orient="records"))
+
+ def __len__(self):
+ return len(self.dataframe)
+
+ def _get_list(self):
+ return self.dataframe.to_dict(orient="records")
+
+ _list = property(_get_list)
+
+
+class PandasLogWrapper(Sequence):
+ # permits to iterate over a Pandas dataframe and access its Traces object
+ # *without* a conversion to EventLog
+ def __init__(
+ self,
+ dataframe: pd.DataFrame,
+ parameters: Optional[Dict[Any, Any]] = None,
+ ):
+ if parameters is None:
+ parameters = {}
+
+ self.parameters = parameters
+ self.case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ self.dataframe = dataframe
+
+ self.grouped_dataframe = self.dataframe.groupby(
+ self.case_id_key
+ ).groups
+ self.keys = list(self.grouped_dataframe)
+
+ self.attributes = {}
+ self.extensions = {}
+ self.omni_present = {}
+ self.classifiers = {}
+ self.properties = {}
+
+ def __getitem__(self, key):
+ if type(key) is slice:
+ start = key.start % len(self.dataframe)
+ stop = key.stop % len(self.dataframe)
+ sli = slice(start, stop, key.step)
+ ret = []
+ for x in self.keys[sli]:
+ ret.append(
+ PandasTraceWrapper(
+ self.dataframe.loc[self.grouped_dataframe[x]]
+ .copy()
+ .reset_index(),
+ parameters=self.parameters,
+ )
+ )
+ return ret
+ key = key % len(self.grouped_dataframe)
+ return PandasTraceWrapper(
+ self.dataframe.loc[self.grouped_dataframe[self.keys[key]]]
+ .copy()
+ .reset_index(),
+ parameters=self.parameters,
+ )
+
+ def __iter__(self):
+ for key in self.keys:
+ yield PandasTraceWrapper(
+ self.dataframe.loc[self.grouped_dataframe[key]]
+ .copy()
+ .reset_index(),
+ parameters=self.parameters,
+ )
+
+ def __len__(self):
+ return len(self.grouped_dataframe)
+
+ def _get_list(self):
+ ret = []
+ for key in self.keys:
+ ret.append(
+ PandasTraceWrapper(
+ self.dataframe.loc[self.grouped_dataframe[key]]
+ .copy()
+ .reset_index(),
+ parameters=self.parameters,
+ )
+ )
+ return ret
+
+ _list = property(_get_list)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pandas_numpy_variants.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pandas_numpy_variants.py
new file mode 100644
index 0000000000000000000000000000000000000000..aca682f23b2931d2d18e62b369a406de550bb60d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pandas_numpy_variants.py
@@ -0,0 +1,123 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import pandas as pd
+from enum import Enum
+from pm4py.util import constants, xes_constants, pandas_utils, exec_utils
+import numpy as np
+from collections import Counter
+from typing import Tuple, Dict, Collection
+import importlib.util
+
+
+class Parameters(Enum):
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ INDEX_KEY = "index_key"
+
+
+def apply(
+ dataframe: pd.DataFrame, parameters=None
+) -> Tuple[Dict[Collection[str], int], Dict[str, Collection[str]]]:
+ """
+ Efficient method returning the variants from a Pandas dataframe (through Numpy)
+
+ Minimum viable example:
+
+ import pandas as pd
+ import pm4py
+ from pm4py.objects.log.util import pandas_numpy_variants
+
+ dataframe = pd.read_csv('tests/input_data/receipt.csv')
+ dataframe = pm4py.format_dataframe(dataframe)
+ variants_dict, case_variant = pandas_numpy_variants.apply(dataframe)
+
+
+ Parameters
+ ------------------
+ dataframe
+ Dataframe
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.CASE_ID_KEY => the case identifier
+ - Parameters.ACTIVITY_KEY => the activity
+ - Parameters.TIMESTAMP_KEY => the timestamp
+ - Parameters.INDEX_KEY => the index
+
+ Returns
+ ------------------
+ variants_dict
+ Dictionary associating to each variant the number of occurrences in the dataframe
+ case_variant
+ Dictionary associating to each case identifier the corresponding variant
+ """
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ index_key = exec_utils.get_param_value(
+ Parameters.INDEX_KEY, parameters, constants.DEFAULT_INDEX_KEY
+ )
+
+ if not (hasattr(dataframe, "attrs") and dataframe.attrs):
+ # dataframe has not been initialized through format_dataframe
+ dataframe = pandas_utils.insert_index(dataframe, index_key)
+ dataframe.sort_values([case_id_key, timestamp_key, index_key])
+
+ case_variant = dict()
+
+ if importlib.util.find_spec("cudf"):
+ case_variant = (
+ dataframe.groupby(case_id_key)[activity_key].agg(list).to_dict()
+ )
+ case_variant = {x: tuple(y) for x, y in case_variant.items()}
+ variants_counter = Counter(case_variant.values())
+ else:
+ variants_counter = Counter()
+ cases = dataframe[case_id_key].to_numpy()
+ activities = dataframe[activity_key].to_numpy()
+
+ c_unq, c_ind, c_counts = np.unique(
+ cases, return_index=True, return_counts=True
+ )
+
+ for i in range(len(c_ind)):
+ si = c_ind[i]
+ ei = si + c_counts[i]
+ acts = tuple(activities[si:ei])
+ variants_counter[acts] += 1
+ case_variant[c_unq[i]] = acts
+
+ # return as Python dictionary
+ variants_dict = {x: y for x, y in variants_counter.items()}
+
+ return variants_dict, case_variant
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pl_lazy_extra_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pl_lazy_extra_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed54d528b9096f65e4f5bd47fc9c61e2e97c412d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pl_lazy_extra_utils.py
@@ -0,0 +1,183 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from enum import Enum
+from typing import Optional, Dict, Any, Iterable, List, Set
+
+import polars as pl
+
+from pm4py.util import constants, xes_constants, exec_utils
+
+
+class Parameters(Enum):
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ COMPUTE_EXTRA_TEMPORAL_FEATURES = "compute_extra_temporal_features"
+
+
+def _drop_if_present(lf: pl.LazyFrame, cols: Iterable[str]) -> pl.LazyFrame:
+ """Drop columns from a LazyFrame if they exist (schema-aware)."""
+ existing: Set[str] = set(lf.collect_schema().names())
+ to_drop = [c for c in cols if c in existing]
+ return lf.drop(to_drop) if to_drop else lf
+
+
+def _prepare_case_features(
+ df: pl.LazyFrame,
+ case_id_key: str,
+ start_timestamp_key: str,
+ timestamp_key: str,
+ compute_extra_temporal_features: bool,
+) -> pl.LazyFrame:
+ """Compute per-case aggregates needed for feature enrichment."""
+
+ # Use more specific internal names to minimize collisions with user columns.
+ case_start_col = "__pm4py_case_start"
+ case_end_col = "__pm4py_case_end"
+
+ case_summary = df.group_by(case_id_key).agg(
+ [
+ pl.col(start_timestamp_key).first().alias(case_start_col),
+ pl.col(timestamp_key).last().alias(case_end_col),
+ ]
+ )
+
+ case_summary = case_summary.with_columns(
+ (
+ (
+ pl.col(case_end_col).dt.timestamp("ns")
+ - pl.col(case_start_col).dt.timestamp("ns")
+ )
+ / 1_000_000_000
+ ).alias("@@case_throughput")
+ )
+
+ if compute_extra_temporal_features:
+ case_summary = case_summary.with_columns(
+ [
+ pl.col(case_start_col).dt.strftime("%Y").alias("@@case_start_year"),
+ pl.col(case_start_col).dt.strftime("%Y-%m").alias("@@case_start_ymonth"),
+ pl.concat_str(pl.lit("M"), pl.col(case_start_col).dt.strftime("%m")).alias(
+ "@@case_start_month"
+ ),
+ pl.concat_str(
+ pl.lit("W"),
+ pl.col(case_start_col)
+ .dt.week()
+ .cast(pl.Utf8)
+ .str.pad_start(2, "0"),
+ ).alias("@@case_start_week"),
+ pl.col(case_end_col).dt.strftime("%Y").alias("@@case_end_year"),
+ pl.col(case_end_col).dt.strftime("%Y-%m").alias("@@case_end_ymonth"),
+ pl.concat_str(pl.lit("M"), pl.col(case_end_col).dt.strftime("%m")).alias(
+ "@@case_end_month"
+ ),
+ pl.concat_str(
+ pl.lit("W"),
+ pl.col(case_end_col)
+ .dt.week()
+ .cast(pl.Utf8)
+ .str.pad_start(2, "0"),
+ ).alias("@@case_end_week"),
+ ]
+ )
+
+ select_columns: List[pl.Expr] = [pl.col(case_id_key), pl.col("@@case_throughput")]
+
+ if compute_extra_temporal_features:
+ select_columns.extend(
+ [
+ pl.col("@@case_start_year"),
+ pl.col("@@case_start_ymonth"),
+ pl.col("@@case_start_month"),
+ pl.col("@@case_start_week"),
+ pl.col("@@case_end_year"),
+ pl.col("@@case_end_ymonth"),
+ pl.col("@@case_end_month"),
+ pl.col("@@case_end_week"),
+ ]
+ )
+
+ return case_summary.select(select_columns)
+
+
+def compute_extra_columns(
+ dataframe: pl.LazyFrame,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> pl.LazyFrame:
+ """Enrich a Polars LazyFrame with additional case-level columns."""
+
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ start_timestamp_key = exec_utils.get_param_value(
+ Parameters.START_TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ compute_extra_temporal_features = exec_utils.get_param_value(
+ Parameters.COMPUTE_EXTRA_TEMPORAL_FEATURES, parameters, True
+ )
+
+ # Drop any previously-added enrichment columns to avoid duplicated columns
+ # (including join-suffix leftovers from older versions).
+ all_enrichment_columns = [
+ "@@count",
+ "@@case_throughput",
+ "@@case_start_year",
+ "@@case_start_ymonth",
+ "@@case_start_month",
+ "@@case_start_week",
+ "@@case_end_year",
+ "@@case_end_ymonth",
+ "@@case_end_month",
+ "@@case_end_week",
+ ]
+ drop_candidates = list(all_enrichment_columns) + [
+ f"{c}_right" for c in all_enrichment_columns
+ ]
+ dataframe = _drop_if_present(dataframe, drop_candidates)
+
+ df = dataframe.with_columns(pl.lit(1).alias("@@count"))
+
+ case_features = _prepare_case_features(
+ df,
+ case_id_key,
+ start_timestamp_key,
+ timestamp_key,
+ compute_extra_temporal_features,
+ )
+
+ enriched = df.join(case_features, on=case_id_key, how="left", coalesce=True, maintain_order="left")
+ return enriched
+
+
+__all__ = ["Parameters", "compute_extra_columns"]
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pl_lazy_fea_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pl_lazy_fea_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e421b4652237b45d17bd37bb7db3eb7a98f5e68c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/pl_lazy_fea_utils.py
@@ -0,0 +1,674 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any, List, Set, Iterable, Collection
+
+import polars as pl
+
+from pm4py.objects.log.util.dataframe_utils import Parameters
+from pm4py.util import constants, exec_utils, pandas_utils
+from pm4py.util import xes_constants
+
+
+def _dedupe_preserve_order(values: Iterable[str]) -> List[str]:
+ seen: Set[str] = set()
+ out: List[str] = []
+ for v in values:
+ if v not in seen:
+ seen.add(v)
+ out.append(v)
+ return out
+
+
+def _sanitize_feature_name(
+ prefix: str, value: Any, used_names: Optional[Set[str]] = None
+) -> str:
+ sanitized = str(value).encode("ascii", errors="ignore").decode("ascii")
+ if not sanitized:
+ sanitized = "value"
+ base_name = f"{prefix}_{sanitized}"
+
+ if used_names is None:
+ return base_name
+
+ candidate = base_name
+ suffix = 1
+ while candidate in used_names:
+ candidate = f"{base_name}__{suffix}"
+ suffix += 1
+ used_names.add(candidate)
+ return candidate
+
+
+_DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS = (
+ "last",
+ "first",
+ "min",
+ "max",
+ "mean",
+ "median",
+ "stdev",
+ "sum",
+)
+
+_NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES = {
+ "last": "LAST",
+ "first": "FIRST",
+ "min": "MIN",
+ "max": "MAX",
+ "mean": "MEAN",
+ "median": "MEDIAN",
+ "stdev": "STDEV",
+ "sum": "SUM",
+}
+
+_NUMERIC_ATTRIBUTE_AGGREGATION_ALIASES = {
+ "std": "stdev",
+ "standard_deviation": "stdev",
+}
+
+
+def _is_internal_attribute(column: str) -> bool:
+ return str(column).startswith("@@")
+
+
+def _normalize_numeric_attribute_aggregations(
+ aggregations: Optional[Collection[str]],
+) -> List[str]:
+ if aggregations is None:
+ values = list(_DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS)
+ elif isinstance(aggregations, str):
+ values = [aggregations]
+ else:
+ values = list(aggregations)
+
+ normalized = []
+ seen = set()
+ for value in values:
+ aggregation = str(value).lower()
+ aggregation = _NUMERIC_ATTRIBUTE_AGGREGATION_ALIASES.get(
+ aggregation, aggregation
+ )
+ if aggregation not in _NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES:
+ supported = ", ".join(_DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS)
+ raise ValueError(
+ f"Unsupported numeric attribute aggregation: {value}. "
+ f"Supported values are: {supported}."
+ )
+ if aggregation not in seen:
+ normalized.append(aggregation)
+ seen.add(aggregation)
+
+ if isinstance(aggregations, (set, frozenset)):
+ normalized_set = set(normalized)
+ normalized = [
+ aggregation
+ for aggregation in _DEFAULT_NUMERIC_ATTRIBUTE_AGGREGATIONS
+ if aggregation in normalized_set
+ ]
+
+ return normalized
+
+
+def _get_numeric_feature_columns(
+ numeric_columns: List[str],
+ enable_numeric_attribute_statistics: bool,
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
+) -> List[str]:
+ if (
+ not enable_numeric_attribute_statistics
+ and numeric_attribute_aggregations is None
+ ):
+ return numeric_columns
+ numeric_attribute_aggregations = _normalize_numeric_attribute_aggregations(
+ numeric_attribute_aggregations
+ )
+ feature_columns = []
+ for col in numeric_columns:
+ if _is_internal_attribute(col):
+ feature_columns.append(col)
+ else:
+ feature_columns.extend(
+ f"{col}_{_NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES[aggregation]}"
+ for aggregation in numeric_attribute_aggregations
+ )
+ return feature_columns
+
+
+def _scalar_from_lazy(lf: pl.LazyFrame, expr: pl.Expr) -> Any:
+ result = lf.select(expr.alias("__scalar")).collect()
+ if result.height == 0 or result.width == 0:
+ return None
+ return result.to_series(0)[0]
+
+
+def _lazy_schema(lf: pl.LazyFrame) -> pl.Schema:
+ return lf.collect_schema()
+
+
+def _lazy_columns(lf: pl.LazyFrame) -> List[str]:
+ return _lazy_schema(lf).names()
+
+
+def _drop_if_present(lf: pl.LazyFrame, cols: Iterable[str]) -> pl.LazyFrame:
+ existing = set(_lazy_columns(lf))
+ to_drop = [c for c in cols if c in existing]
+ return lf.drop(to_drop) if to_drop else lf
+
+
+def _unique_internal_name(existing: Set[str], base: str) -> str:
+ if base not in existing:
+ return base
+ i = 1
+ while f"{base}__{i}" in existing:
+ i += 1
+ return f"{base}__{i}"
+
+
+def _is_numeric_dtype(dtype: pl.DataType) -> bool:
+ dtype_str = str(dtype).lower()
+ if any(token in dtype_str for token in ("int", "uint", "float")):
+ return True
+ if dtype_str.startswith("decimal"):
+ return True
+ if dtype_str.startswith("duration"):
+ return True
+ if dtype_str == "boolean":
+ return True
+ return False
+
+
+def _is_string_dtype(dtype: pl.DataType) -> bool:
+ dtype_str = str(dtype).lower()
+ return dtype_str in {"utf8", "string"} or dtype_str.startswith("categorical")
+
+
+def _numeric_feature_dtype(dtype: pl.DataType) -> pl.DataType:
+ if dtype == pl.Boolean:
+ return pl.UInt8
+ if dtype in {
+ pl.Int8,
+ pl.Int16,
+ pl.Int32,
+ pl.UInt8,
+ pl.UInt16,
+ pl.UInt32,
+ pl.Float32,
+ }:
+ return dtype
+
+ dtype_str = str(dtype).lower()
+ if dtype in {pl.Int64, pl.UInt64, pl.Float64}:
+ return pl.Float32
+ if dtype_str.startswith("decimal") or dtype_str.startswith("duration"):
+ return pl.Float32
+
+ return pl.Float32
+
+
+def _unsigned_count_dtype(max_value: int) -> pl.DataType:
+ if max_value <= 0xFF:
+ return pl.UInt8
+ if max_value <= 0xFFFF:
+ return pl.UInt16
+ if max_value <= 0xFFFFFFFF:
+ return pl.UInt32
+ return pl.UInt64
+
+
+def _max_case_length(df: pl.LazyFrame, case_id_key: str) -> int:
+ max_case_length = _scalar_from_lazy(
+ df.group_by(case_id_key).agg(pl.len().alias("__case_size")),
+ pl.col("__case_size").max(),
+ )
+ return int(max_case_length or 0)
+
+
+def automatic_feature_selection_df(
+ df: pl.LazyFrame, parameters: Optional[Dict[Any, Any]] = None
+) -> pl.LazyFrame:
+ """Selects useful features from a Polars lazyframe for ML purposes."""
+ if parameters is None:
+ parameters = {}
+
+ schema = _lazy_schema(df)
+ available_columns = set(schema.names())
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+
+ default_mandatory = available_columns.intersection(
+ {case_id_key, activity_key, timestamp_key}
+ )
+ mandatory_attributes = exec_utils.get_param_value(
+ Parameters.MANDATORY_ATTRIBUTES,
+ parameters,
+ default_mandatory,
+ )
+ mandatory_set = set(mandatory_attributes)
+
+ min_different_occ_str_attr = exec_utils.get_param_value(
+ Parameters.MIN_DIFFERENT_OCC_STR_ATTR, parameters, 5
+ )
+ max_different_occ_str_attr = exec_utils.get_param_value(
+ Parameters.MAX_DIFFERENT_OCC_STR_ATTR, parameters, 50
+ )
+ consider_all_attributes = exec_utils.get_param_value(
+ Parameters.CONSIDER_ALL_ATTRIBUTES, parameters, True
+ )
+
+ other_attributes_to_retain = set()
+
+ total_cases = _scalar_from_lazy(df, pl.col(case_id_key).n_unique())
+ total_cases = int(total_cases or 0)
+
+ for col, dtype in schema.items():
+ if col == case_id_key:
+ continue
+
+ cases_with_value = _scalar_from_lazy(
+ df.filter(pl.col(col).is_not_null()),
+ pl.col(case_id_key).n_unique(),
+ )
+ cases_with_value = int(cases_with_value or 0)
+
+ if cases_with_value != total_cases and not consider_all_attributes:
+ continue
+
+ if _is_numeric_dtype(dtype):
+ other_attributes_to_retain.add(col)
+ elif _is_string_dtype(dtype):
+ unique_val_count = _scalar_from_lazy(
+ df.filter(pl.col(col).is_not_null()),
+ pl.col(col).n_unique(),
+ )
+ unique_val_count = int(unique_val_count or 0)
+ if (
+ min_different_occ_str_attr
+ <= unique_val_count
+ <= max_different_occ_str_attr
+ ):
+ other_attributes_to_retain.add(col)
+
+ attributes_to_retain = mandatory_set.union(other_attributes_to_retain)
+ selected_columns = [
+ col_name for col_name in schema.names() if col_name in attributes_to_retain
+ ]
+
+ return df.select(selected_columns)
+
+
+def select_number_column(
+ df: pl.LazyFrame,
+ fea_df: pl.LazyFrame,
+ col: str,
+ case_id_key: str = constants.CASE_CONCEPT_NAME,
+ enable_numeric_attribute_statistics: bool = False,
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
+) -> pl.LazyFrame:
+ """Adds a numeric column to the feature lazyframe."""
+ return select_number_columns(
+ df,
+ fea_df,
+ [col],
+ case_id_key=case_id_key,
+ enable_numeric_attribute_statistics=enable_numeric_attribute_statistics,
+ numeric_attribute_aggregations=numeric_attribute_aggregations,
+ )
+
+
+def select_number_columns(
+ df: pl.LazyFrame,
+ fea_df: pl.LazyFrame,
+ columns: List[str],
+ case_id_key: str = constants.CASE_CONCEPT_NAME,
+ enable_numeric_attribute_statistics: bool = False,
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
+) -> pl.LazyFrame:
+ """Adds numeric columns to the feature lazyframe in a single grouped pass."""
+ if not columns:
+ return fea_df
+
+ df_schema = _lazy_schema(df)
+ available = set(df_schema.names())
+
+ clean_columns = [
+ c
+ for c in _dedupe_preserve_order(columns)
+ if c != case_id_key and c in available and _is_numeric_dtype(df_schema[c])
+ ]
+ if not clean_columns:
+ return fea_df
+
+ df_cols = set(_lazy_columns(df))
+ row_nr_col = _unique_internal_name(df_cols, "__row_nr")
+
+ cols_to_drop: Set[str] = set()
+ agg_exprs: List[pl.Expr] = []
+
+ compute_statistics = (
+ enable_numeric_attribute_statistics
+ or numeric_attribute_aggregations is not None
+ )
+ if compute_statistics:
+ numeric_attribute_aggregations = _normalize_numeric_attribute_aggregations(
+ numeric_attribute_aggregations
+ )
+
+ for col in clean_columns:
+ feature_columns = _get_numeric_feature_columns(
+ [col],
+ enable_numeric_attribute_statistics,
+ numeric_attribute_aggregations,
+ )
+ cols_to_drop.update([col, f"{col}_right"])
+ for feature_col in feature_columns:
+ cols_to_drop.update([feature_col, f"{feature_col}_right"])
+
+ feature_dtype = _numeric_feature_dtype(df_schema[col])
+ ordered_values = pl.col(col).sort_by(pl.col(row_nr_col)).drop_nulls()
+
+ if compute_statistics and not _is_internal_attribute(col):
+ float_values = pl.col(col).cast(pl.Float64)
+ aggregation_exprs = {
+ "last": ordered_values.last().cast(feature_dtype),
+ "first": ordered_values.first().cast(feature_dtype),
+ "min": pl.col(col).min().cast(feature_dtype),
+ "max": pl.col(col).max().cast(feature_dtype),
+ "mean": float_values.mean().cast(pl.Float32),
+ "median": float_values.median().cast(pl.Float32),
+ "stdev": float_values.std(ddof=0).cast(pl.Float32),
+ "sum": (
+ pl.when(pl.col(col).is_not_null().sum() > 0)
+ .then(float_values.sum())
+ .otherwise(None)
+ .cast(pl.Float32)
+ ),
+ }
+ for aggregation in numeric_attribute_aggregations:
+ suffix = _NUMERIC_ATTRIBUTE_AGGREGATION_SUFFIXES[aggregation]
+ agg_exprs.append(
+ aggregation_exprs[aggregation].alias(f"{col}_{suffix}")
+ )
+ else:
+ agg_exprs.append(
+ ordered_values.last().cast(feature_dtype).alias(col)
+ )
+
+ fea_df = _drop_if_present(fea_df, cols_to_drop)
+ if not agg_exprs:
+ return fea_df
+
+ df_numeric = (
+ df.with_row_index(row_nr_col)
+ .select([pl.col(case_id_key), pl.col(row_nr_col)] + [pl.col(c) for c in clean_columns])
+ .group_by(case_id_key)
+ .agg(agg_exprs)
+ )
+
+ return fea_df.join(df_numeric, on=case_id_key, how="left", coalesce=True, maintain_order="left")
+
+
+def _collect_categorical_values(
+ df: pl.LazyFrame, columns: List[str]
+) -> Dict[str, List[Any]]:
+ """Collects formatted unique values for the provided categorical columns."""
+ collected: Dict[str, List[Any]] = {}
+ for col in columns:
+ unique_values = (
+ df.select(pl.col(col))
+ .drop_nulls(subset=[col])
+ .unique()
+ .collect()
+ .get_column(col)
+ .to_list()
+ )
+ formatted = [
+ value
+ for value in pandas_utils.format_unique(unique_values)
+ if value is not None
+ ]
+ if formatted:
+ collected[col] = formatted
+
+ return collected
+
+
+def _select_string_columns(
+ df: pl.LazyFrame,
+ fea_df: pl.LazyFrame,
+ columns: List[str],
+ case_id_key: str,
+ count_occurrences: bool,
+) -> pl.LazyFrame:
+ """Adds one-hot or count encoded columns for the provided categorical attributes.
+
+ This function is designed to be idempotent: running it multiple times with the same
+ inputs will overwrite/recompute the same generated feature columns instead of
+ creating suffixed duplicates (e.g., `...__1`, `..._right`).
+ """
+ if not columns:
+ return fea_df
+
+ df_schema = _lazy_schema(df)
+ available = set(df_schema.names())
+
+ clean_columns = [
+ c
+ for c in _dedupe_preserve_order(columns)
+ if c != case_id_key and c in available
+ ]
+ if not clean_columns:
+ return fea_df
+
+ unique_values_map = _collect_categorical_values(df, clean_columns)
+ if not unique_values_map:
+ return fea_df
+
+ existing_cols: Set[str] = set(_lazy_columns(fea_df))
+ used_names: Set[str] = set(existing_cols)
+
+ agg_exprs: List[pl.Expr] = []
+ cols_to_drop: Set[str] = set()
+ feature_dtype = (
+ _unsigned_count_dtype(_max_case_length(df, case_id_key))
+ if count_occurrences
+ else pl.UInt8
+ )
+
+ for column, unique_values in unique_values_map.items():
+ for value in unique_values:
+ # Deterministic base name (no dependency on existing columns).
+ base_name = _sanitize_feature_name(column, value)
+
+ # If the feature column already exists, we recompute it (drop first),
+ # avoiding `*_right` duplicates from joins.
+ if base_name in existing_cols:
+ cols_to_drop.add(base_name)
+ used_names.discard(base_name)
+ if f"{base_name}_right" in existing_cols:
+ cols_to_drop.add(f"{base_name}_right")
+ used_names.discard(f"{base_name}_right")
+
+ # Ensure uniqueness against the remaining schema + other new features.
+ column_name = base_name
+ suffix = 1
+ while column_name in used_names:
+ column_name = f"{base_name}__{suffix}"
+ suffix += 1
+ used_names.add(column_name)
+
+ comparison = pl.col(column).eq(value)
+ if count_occurrences:
+ agg_exprs.append(
+ comparison.cast(pl.UInt8).sum().cast(feature_dtype).alias(column_name)
+ )
+ else:
+ agg_exprs.append(
+ comparison.cast(feature_dtype).max().cast(feature_dtype).alias(column_name)
+ )
+
+ if cols_to_drop:
+ fea_df = _drop_if_present(fea_df, cols_to_drop)
+
+ feature_chunk = (
+ df.select([pl.col(case_id_key)] + [pl.col(c) for c in unique_values_map.keys()])
+ .group_by(case_id_key)
+ .agg(agg_exprs)
+ )
+
+ return fea_df.join(feature_chunk, on=case_id_key, how="left", coalesce=True, maintain_order="left")
+
+
+def select_string_column(
+ df: pl.LazyFrame,
+ fea_df: pl.LazyFrame,
+ col: str,
+ case_id_key: str = constants.CASE_CONCEPT_NAME,
+ count_occurrences: bool = False,
+) -> pl.LazyFrame:
+ """Adds one-hot or count encoded columns for a categorical attribute."""
+ return _select_string_columns(
+ df,
+ fea_df,
+ [col],
+ case_id_key=case_id_key,
+ count_occurrences=count_occurrences,
+ )
+
+
+def select_string_columns(
+ df: pl.LazyFrame,
+ fea_df: pl.LazyFrame,
+ columns: List[str],
+ case_id_key: str = constants.CASE_CONCEPT_NAME,
+ count_occurrences: bool = False,
+) -> pl.LazyFrame:
+ """Adds one-hot or count encoded columns for the provided categorical attributes."""
+ return _select_string_columns(
+ df,
+ fea_df,
+ columns,
+ case_id_key=case_id_key,
+ count_occurrences=count_occurrences,
+ )
+
+
+def get_features_df(
+ df: pl.LazyFrame,
+ list_columns: List[str],
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> pl.LazyFrame:
+ """Performs automatic feature extraction on a Polars LazyFrame."""
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ add_case_identifier_column = exec_utils.get_param_value(
+ Parameters.ADD_CASE_IDENTIFIER_COLUMN, parameters, False
+ )
+ count_occurrences = exec_utils.get_param_value(
+ Parameters.COUNT_OCCURRENCES, parameters, False
+ )
+ enable_numeric_attribute_statistics = exec_utils.get_param_value(
+ Parameters.ENABLE_NUMERIC_ATTRIBUTE_STATISTICS, parameters, False
+ )
+ numeric_attribute_aggregations = exec_utils.get_param_value(
+ Parameters.NUMERIC_ATTRIBUTE_AGGREGATIONS, parameters, None
+ )
+
+ # Avoid duplicate work and join-induced `*_right` columns when the
+ # input list contains duplicates.
+ list_columns = _dedupe_preserve_order(list_columns)
+
+ fea_df = df.select(pl.col(case_id_key)).unique().sort(case_id_key, maintain_order=True)
+
+ schema = _lazy_schema(df)
+ numeric_columns: List[str] = []
+ string_columns: List[str] = []
+
+ for col in list_columns:
+ if col == case_id_key or col not in schema:
+ continue
+ dtype = schema[col]
+ if _is_numeric_dtype(dtype):
+ numeric_columns.append(col)
+ elif _is_string_dtype(dtype):
+ string_columns.append(col)
+
+ fea_df = select_number_columns(
+ df,
+ fea_df,
+ numeric_columns,
+ case_id_key=case_id_key,
+ enable_numeric_attribute_statistics=enable_numeric_attribute_statistics,
+ numeric_attribute_aggregations=numeric_attribute_aggregations,
+ )
+
+ fea_df = select_string_columns(
+ df,
+ fea_df,
+ string_columns,
+ case_id_key=case_id_key,
+ count_occurrences=count_occurrences,
+ )
+
+ fea_df = fea_df.sort(case_id_key, maintain_order=True)
+ if not add_case_identifier_column:
+ fea_df = fea_df.drop(case_id_key)
+
+ return fea_df
+
+
+def automatic_feature_extraction_df(
+ df: pl.LazyFrame, parameters: Optional[Dict[Any, Any]] = None
+) -> pl.LazyFrame:
+ """Wrapper that performs automatic feature extraction on a Polars lazyframe."""
+ if parameters is None:
+ parameters = {}
+
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+
+ fea_sel_df = automatic_feature_selection_df(df, parameters=parameters)
+ columns = set(_lazy_columns(fea_sel_df))
+
+ columns.discard(case_id_key)
+ columns.discard(timestamp_key)
+
+ return get_features_df(fea_sel_df, list(columns), parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/sampling.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a9fef7a444b97e5ee5424f4eccaf1c2d0e915e9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/sampling.py
@@ -0,0 +1,100 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import random
+
+from pm4py.objects.log.obj import EventStream, EventLog
+
+
+def sample_stream(event_log, no_events=100):
+ """
+ Randomly sample a fixed number of events from the original event log
+
+ Parameters
+ -----------
+ event_log
+ Event log
+ no_events
+ Number of events that the sample should have
+
+ Returns
+ -----------
+ newLog
+ Filtered log
+ """
+ new_log = EventStream(
+ attributes=event_log.attributes,
+ extensions=event_log.extensions,
+ globals=event_log.omni_present,
+ classifiers=event_log.classifiers,
+ )
+ new_log._list = random.sample(event_log, min(no_events, len(event_log)))
+ return new_log
+
+
+def sample_log(log, no_traces=100):
+ """
+ Randomly sample a fixed number of traces from the original log
+
+ Parameters
+ -----------
+ log
+ Log
+ no_traces
+ Number of traces that the sample should have
+
+ Returns
+ -----------
+ newLog
+ Filtered log
+ """
+ new_log = EventLog(
+ attributes=log.attributes,
+ extensions=log.extensions,
+ globals=log.omni_present,
+ classifiers=log.classifiers,
+ properties=log.properties,
+ )
+ new_log._list = random.sample(log, min(no_traces, len(log)))
+ return new_log
+
+
+def sample(log, n=100):
+ """
+ Randomly sample a fixed number of traces from the original log
+
+ Parameters
+ -----------
+ log
+ Trace/event log
+ n
+ Number of elements that the sample should have
+
+ Returns
+ -----------
+ newLog
+ Filtered log
+ """
+
+ if type(log) is EventLog:
+ return sample_log(log, no_traces=n)
+
+ return sample_stream(log, no_events=n)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/sorting.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/sorting.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cfc5d0534686b176f64f5c37a4fe6b04e001db9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/sorting.py
@@ -0,0 +1,248 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog, Trace, EventStream
+from pm4py.util import xes_constants as xes
+from pm4py.objects.conversion.log import converter as log_converter
+
+
+def sort_timestamp_trace(
+ trace, timestamp_key=xes.DEFAULT_TIMESTAMP_KEY, reverse_sort=False
+):
+ """
+ Sort a trace based on timestamp key
+
+ Parameters
+ -----------
+ trace
+ Trace
+ timestamp_key
+ Timestamp key
+ reverse_sort
+ If true, reverses the direction in which the sort is done (ascending)
+
+ Returns
+ -----------
+ trace
+ Sorted trace
+ """
+ events = sorted(
+ trace._list, key=lambda x: x[timestamp_key], reverse=reverse_sort
+ )
+ new_trace = Trace(events, attributes=trace.attributes)
+ return new_trace
+
+
+def sort_timestamp_stream(
+ event_log, timestamp_key=xes.DEFAULT_TIMESTAMP_KEY, reverse_sort=False
+):
+ """
+ Sort an event log based on timestamp key
+
+ Parameters
+ -----------
+ event_log
+ Event log
+ timestamp_key
+ Timestamp key
+ reverse_sort
+ If true, reverses the direction in which the sort is done (ascending)
+
+ Returns
+ -----------
+ event_log
+ Sorted event log
+ """
+ events = sorted(
+ event_log._list, key=lambda x: x[timestamp_key], reverse=reverse_sort
+ )
+ new_stream = EventStream(
+ events,
+ attributes=event_log.attributes,
+ extensions=event_log.extensions,
+ omni_present=event_log.omni_present,
+ classifiers=event_log.classifiers,
+ properties=event_log.properties,
+ )
+ return new_stream
+
+
+def sort_timestamp_log(
+ event_log, timestamp_key=xes.DEFAULT_TIMESTAMP_KEY, reverse_sort=False
+):
+ """
+ Sort a log based on timestamp key
+
+ Parameters
+ -----------
+ event_log
+ Log
+ timestamp_key
+ Timestamp key
+ reverse_sort
+ If true, reverses the direction in which the sort is done (ascending)
+
+ Returns
+ -----------
+ log
+ Sorted log
+ """
+ event_log = log_converter.apply(
+ event_log, variant=log_converter.Variants.TO_EVENT_LOG
+ )
+
+ new_log = EventLog(
+ attributes=event_log.attributes,
+ extensions=event_log.extensions,
+ omni_present=event_log.omni_present,
+ classifiers=event_log.classifiers,
+ properties=event_log.properties,
+ )
+ for trace in event_log:
+ if trace:
+ new_log.append(
+ sort_timestamp_trace(
+ trace,
+ timestamp_key=timestamp_key,
+ reverse_sort=reverse_sort,
+ )
+ )
+ new_log._list.sort(key=lambda x: x[0][timestamp_key], reverse=reverse_sort)
+
+ return new_log
+
+
+def sort_timestamp(
+ log, timestamp_key=xes.DEFAULT_TIMESTAMP_KEY, reverse_sort=False
+):
+ """
+ Sort a log based on timestamp key
+
+ Parameters
+ -----------
+ log
+ Trace/Event log
+ timestamp_key
+ Timestamp key
+ reverse_sort
+ If true, reverses the direction in which the sort is done (ascending)
+
+ Returns
+ -----------
+ log
+ Sorted Trace/Event log
+ """
+ if type(log) is EventLog:
+ return sort_timestamp_log(
+ log, timestamp_key=timestamp_key, reverse_sort=reverse_sort
+ )
+ return sort_timestamp_stream(
+ log, timestamp_key=timestamp_key, reverse_sort=reverse_sort
+ )
+
+
+def sort_lambda_log(event_log, sort_function, reverse=False):
+ """
+ Sort a log based on a lambda expression
+
+ Parameters
+ ------------
+ event_log
+ Log
+ sort_function
+ Sort function
+ reverse
+ Boolean (sort by reverse order)
+
+ Returns
+ ------------
+ new_log
+ Sorted log
+ """
+ event_log = log_converter.apply(
+ event_log, variant=log_converter.Variants.TO_EVENT_LOG
+ )
+
+ traces = sorted(event_log._list, key=sort_function, reverse=reverse)
+ new_log = EventLog(
+ traces,
+ attributes=event_log.attributes,
+ extensions=event_log.extensions,
+ omni_present=event_log.omni_present,
+ classifiers=event_log.classifiers,
+ properties=event_log.properties,
+ )
+
+ return new_log
+
+
+def sort_lambda_stream(event_log, sort_function, reverse=False):
+ """
+ Sort a stream based on a lambda expression
+
+ Parameters
+ ------------
+ event_log
+ Stream
+ sort_function
+ Sort function
+ reverse
+ Boolean (sort by reverse order)
+
+ Returns
+ ------------
+ stream
+ Sorted stream
+ """
+ events = sorted(event_log._list, key=sort_function, reverse=reverse)
+ new_stream = EventStream(
+ events,
+ attributes=event_log.attributes,
+ extensions=event_log.extensions,
+ omni_present=event_log.omni_present,
+ classifiers=event_log.classifiers,
+ properties=event_log.properties,
+ )
+
+ return new_stream
+
+
+def sort_lambda(log, sort_function, reverse=False):
+ """
+ Sort a log based on lambda expression
+
+ Parameters
+ -------------
+ log
+ Log
+ sort_function
+ Sort function
+ reverse
+ Boolean (sort by reverse order)
+
+ Returns
+ -------------
+ log
+ Sorted log
+ """
+ if type(log) is EventLog:
+ return sort_lambda_log(log, sort_function, reverse=reverse)
+ return sort_lambda_stream(log, sort_function, reverse=reverse)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/split_train_test.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/split_train_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec702f273d70e8b820159c565e8e722159d369d2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/split_train_test.py
@@ -0,0 +1,73 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.log.obj import EventLog
+from typing import Tuple
+import random
+import math
+
+
+def split(
+ log: EventLog, train_percentage: float = 0.8
+) -> Tuple[EventLog, EventLog]:
+ """
+ Split an event log in a training log and a test log (for machine learning purposes)
+
+ Parameters
+ --------------
+ log
+ Event log
+ train_percentage
+ Fraction of traces to be included in the training log (from 0.0 to 1.0)
+
+ Returns
+ --------------
+ training_log
+ Training event log
+ test_log
+ Test event log
+ """
+ idxs = [i for i in range(len(log))]
+ random.shuffle(idxs)
+ stop_idx = math.floor(len(idxs) * train_percentage) + 1
+ idxs_train = idxs[:stop_idx]
+ idxs_test = idxs[stop_idx:]
+ train_log = EventLog(
+ list(),
+ attributes=log.attributes,
+ extensions=log.extensions,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ properties=log.properties,
+ )
+ test_log = EventLog(
+ list(),
+ attributes=log.attributes,
+ extensions=log.extensions,
+ classifiers=log.classifiers,
+ omni_present=log.omni_present,
+ properties=log.properties,
+ )
+ for idx in idxs_train:
+ train_log.append(log[idx])
+ for idx in idxs_test:
+ test_log.append(log[idx])
+ return train_log, test_log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/xes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/xes.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c0e8ed6e17ec8ec924ef08229b62d43bbbe4a07
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/log/util/xes.py
@@ -0,0 +1,60 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+# XES TAGS
+TAG_BOOLEAN = "boolean"
+TAG_CLASSIFIER = "classifier"
+TAG_DATE = "date"
+TAG_EVENT = "event"
+TAG_EXTENSION = "extension"
+TAG_FLOAT = "float"
+TAG_GLOBAL = "global"
+TAG_ID = "id"
+TAG_INT = "int"
+TAG_LIST = "list"
+TAG_LOG = "log"
+TAG_STRING = "string"
+TAG_TRACE = "trace"
+TAG_VALUES = "values"
+TAG_VERSION = "xes.version"
+TAG_FEATURES = "xes.features"
+TAG_XMLNS = "xmlns"
+
+# XES/INTERNAL KEYS
+KEY_CHILDREN = "children"
+KEY_KEY = "key"
+KEY_KEYS = "keys"
+KEY_NAME = "name"
+KEY_PREFIX = "prefix"
+KEY_SCOPE = "scope"
+KEY_URI = "uri"
+KEY_VALUE = "value"
+
+DEFAULT_NAME_KEY = "concept:name"
+DEFAULT_TIMESTAMP_KEY = "time:timestamp"
+DEFAULT_START_TIMESTAMP_KEY = "start_timestamp"
+DEFAULT_TRACEID_KEY = "concept:name"
+DEFAULT_RESOURCE_KEY = "org:resource"
+DEFAULT_TRANSITION_KEY = "lifecycle:transition"
+
+VALUE_XES_VERSION = "1849-2016"
+VALUE_XES_FEATURES = "nested-attributes"
+VALUE_XMLNS = "http://www.xes-standard.org/"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..86e8e563e485de7554adfbacee156fca8098b37f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.oc_causal_net import obj, converter, semantics, creation, utils
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..d09d17aa8d4fd8dded3e3060a781d8c11886f3da
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/converter.py
@@ -0,0 +1,48 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.oc_causal_net.variants import to_ocpn
+from pm4py.util import exec_utils
+from enum import Enum
+
+class Variants(Enum):
+ TO_OCPN = to_ocpn
+
+def apply(oc_causal_net, parameters=None, variant=Variants.TO_OCPN):
+ """
+ Method for converting from Object-centric Causal Net Object-centric Petri Net
+
+ Parameters
+ -----------
+ oc_causal_net
+ Object-centric Causal net
+ parameters
+ Parameters of the algorithm
+ variant
+ Chosen variant of the algorithm:
+ - Variants.TO_OCPN
+
+ Returns
+ -----------
+ OCPetriNet
+ Object-centric Petri net converted from the Object-centric Causal Net
+ """
+ return exec_utils.get_variant(variant).apply(oc_causal_net, parameters=parameters)
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/creation/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/creation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..70602d2fc35ecc4ff0231093bf1c4bf7e41277c0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/creation/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.oc_causal_net.creation import factory
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/creation/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/creation/factory.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5f0e6891c0554a40ac2eae5ea5b03555c31fc21
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/creation/factory.py
@@ -0,0 +1,157 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.oc_causal_net.obj import OCCausalNet
+import networkx as nx
+
+
+def create_oc_causal_net(marker_groups):
+ """
+ Create an object-centric causal net from a list of marker groups.
+ Does not consider activity counts or the relative occurrence threshold.
+ May mutate the input data.
+
+ Parameters
+ ----------
+ marker_groups : dict[str, ]
+ Dict of marker groups per activity. Syntax::
+
+ {
+ "activity_name": {
+ "img": [
+ [
+ (activity, object_type, (min_count, max_count), marker_key),
+ // -1 for max_count = inf; 0 for unique marker key
+ ...
+ ],
+ ...
+ ],
+ "omg": [
+ ...
+ ]
+ }
+ ]
+ }
+
+ Returns
+ -------
+ OCCausalNet
+ Object-centric causal net
+ """
+ # infer activities
+ activities = set(marker_groups.keys())
+
+ # get input and output marker groups
+ input_marker_groups = {}
+ output_marker_groups = {}
+
+ # make all keys=0 unique
+ # find max key
+ max_key = max(
+ [
+ key
+ for groups in marker_groups.values()
+ for group in groups.get("img", []) + groups.get("omg", [])
+ for _, _, _, key in group
+ ],
+ default=0,
+ )
+ key_counter = max_key + 1
+
+ # give markers with key=0 a unique key and set inf as max count if max count is -1
+ for groups in marker_groups.values():
+ for group in groups.get("img", []) + groups.get("omg", []):
+ for i, (
+ related_activity,
+ object_type,
+ count_range,
+ marker_key,
+ ) in enumerate(group):
+ if marker_key == 0:
+ group[i] = (
+ related_activity,
+ object_type,
+ (
+ count_range
+ if count_range[1] != -1
+ else (count_range[0], float("inf"))
+ ),
+ key_counter,
+ )
+ key_counter += 1
+ key_counter = max_key + 1
+
+ for activity, groups in marker_groups.items():
+ img = groups.get("img", [])
+ omg = groups.get("omg", [])
+
+ if img:
+ input_marker_groups[activity] = [
+ OCCausalNet.MarkerGroup(
+ markers=[
+ OCCausalNet.Marker(
+ related_activity, object_type, count_range, marker_key
+ )
+ for related_activity, object_type, count_range, marker_key in group
+ ]
+ )
+ for group in img
+ ]
+ if omg:
+ output_marker_groups[activity] = [
+ OCCausalNet.MarkerGroup(
+ markers=[
+ OCCausalNet.Marker(
+ related_activity, object_type, count_range, marker_key
+ )
+ for related_activity, object_type, count_range, marker_key in group
+ ]
+ )
+ for group in omg
+ ]
+
+ # infer arcs from the marker groups
+ arcs = dict()
+ for activity in activities:
+ for group in output_marker_groups.get(activity, []):
+ for marker in group.markers:
+ related_activity = marker.related_activity
+ object_type = marker.object_type
+ if activity not in arcs:
+ arcs[activity] = {}
+ if related_activity not in arcs[activity]:
+ arcs[activity][related_activity] = {}
+ if object_type not in arcs[activity][related_activity]:
+ arcs[activity][related_activity][object_type] = {}
+ arcs[activity][related_activity][object_type] = {
+ "object_type": object_type
+ }
+ # create the dependency graph
+ dependency_graph = nx.MultiDiGraph(arcs)
+
+ # create the object-centric causal net
+ occn = OCCausalNet(
+ dependency_graph,
+ output_marker_groups,
+ input_marker_groups,
+ )
+ return occn
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..aee4a1df372256252bb029bf646f0b89cb9dfeb0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/obj.py
@@ -0,0 +1,370 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from itertools import combinations
+import networkx as nx
+from pm4py.objects.oc_causal_net.utils.filters import filter4
+from typing import Tuple, List, Dict
+from collections import Counter, defaultdict
+from functools import cached_property
+
+
+class OCCausalNet(object):
+ """
+ Object-Centric Causal Net capturing dependency graph and marker groups.
+ """
+
+ class Marker(object):
+ """
+ Represents a single marker in an object-centric causal net.
+ """
+
+ def __init__(
+ self, related_activity, object_type, count_range: Tuple, marker_key: int
+ ):
+ """
+ Constructor
+
+ Parameters
+ ----------
+ related_activity : str
+ Activity that has to fulfill the marker (predecessor or successor)
+ object_type : str
+ object type of the marker
+ count_range : Tuple
+ Min and max number of markers consumable ('cardinalities')
+ marker_key : int
+ Key of the marker
+ """
+ self.__related_activity = related_activity
+ self.__object_type = object_type
+ self.__count_range = count_range
+ self.__marker_key = marker_key
+
+ def __repr__(self):
+ return f"(a={self.related_activity}, ot={self.object_type}, c={self.count_range}, k={self.marker_key})"
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __hash__(self):
+ return hash(
+ (
+ self.related_activity,
+ self.object_type,
+ self.min_count,
+ self.max_count,
+ self.marker_key,
+ )
+ )
+
+ def __get_related_activity(self):
+ return self.__related_activity
+
+ def __get_object_type(self):
+ return self.__object_type
+
+ def __get_count_range(self):
+ return self.__count_range
+
+ def __get_min_count(self):
+ return self.__count_range[0]
+
+ def __get_max_count(self):
+ return self.__count_range[1]
+
+ def __get_marker_key(self):
+ return self.__marker_key
+
+ def __set_marker_key(self, marker_key: int):
+ self.__marker_key = marker_key
+
+ def __eq__(self, other):
+ if isinstance(other, OCCausalNet.Marker):
+ return (
+ self.related_activity == other.related_activity
+ and self.object_type == other.object_type
+ and self.min_count == other.min_count
+ and self.max_count == other.max_count
+ and self.marker_key == other.marker_key
+ )
+ return False
+
+ related_activity = property(__get_related_activity)
+ object_type = property(__get_object_type)
+ count_range = property(__get_count_range)
+ min_count = property(__get_min_count)
+ max_count = property(__get_max_count)
+ marker_key = property(__get_marker_key, __set_marker_key)
+
+ class MarkerGroup(object):
+ """
+ Represents a group of markers. A group of markers semantically
+ represents the AND gate of all markers in the group.
+ """
+
+ def __init__(
+ self,
+ markers: List["OCCausalNet.Marker"],
+ support_count: int = float("inf"),
+ ):
+ """
+ Constructor
+
+ Parameters
+ ----------
+ markers : List[OCCausalNet.Marker]
+ List of markers that comprise the group
+ support_count : int
+ Frequency of this marker group in the event log. May be used to
+ filter infrequent marker groups.
+ Default is inf.
+ """
+ self.__markers = markers
+ self.__support_count = support_count
+
+ def __repr__(self):
+ return f"({self.markers}, count={self.support_count})"
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __eq__(self, other):
+ if isinstance(other, OCCausalNet.MarkerGroup):
+ return (
+ Counter(self.markers) == Counter(other.markers)
+ and self.support_count == other.support_count
+ )
+ return False
+
+ def __hash__(self):
+ return hash(
+ (
+ frozenset(self.markers),
+ self.support_count,
+ )
+ )
+
+ def __get_markers(self):
+ return self.__markers
+
+ def __get_support_count(self):
+ return self.__support_count
+
+ @cached_property
+ def dict_representation(self):
+ """
+ Returns a dictionary representation of the marker group for
+ efficient checking if the marker group can be bound with a
+ given set of objects per related activity and object type.
+ Is only computed once and cached.
+ Is invalid if the marker group is changed after initialization.
+ Assumes that the marker group is valid, i.e., there is at most one marker per
+ related activity and object type.
+
+ Returns
+ -------
+ defaultdict[str, defaultdict[str, tuple[int, int]]]
+ Dictionary representation of the marker group, mapping
+ related activities to objects types to min and max cardinalities.
+ """
+ result = defaultdict(lambda: defaultdict(lambda: (float("inf"), 0)))
+ for marker in self.markers:
+ related_activity = marker.related_activity
+ object_type = marker.object_type
+ result[related_activity][object_type] = (
+ marker.min_count,
+ marker.max_count if marker.max_count != -1 else float("inf"),
+ )
+ return result
+
+ @cached_property
+ def key_constraints(self):
+ """
+ Returns all tuples (related_activity, object_type, related_activity_2) that
+ cannot share objects due to having the same key.
+ Is only computed once and cached.
+ Is invalid if the marker group is changed after initialization.
+
+ Returns
+ -------
+ List[Tuple[str, str, str]]
+ List of tuples (related_activity, object_type, related_activity_2)
+ that cannot share the same marker key.
+ """
+ # group related activities by (marker_key, object_type)
+ grouped = defaultdict(list)
+ for marker in self.markers:
+ grouped[(marker.marker_key, marker.object_type)].append(
+ marker.related_activity
+ )
+
+ # Generate constraints from groups with >= 2 elements
+ constraints = []
+ for (marker_key, object_type), related_activities in grouped.items():
+ if len(related_activities) > 1:
+ for act1, act2 in combinations(related_activities, 2):
+ constraints.append((act1, object_type, act2))
+
+ return constraints
+
+ markers = property(__get_markers)
+ support_count = property(__get_support_count)
+
+ def __init__(
+ self,
+ dependency_graph: nx.MultiDiGraph,
+ output_marker_groups: Dict[str, List["OCCausalNet.MarkerGroup"]],
+ input_marker_groups: Dict[str, List["OCCausalNet.MarkerGroup"]],
+ activity_count: Dict[str, int] = None,
+ relative_occurrence_threshold: float = 0,
+ ):
+ """
+ Constructor
+
+ Parameters
+ ----------
+ dependency_graph : nx.MultiDiGraph
+ Object-centric dependency graph
+ Arc (a, object_type, a') must be encoded as dg[a][a'][object_type] = {"object_type": object_type}
+ output_marker_groups : Dict[str, List[OCCausalNet.MarkerGroup]]
+ Output marker groups per activity
+ input_marker_groups : Dict[str, List[OCCausalNet.MarkerGroup]]
+ Input marker groups per activity
+ activity_count : Dict[str, int]
+ Activity counts in the event log for filtering of infrequent marker groups.
+ relative_occurrence_threshold : float
+ Relative threshold for filtering infrequent marker groups. Range is [0,1].
+ Default is 0, meaning no filtering.
+ """
+ self.__dependency_graph = dependency_graph
+ self.__activities = list(dependency_graph._node.keys())
+ if activity_count is None:
+ activity_count = {act: 1 for act in self.activities}
+ self.__edges = dependency_graph._succ
+ self.__relative_occurrence_threshold = relative_occurrence_threshold
+ self.__input_marker_groups, self.__output_marker_groups = filter4(
+ input_marker_groups,
+ output_marker_groups,
+ self.__relative_occurrence_threshold,
+ activity_count,
+ )
+ self.__object_types = {
+ o.object_type
+ for binds in self.__input_marker_groups.values()
+ for bs in binds
+ for o in bs.markers
+ }
+ self.__activity_count = activity_count
+
+ def __repr__(self):
+ # a OCCN is fully defined by its activities and marker groups
+ ret = f"Activities: {self.activities}"
+ for act in self.activities:
+ img = (
+ self.input_marker_groups[act] if act in self.input_marker_groups else []
+ )
+ ret += f"\nInput_marker_groups[{act}]: {img}\n"
+ omg = (
+ self.output_marker_groups[act]
+ if act in self.output_marker_groups
+ else []
+ )
+ ret += f"Output_marker_groups[{act}]: {omg}"
+ return ret
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __hash__(self):
+ return id(self)
+
+ def __eq__(self, other):
+ if isinstance(other, OCCausalNet):
+ def normalize_edges(edges):
+ normalized = Counter()
+ for source, target_dict in edges.items():
+ for target, key_dict in target_dict.items():
+ for edge_key, attributes in key_dict.items():
+ object_type = (
+ attributes.get("object_type")
+ if isinstance(attributes, dict)
+ else None
+ )
+ normalized[(source, target, edge_key, object_type)] += 1
+ return normalized
+
+ return (
+ set(self.activities) == set(other.activities)
+ and normalize_edges(self.edges) == normalize_edges(other.edges)
+ and all(
+ Counter(self.input_marker_groups.get(a, []))
+ == Counter(other.input_marker_groups.get(a, []))
+ for a in self.activities
+ )
+ and all(
+ Counter(self.output_marker_groups.get(a, []))
+ == Counter(other.output_marker_groups.get(a, []))
+ for a in self.activities
+ )
+ and set(self.object_types) == set(other.object_types)
+ and all(
+ self.activity_count.get(a, 0) == other.activity_count.get(a, 0)
+ for a in self.activities
+ )
+ and self.relative_occurrence_threshold
+ == other.relative_occurrence_threshold
+ )
+ return False
+
+ def __get_dependency_graph(self):
+ return self.__dependency_graph
+
+ def __get_activities(self):
+ return self.__activities
+
+ def __get_edges(self):
+ return self.__edges
+
+ def __get_input_marker_groups(self):
+ return self.__input_marker_groups
+
+ def __get_output_marker_groups(self):
+ return self.__output_marker_groups
+
+ def __get_object_types(self):
+ return self.__object_types
+
+ def __get_activity_count(self):
+ return self.__activity_count
+
+ def __get_relative_occurrence_threshold(self):
+ return self.__relative_occurrence_threshold
+
+ dependency_graph = property(__get_dependency_graph)
+ activities = property(__get_activities)
+ edges = property(__get_edges)
+ input_marker_groups = property(__get_input_marker_groups)
+ output_marker_groups = property(__get_output_marker_groups)
+ object_types = property(__get_object_types)
+ activity_count = property(__get_activity_count)
+ relative_occurrence_threshold = property(__get_relative_occurrence_threshold)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d02e1bb35994e5357b0cb3172deb7843039f506
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/semantics.py
@@ -0,0 +1,1062 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from collections import Counter, defaultdict
+import itertools
+from typing import Any, Dict, Generic, Optional, Set, Tuple, TypeVar, Union
+from copy import deepcopy
+from pm4py.objects.oc_causal_net.obj import OCCausalNet
+
+
+N = TypeVar("N", bound=OCCausalNet)
+M = TypeVar("M", bound=OCCausalNet.Marker)
+MG = TypeVar("MG", bound=OCCausalNet.MarkerGroup)
+
+
+class OCCausalNetState(Generic[N], defaultdict):
+ """
+ The state of an object-centric causal net is a mapping from activities act to
+ multisets of outstanding obligations (act2, object_id, object_type) from act2 to act.
+
+ ```
+ state = OCCausalNetState({act: Counter([(act2, object_id, object_type)])})
+ ```
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """Initializes the OCCausalNetState, querying unspecified activities defaults to an empty multiset."""
+ super().__init__(Counter)
+ data_args = args
+ if args and args[0] is Counter:
+ data_args = args[1:]
+ initial_data = dict(*data_args, **kwargs)
+ for act, obligations in initial_data.items():
+ self[act] = Counter(obligations)
+
+ def __hash__(self):
+ return frozenset(
+ (act, frozenset(counter.items()))
+ for act, counter in self.items()
+ if counter
+ ).__hash__()
+
+ def __eq__(self, other):
+ if not isinstance(other, OCCausalNetState):
+ return False
+ return all(
+ self.get(a, Counter()) == other.get(a, Counter())
+ for a in set(self.keys()) | set(other.keys())
+ )
+
+ def __le__(self, other):
+ for a, self_counter in self.items():
+ other_counter = other.get(a, Counter())
+ # Every obligation count in self must be less than or equal to the count in other.
+ if not all(
+ other_counter.get(pred, 0) >= count
+ for pred, count in self_counter.items()
+ ):
+ return False
+ return True
+
+ def __add__(self, other):
+ result = OCCausalNetState()
+ for a, self_counter in self.items():
+ result[a] += self_counter
+ for a, other_counter in other.items():
+ result[a] += other_counter
+ return result
+
+ def __sub__(self, other):
+ result = OCCausalNetState()
+ for a, self_counter in self.items():
+ diff = self_counter - other.get(a, Counter())
+ if diff != Counter():
+ result[a] = diff
+ return result
+
+ def __repr__(self):
+ # e.g. [(a, o1[order], a'), ...]
+ sorted_entries = sorted(self.items(), key=lambda item: item[0])
+ obligations = [
+ f"({pred}, {obj_id}[{ot}], {act}):{count}"
+ for (act, obl) in sorted_entries
+ for ((pred, obj_id, ot), count) in obl.items()
+ ]
+ return f'[{", ".join(obligations) if obligations else ""}]'
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __deepcopy__(self, memodict={}):
+ new_state = OCCausalNetState()
+ memodict[id(self)] = new_state
+ for act, obligations in self.items():
+ act_copy = (
+ memodict[id(act)] if id(act) in memodict else deepcopy(act, memodict)
+ )
+ counter_copy = (
+ memodict[id(obligations)]
+ if id(obligations) in memodict
+ else deepcopy(obligations, memodict)
+ )
+ new_state[act_copy] = counter_copy
+ return new_state
+
+ @property
+ def activities(self) -> Set:
+ """
+ Set of activities with outstanding obligations.
+ """
+ return set(act for act in self.keys() if self[act])
+
+
+class OCCausalNetSemantics(Generic[N]):
+ """
+ Class for the semantics of object-centric causal nets
+ """
+
+ @classmethod
+ def enabled_activities(
+ cls,
+ occn: N,
+ state: OCCausalNetState,
+ include_start_activities=False,
+ act_to_idx: dict = None,
+ ot_to_idx: dict = None,
+ ) -> Set:
+ """
+ Returns the enabled activities in the given state.
+
+ Parameters
+ ----------
+ occn
+ Object-centric causal net
+ state
+ State of the OCCN
+ include_start_activities
+ True if start activities should be included in the set.
+ Start activities are always enabled.
+ act_to_idx
+ If activities are denoted in the state by an id instead of their name,
+ a dictionary mapping activities to their index has to be provided here.
+ ot_to_idx
+ If object types are denoted in the state by an id instead of their name,
+ a dictionary mapping object types to their index has to be provided here.
+
+ Returns
+ -------
+ set
+ Set of all activities enabled.
+ """
+ return set(
+ act
+ for act in occn.activities
+ if (include_start_activities or not act.startswith("START_"))
+ and cls.is_enabled(occn, act, state, act_to_idx, ot_to_idx)
+ )
+
+ @classmethod
+ def is_enabled(
+ cls,
+ occn: N,
+ act: str,
+ state: OCCausalNetState,
+ act_to_idx: dict = None,
+ ot_to_idx: dict = None,
+ ) -> bool:
+ """
+ Checks whether a given activity is enabled in a given object-centric
+ casal net and state.
+ An activity is enabled if there exists an input marker group that can be
+ bound. Start activities are always enabled.
+
+ Parameters
+ ----------
+ occn
+ Object-centric causal net
+ act
+ Activity to check
+ state
+ State of the OCCN
+ act_to_idx
+ If activities are denoted in the state by an id instead of their name,
+ a dictionary mapping activities to their index has to be provided here.
+ ot_to_idx
+ If object types are denoted in the state by an id instead of their name,
+ a dictionary mapping object types to their index has to be provided here.
+
+ Returns
+ -------
+ bool
+ true if enabled, false otherwise
+ """
+ # Start activities are always enabled
+ if act.startswith("START_"):
+ return True
+
+ if act_to_idx:
+ act_id = act_to_idx[act]
+ else:
+ act_id = act
+
+
+ # preprocess Counter for this activity to a lookup table where values
+ # are sets of objects with outstanding obligations to this act
+ objects = defaultdict(set)
+ for rel_act, obj_id, ot_id in state[act_id].keys():
+ objects[(rel_act, ot_id)].add(obj_id)
+
+
+
+ imgs = occn.input_marker_groups[act]
+
+ # if there are not outstanding obligations, the activity cannot be enabled
+ if not state[act_id]:
+ return False
+
+ # check each img
+ for img in imgs:
+ # markers that allow for consumption of 0 obligations do not need to be enabled
+ # at least one marker of the img needs to be enabled
+ one_marker_enabled = False
+ for marker in img.markers:
+ min_count = marker.min_count
+ rel_act_id = (
+ marker.related_activity
+ if not act_to_idx
+ else act_to_idx[marker.related_activity]
+ )
+ ot_id = (
+ marker.object_type
+ if not ot_to_idx
+ else ot_to_idx[marker.object_type]
+ )
+
+ num_objects = len(objects[(rel_act_id, ot_id)])
+ if num_objects >= max(min_count, 1):
+ one_marker_enabled = True
+ elif min_count != 0:
+ # marker is not enabled, move on to next img
+ one_marker_enabled = False
+ break
+ if one_marker_enabled:
+ return True
+ return False
+
+ @classmethod
+ def _find_matching_marker_group(
+ cls, obligations: dict, marker_groups: list
+ ) -> Union[MG, None]:
+ """
+ Finda a matching marker group that is able to consume/produce the given obligations.
+
+ Parameters
+ ----------
+ obligations : dict
+ Obligations to consume, mapping related activities to a dict mapping
+ object types to a set of object ids
+ marker_groups : list
+ List of marker groups to check
+
+ Returns
+ -------
+ Union[MG, None]
+ A matching marker group if found, None otherwise.
+ """
+ if not obligations:
+ return None
+ # Calculate object counts from the obligations
+ obj_counts = {
+ related_act: {
+ ot: len(obligations[related_act][ot]) for ot in obligations[related_act]
+ }
+ for related_act in obligations
+ }
+
+ # check each group
+ for mg in marker_groups:
+ mg_dict = mg.dict_representation
+
+ # Check that markers for all required related activities exist
+ # and all required ots are present
+ failure = False
+ for related_act in obj_counts:
+ if related_act not in mg_dict:
+ failure = True
+ for ot in obj_counts[related_act]:
+ if ot not in mg_dict[related_act]:
+ failure = True
+ if failure:
+ continue
+
+ # 1: check that count matches (= is within cardinality bounds)
+ counts_match = all(
+ mg_dict[related_act][ot][1]
+ >= obj_counts.get(related_act, {}).get(ot, 0)
+ >= mg_dict[related_act][ot][0]
+ for related_act in mg_dict
+ for ot in mg_dict[related_act]
+ )
+ if not counts_match:
+ continue
+
+ # 2: check key constraints
+ constraints_violated = any(
+ obligations.get(rel_act_1, {})
+ .get(ot, set())
+ .intersection(obligations.get(rel_act_2, {}).get(ot, set()))
+ for (rel_act_1, ot, rel_act_2) in mg.key_constraints
+ )
+ if constraints_violated:
+ continue
+
+ # found matching group
+ return mg
+
+ return None
+
+ @classmethod
+ def is_binding_enabled(
+ cls,
+ net: N,
+ act: str,
+ cons: Dict[str, Dict[str, Set]],
+ prod: Dict[str, Dict[str, Set]],
+ state: OCCausalNetState,
+ ) -> Optional[Tuple[MG, MG]]:
+ """
+ Checks whether the given binding is enabled in the object-centric causal net.
+ A binding is enabled if the activity has input and output marker groupos that
+ match the given objects and the state contains all necessary obligations.
+
+
+ Parameters
+ ----------
+ net : N
+ The object-centric causal net
+ act : str
+ The activity to bind
+ cons : dict[str, dict[str, Set]]
+ The obligations to consume, mapping predecessor activities to a dict mapping
+ object types to a set of object ids
+ prod : dict[str, dict[str, Set]]
+ The obligations to produce, mapping successor activities to a dict mapping
+ object types to a set of object ids
+ state : OCCausalNetState
+ The current state of the OCCN
+
+ Returns
+ -------
+ Union[tuple[MG, MG], None]:
+ The input and output marker groups enabling the binding if it is enabled, None otherwise.
+ """
+ # 1: check that all consumed obligations are present in the state
+ if cons:
+ if any(
+ state[act].get((pred, obj_id, ot), 0) <= 0
+ for pred in cons.keys()
+ for ot in cons[pred].keys()
+ for obj_id in cons[pred][ot]
+ ):
+ return None
+ else:
+ if not prod:
+ # we need to either consume or produce obligations
+ return None
+
+ # 2: Find a matching input marker group
+ if act.startswith("START_"):
+ if cons:
+ return None
+ # For START activities, we do not consume obligations, cons has to be empty
+ matched_img = None
+ else:
+ matched_img = cls._find_matching_marker_group(
+ cons, net.input_marker_groups[act]
+ )
+ if matched_img is None:
+ return None
+
+ # 3: Find a matching output marker group
+ if act.startswith("END_"):
+ if prod:
+ return None
+ # For START activities, we do not consume obligations, prod has to be empty
+ matched_omg = None
+ else:
+ matched_omg = cls._find_matching_marker_group(
+ prod, net.output_marker_groups[act]
+ )
+ if matched_omg is None:
+ return None
+
+ return (matched_img, matched_omg)
+
+ @classmethod
+ def bind_activity(
+ cls,
+ net: N,
+ act: str,
+ cons: Dict[str, Dict[str, Set]],
+ prod: Dict[str, Dict[str, Set]],
+ state: OCCausalNetState,
+ ) -> OCCausalNetState:
+ """
+ Binds an activity in the object-centric causal net.
+ For performance reasons, this method does not check whether the binding
+ is valid given the current state. If necessary, the caller should
+ ensure this, e.g., using the `is_binding_enabled` method.
+
+ Parameters
+ ----------
+ net : N
+ The object-centric causal net
+ act : str
+ The activity to bind
+ cons : dict[str, dict[str, Set]]
+ The obligations to consume, mapping predecessor activities to a dict mapping
+ object types to a set of object ids
+ prod : dict[str, dict[str, Set]]
+ The obligations to produce, mapping successor activities to a dict mapping
+ object types to a set of object ids
+ state : OCCausalNetState
+ The current state of the OCCN
+
+ Returns
+ -------
+ OCCausalNetState
+ The new state after binding the activity
+ """
+ # consume obligations
+ if cons:
+ consume = OCCausalNetState(
+ {
+ act: Counter(
+ [
+ (pred, obj_id, ot)
+ for pred in cons
+ for ot in cons[pred]
+ for obj_id in cons[pred][ot]
+ ]
+ )
+ }
+ )
+ state -= consume
+
+ # produce obligations
+ if prod:
+ produce = OCCausalNetState(
+ {
+ succ: Counter(
+ [
+ (act, obj_id, ot)
+ for ot in prod[succ]
+ for obj_id in prod[succ][ot]
+ ]
+ )
+ for succ in prod
+ }
+ )
+ state += produce
+
+ return state
+
+ @classmethod
+ def replay(cls, occn: N, sequence: tuple) -> bool:
+ """
+ Replays a sequence of bindings on the object-centric causal net.
+
+ Parameters
+ ----------
+ occn : N
+ The object-centric causal net to replay on.
+ sequence : tuple
+ A sequence of bindings, where each binding is a tuple of (activity_name, consumed_obligations, produced_obligations).
+ consumed_obligations and produced_obligations are dictionaries mapping
+ related activities to a dict mapping object types to a set of object ids.
+
+ Returns
+ -------
+ bool
+ True if the sequence can be replayed on the net, False otherwise.
+ """
+ # start in the empty state
+ state = OCCausalNetState()
+
+ # replay each binding
+ for act, cons, prod in sequence:
+ if not cls.is_binding_enabled(occn, act, cons, prod, state):
+ return False
+
+ state = cls.bind_activity(occn, act, cons, prod, state)
+
+ # check if we are in the empty state
+ if state.activities:
+ return False
+
+ return True
+
+ @classmethod
+ def enabled_bindings_start_activity(
+ cls,
+ occn: N,
+ act: str,
+ object_type: str,
+ objects: set,
+ act_to_idx: dict = None,
+ ot_to_idx: dict = None,
+ ) -> tuple:
+ """
+ Computes all enabled bindings for a start activity with a given set of objects.
+ These bindings will produce obligations for at least one of the objects.
+ Based on the `enabled_bindings` method, but specialized for start activities.
+
+ Parameters
+ ----------
+ occn : N
+ The object-centric causal net
+ act : str
+ The start activity to bind
+ object_type : str
+ The object type of the start activity
+ objects : set
+ A set of objects to bind to the activity. All bindings will bind at least one.
+ act_to_idx : dict, optional
+ If activities are denoted in the state by an id instead of their name,
+ a dictionary mapping activities to their index has to be provided here.
+ ot_to_idx : dict, optional
+ If object types are denoted in the state by an id instead of their name,
+ a dictionary mapping object types to their index has to be provided here.
+
+ Returns
+ -------
+ tuple
+ A tuple where entries are tuples of activity id, consumed objects, and produced objects.
+ Consumed / produces are tuples of (predecessor/successor activity id, objects_per_ot)
+ where objects_per_ot is a tuples of entries (object_type, objects)
+ where objects is a tuple (obj_id_1, obj_id_2, ...).
+ If act_to_idx and ot_to_idx are provided, indices instead of names are
+ used for activities and object types.
+ """
+ assert act.startswith("START_"), "This method is only for start activities."
+ if act_to_idx:
+ act_id = act_to_idx[act]
+ else:
+ act_id = act
+
+ if ot_to_idx:
+ ot_id = ot_to_idx[object_type]
+ else:
+ ot_id = object_type
+
+ # create a list of fake consumed tuples that binds the powerset of objects
+ fake_consumed = []
+ for i in range(len(objects)):
+ for combo in itertools.combinations(objects, i + 1):
+ fake_consumed.append((
+ (-1, (
+ (ot_id, combo),
+ )
+ )
+ ,))
+
+ # create the corresponding produced tuples
+ memo_produced = {}
+ memo_ot_assignments = {}
+
+ enabled_bindings = []
+
+ for consumed in fake_consumed:
+ possible_produced_for_consumed = cls.__generate_produced_for_consumed(
+ occn,
+ act,
+ consumed,
+ memo_produced,
+ memo_ot_assignments,
+ act_to_idx,
+ ot_to_idx,
+ )
+
+ for produced in possible_produced_for_consumed:
+ enabled_bindings.append((act_id, None, produced))
+
+ return tuple(enabled_bindings)
+
+ @classmethod
+ def enabled_bindings(
+ cls,
+ occn: N,
+ act: str,
+ state: OCCausalNetState,
+ act_to_idx: dict = None,
+ ot_to_idx: dict = None,
+ ) -> tuple:
+ """
+ Computes all enabled bindings for a given activity in a given state.
+
+ Parameters
+ ----------
+ occn : N
+ The object-centric causal net
+ act : str
+ The activity to bind
+ state : OCCausalNetState
+ The current state of the OCCN
+ act_to_idx : dict, optional
+ If activities are denoted in the state by an id instead of their name,
+ a dictionary mapping activities to their index has to be provided here.
+ ot_to_idx : dict, optional
+ If object types are denoted in the state by an id instead of their name,
+ a dictionary mapping object types to their index has to be provided here.
+
+ Returns
+ -------
+ tuple
+ A tuple where entries are tuples of activity id, consumed objects, and produced objects.
+ Consumed / produces are tuples of (predecessor/successor activity id, objects_per_ot)
+ where objects_per_ot is a tuples of entries (object_type, objects)
+ where objects is a tuple (obj_id_1, obj_id_2, ...).
+ If act_to_idx and ot_to_idx are provided, indices instead of names are
+ used for activities and object types.
+ """
+ if act_to_idx:
+ act_id = act_to_idx[act]
+ else:
+ act_id = act
+
+ # outstanding obligations for the activity
+ obligations = state[act_id]
+
+ # pre-process obligations to a dict where keys are (related activity, object_type)
+ # and values are sets of object ids (neglecting the count)
+ obligations_dict = defaultdict(set)
+ for (related_act, obj_id, ot_id), _ in obligations.items():
+ obligations_dict[(related_act, ot_id)].add(obj_id)
+
+ # ----------- Create all possibilities for consumed -----------
+
+ possible_consumed = cls.__generate_consumed(
+ occn, act, obligations_dict, act_to_idx, ot_to_idx
+ )
+ if not possible_consumed:
+ return ()
+
+ # ----------- Create all possible produced tuples per consumed tuple -----------
+
+ final_bindings = []
+ # Memoization for produced tuples, keyed by comsumed object sets by object type
+ memo_produced = {}
+ # Memoization for sub-problem of assigning objects of one ot for one omg
+ memo_ot_assignments = {}
+
+ for consumed in possible_consumed:
+ # End activities do not produce obligations
+ if act.startswith("END_"):
+ possible_produced_for_consumed = {None}
+ else:
+ possible_produced_for_consumed = cls.__generate_produced_for_consumed(
+ occn,
+ act,
+ consumed,
+ memo_produced,
+ memo_ot_assignments,
+ act_to_idx,
+ ot_to_idx,
+ )
+
+ # Create final bindings
+ for produced in possible_produced_for_consumed:
+ final_bindings.append((act_id, consumed, produced))
+
+ return tuple(final_bindings)
+
+ @classmethod
+ def __generate_consumed(
+ cls,
+ occn: N,
+ act: str,
+ obligations_dict: dict,
+ act_to_idx: dict = None,
+ ot_to_idx: dict = None,
+ ) -> Set[tuple]:
+ """
+ Generates all possible consumed tuples for a given activity and obligations.
+ """
+ possible_consumed = set()
+ for img in occn.input_marker_groups[act]:
+ img_dict = img.dict_representation
+
+ # preprocess key constraints if ids are used
+ key_constraints_by_id = []
+ if act_to_idx:
+ for rel_act_1_id, ot_id, rel_act_2_id in img.key_constraints:
+ key_constraints_by_id.append(
+ (
+ act_to_idx[rel_act_1_id],
+ ot_to_idx[ot_id],
+ act_to_idx[rel_act_2_id],
+ )
+ )
+ else:
+ key_constraints_by_id = img.key_constraints
+
+ # get all combinations on which objects we can consume given the img
+ keys, combinations_iter_list = (
+ cls.__generate_predecessor_object_combinations(
+ img_dict, obligations_dict, act_to_idx, ot_to_idx
+ )
+ )
+
+ if not keys:
+ # img not enabled
+ continue
+
+ # from the consumed_per_pred, create all combinations of consumed obligations
+ # these are added to possible_consumed
+ cls.__consumed_from_predecessor_combinations(
+ possible_consumed, keys, combinations_iter_list, key_constraints_by_id
+ )
+
+ return possible_consumed
+
+ @classmethod
+ def __generate_predecessor_object_combinations(
+ cls,
+ img_dict: dict,
+ obligations_dict: dict,
+ act_to_idx: dict = None,
+ ot_to_idx: dict = None,
+ ):
+ """
+ Generates all combinations of objects from obligations_dict that can be consumed given the img_dict.
+ """
+ # we build two lists: keys of format (predecessor_id, ot_id) and
+ # a list of iterations where each iterator yields all possible object
+ # combinations for all (predecessor, ot) pairs
+ keys = []
+ combinations_iter_list = []
+
+ for predecessor in img_dict:
+ for ot in img_dict[predecessor]:
+ min_count, max_count = img_dict[predecessor][ot]
+
+ if act_to_idx:
+ pred_id = act_to_idx[predecessor]
+ else:
+ pred_id = predecessor
+
+ if ot_to_idx:
+ ot_id = ot_to_idx[ot]
+ else:
+ ot_id = ot
+
+ # get all objects for obligations of the predecessor activity and object type
+ objects_for_pred = sorted(obligations_dict[(pred_id, ot_id)])
+
+ if len(objects_for_pred) < min_count:
+ # get to next img, this one cannot be bound
+ return [], []
+ if not objects_for_pred:
+ # no objects available for this (pred, ot) pair, skip
+ continue
+ else:
+ # get all combinations of objects
+ keys.append((pred_id, ot_id))
+ combinations_for_req = itertools.chain.from_iterable(
+ [
+ itertools.combinations(objects_for_pred, r)
+ for r in range(
+ # this (pred, ot) pair may consume min_count to max_count objects
+ min_count,
+ min(max_count, len(objects_for_pred)) + 1,
+ )
+ ]
+ )
+ combinations_iter_list.append(combinations_for_req)
+
+ return keys, combinations_iter_list
+
+ @staticmethod
+ def __consumed_from_predecessor_combinations(
+ possible_consumed: set,
+ keys: list,
+ combinations_iter_list: list,
+ key_constraints_by_id: list,
+ ):
+ """
+ Generates all consumed tuples given all possible assignments from
+ (predecessor, object type) tuples to sets of objects that may be consumed
+ by this pair.
+ """
+ # create cross product of all options per predecessor and object type
+ cross_product_iter = itertools.product(*combinations_iter_list)
+ for binding_selection in cross_product_iter:
+ # create dict mapping predecessor activitiy to (ot_id, objects) tuples
+ grouped_by_pred = defaultdict(dict)
+ for (pred_id, ot_id), objects in zip(keys, binding_selection):
+ if len(objects) > 0:
+ grouped_by_pred[pred_id][ot_id] = objects
+
+ # if all markers of the img are optional, we can skip empty bindings
+ if not grouped_by_pred:
+ continue
+
+ # Check key constraints
+ constraint_violated = False
+ for rel_act_1_id, ot_id, rel_act_2_id in key_constraints_by_id:
+ objects1 = grouped_by_pred.get(rel_act_1_id, {}).get(ot_id)
+ objects2 = grouped_by_pred.get(rel_act_2_id, {}).get(ot_id)
+ if objects1 and objects2 and set(objects1).intersection(objects2):
+ # key constraint violated, move on to next binding
+ constraint_violated = True
+ break
+
+ if constraint_violated:
+ continue
+
+ # convert to memory-efficient tuple representation
+ consumed_tuple = tuple(
+ # sorting necessary to ensure duplicate-free tuples in possible_consumed
+ (pred_id, tuple(sorted(ot_obj_pairs.items())))
+ for pred_id, ot_obj_pairs in sorted(grouped_by_pred.items())
+ )
+ # add to possible consumed obligations (duplicate-free)
+ possible_consumed.add(consumed_tuple)
+
+ @classmethod
+ def __generate_produced_for_consumed(
+ cls,
+ occn: N,
+ act: str,
+ consumed: tuple,
+ memo_produced: dict,
+ memo_ot_assignments: dict,
+ act_to_idx: dict = None,
+ ot_to_idx: dict = None,
+ ) -> Set[tuple]:
+ """
+ Generates all possible produced tuples for a given consumed tuple.
+ """
+ # 1. Process consumed tuple into sets of consumed objects per ot
+ consumed_objects_by_ot = defaultdict(set)
+ for _, ot_obj_pairs in consumed:
+ for ot_id, objects in ot_obj_pairs:
+ consumed_objects_by_ot[ot_id].update(objects)
+
+ # Create hashable key for memo
+ consumed_key = cls.__make_hashable(consumed_objects_by_ot)
+
+ # 2. Check memo cache
+ if consumed_key in memo_produced:
+ possible_produced_for_consumed = memo_produced[consumed_key]
+ else:
+ # Compute all possible produced tuples
+ possible_produced_for_consumed = set() # set to avoid duplicates
+ # Compute per omg; cache to avoid recomputation
+ for omg in occn.output_marker_groups[act]:
+ produced_for_omg = cls.__generate_produced_for_omg(
+ omg,
+ consumed_objects_by_ot,
+ memo_ot_assignments,
+ act_to_idx,
+ ot_to_idx,
+ )
+ possible_produced_for_consumed.update(produced_for_omg)
+
+ # Store result in cache
+ memo_produced[consumed_key] = possible_produced_for_consumed
+
+ return possible_produced_for_consumed
+
+ @classmethod
+ def __generate_produced_for_omg(
+ cls, omg, consumed_objects_by_ot, memo, act_to_idx, ot_to_idx
+ ):
+ """
+ Generates all possible produced tuples for a given output marker group and
+ consumed objects by object type (these need to be produced).
+ """
+ omg_dict = omg.dict_representation
+
+ # Pre-process omg requirements and key constraints into efficient lookups in case ids are used
+ reqs_by_ot = defaultdict(list)
+ key_constraints_by_ot = defaultdict(set)
+
+ for succ_name, ot_map in omg_dict.items():
+ succ_id = act_to_idx[succ_name] if act_to_idx else succ_name
+ for ot_name, (min_c, max_c) in ot_map.items():
+ ot_id = ot_to_idx[ot_name] if ot_to_idx else ot_name
+ reqs_by_ot[ot_id].append((succ_id, min_c, max_c))
+
+ for s1_name, ot_name, s2_name in omg.key_constraints:
+ s1_id = act_to_idx[s1_name] if act_to_idx else s1_name
+ ot_id = ot_to_idx[ot_name] if ot_to_idx else ot_name
+ s2_id = act_to_idx[s2_name] if act_to_idx else s2_name
+ key_constraints_by_ot[ot_id].add(frozenset([s1_id, s2_id]))
+
+ # Check if objects types match for early exit
+ consumed_ots = set(consumed_objects_by_ot.keys())
+ required_ots = set(reqs_by_ot.keys())
+
+ if not consumed_ots.issubset(required_ots):
+ # omg has no marker for some consumed object type
+ return []
+
+ missing_required_ots = required_ots - consumed_ots
+ for missing_ot in missing_required_ots:
+ # marker has an ot that was not consumed
+ # this is an issue if that marker is not optional
+ if any(min_c > 0 for _, min_c, _ in reqs_by_ot[missing_ot]):
+ return []
+
+ # Get all possible assignments of successor activities to consumed objects
+ # this is done per individually per object type
+ ot_ids_in_order, assignments_in_order = cls.__generate_successor_assignments(
+ omg, memo, consumed_objects_by_ot, reqs_by_ot, key_constraints_by_ot
+ )
+
+ # Get cross product of all assignments per object type to get all possible produced tuples
+ final_produced_tuples = cls.__produced_from_successor_assignments(
+ ot_ids_in_order, assignments_in_order
+ )
+
+ return final_produced_tuples
+
+ @staticmethod
+ def __generate_successor_assignments(
+ omg: MG,
+ memo: dict,
+ consumed_objects_by_ot: dict,
+ reqs_by_ot: dict,
+ key_constraints_by_ot: dict,
+ ):
+ """
+ Generates all possible assignments of consumed objects to successor activities.
+ """
+ # we generate all possible assignments of consumed objects to successor activities
+ # and then prune the ones that violate key constraints and
+ # the ones that violate the min/max cardinality requirements
+ ot_ids_in_order = []
+ assignments_in_order = []
+ # Solve assignment problem for each object type separetly
+ # this is cached since different consumed_objects_by_ot may have
+ # the same object sets for the same ot_id
+ for ot_id, objects in consumed_objects_by_ot.items():
+ memo_key = (id(omg), ot_id, frozenset(objects))
+ if memo_key in memo:
+ valid_ot_assignments = memo[memo_key]
+ else:
+ ot_reqs = reqs_by_ot.get(ot_id, [])
+ successors_for_ot = [req[0] for req in ot_reqs]
+ ot_key_constraints = key_constraints_by_ot.get(ot_id, set())
+
+ per_object_choices = []
+ for obj in objects:
+ obj_choices = []
+ # object may be assigned to 1 or more successors
+ for i in range(1, len(successors_for_ot) + 1):
+ # get all combinations of successors of size i
+ for succ_set in itertools.combinations(successors_for_ot, i):
+ # check key constraints
+ is_valid = all(
+ frozenset(pair) not in ot_key_constraints
+ for pair in itertools.combinations(succ_set, 2)
+ )
+ if is_valid:
+ obj_choices.append(succ_set)
+ if not obj_choices:
+ return [], [] # An object has no valid assignment
+ per_object_choices.append(obj_choices)
+
+ # Create all combinations of assignments with cross-product over all objects
+ valid_ot_assignments = []
+ for assignment_choice in itertools.product(*per_object_choices):
+ final_assignment = defaultdict(list)
+ for obj, succs in zip(objects, assignment_choice):
+ for succ in succs:
+ final_assignment[succ].append(obj)
+
+ # Check cardinality constraints
+ counts_ok = True
+ for succ_id, min_c, max_c in ot_reqs:
+ count = len(final_assignment.get(succ_id, []))
+ if not (min_c <= count <= max_c):
+ counts_ok = False
+ break
+
+ if counts_ok:
+ # add to valid assignments
+ canonical_assignment = {
+ s: tuple(sorted(o)) for s, o in final_assignment.items()
+ }
+ valid_ot_assignments.append(canonical_assignment)
+
+ # Store in memoization cache
+ memo[memo_key] = valid_ot_assignments
+
+ # Only proceed if we have valid assignments for this ot_id
+ if not valid_ot_assignments:
+ return [], []
+
+ # Store ot_id and valid assignments
+ ot_ids_in_order.append(ot_id)
+ assignments_in_order.append(valid_ot_assignments)
+
+ return ot_ids_in_order, assignments_in_order
+
+ @staticmethod
+ def __produced_from_successor_assignments(
+ ot_ids_in_order: list, assignments_in_order: list
+ ) -> Set[tuple]:
+ """
+ Generates all produced tuples given all possible assignments from
+ successor activities to sets of objects that may be produced for this activity.
+ """
+ final_produced_tuples = set() # avoid duplicates
+ for final_choice in itertools.product(*assignments_in_order):
+ # convert to dict first
+ produced_grouped_by_succ = defaultdict(dict)
+
+ for ot_id, ot_assignment_dict in zip(ot_ids_in_order, final_choice):
+ for succ_id, assigned_objects in ot_assignment_dict.items():
+ if len(assigned_objects) > 0:
+ produced_grouped_by_succ[succ_id][ot_id] = assigned_objects
+
+ # Has to produce at least one object
+ if not produced_grouped_by_succ:
+ continue
+
+ # Convert to tuple representation
+ produced_tuple = tuple(
+ (succ_id, tuple(sorted(ot_obj_pairs.items())))
+ for succ_id, ot_obj_pairs in sorted(produced_grouped_by_succ.items())
+ )
+ final_produced_tuples.add(produced_tuple)
+ return final_produced_tuples
+
+ @staticmethod
+ def __make_hashable(d):
+ """Helper function to create a hashable key from a dictionary."""
+ # Converts a dict of {ot_id: set(obj_ids)} to a frozenset of items
+ # so it can be used as a dictionary key for memoization.
+ return frozenset((k, frozenset(v)) for k, v in d.items())
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..93032146b879d258ed0827ab976bda55932f74d0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.oc_causal_net.utils import filters, occn_utils
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/filters.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..c50a32a4fc196281309750364aa97ef04824471e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/filters.py
@@ -0,0 +1,187 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+
+def filter4(input_marker_groups, output_marker_groups, threshold, activity_count):
+ """
+ Filters input_marker_groups and output_marker_groups by relative support, then
+ recursively keeps only those MarkerGroups that remain connected.
+
+ Parameters
+ ----------
+ input_marker_groups : Dict[str, List[OCCausalNet.MarkerGroup]]
+ Input marker groups of the activities
+ output_marker_groups : Dict[str, List[OCCausalNet.MarkerGroup]]
+ Output marker groups of the activities
+ threshold : float
+ Minimum relative support = support_count / activity_count[activity]
+ activity_count : Dict[str,int]
+ Absolute frequency of each activity in the event log.
+
+ Returns
+ -------
+ Tuple[
+ Dict[str, List[OCCausalNet.MarkerGroup]],
+ Dict[str, List[OCCausalNet.MarkerGroup]]
+ ]
+ (filtered_input_marker_groups, filtered_output_marker_groups)
+ """
+
+ def filterByTreshold(marker_groups, activity):
+ """
+ Filters a list of MarkerGroups by relative support.
+
+ Parameters
+ ----------
+ marker_groups : List[OCCausalNet.MarkerGroup]
+ The MarkerGroups to filter.
+ activity : str
+ Activity name whose frequency is used for relative support.
+
+ Returns
+ -------
+ List[OCCausalNet.MarkerGroup]
+ Those groups whose support_count / activity_count[activity] > threshold.
+ """
+ filteredMarkerGroups = [
+ marker_group
+ for marker_group in marker_groups
+ if marker_group.support_count / activity_count[activity] > threshold
+ ]
+ return filteredMarkerGroups
+
+ def getMostFrequent(marker_groups):
+ """
+ Returns the most frequent MarkerGroup in the list.
+
+ Parameters
+ ----------
+ marker_groups : List[OCCausalNet.MarkerGroup]
+ List of marker groups to examine.
+
+ Returns
+ -------
+ OCCausalNet.MarkerGroup
+ The one with the highest support_count.
+ """
+ try:
+ most_frequent_marker_group = marker_groups[
+ [marker_group.support_count for marker_group in marker_groups].index(
+ max([marker_group.support_count for marker_group in marker_groups])
+ )
+ ]
+ except ValueError as e:
+ raise Exception(f"Invalid marker groups provided for some activity. Error: {e}")
+ return most_frequent_marker_group
+
+ def getSubsequentInputMarkerGroups(most_frequent_marker_group, activity):
+ """
+ For every marker in *most_frequent_marker_group* (which belongs to an
+ **output** marker group of *activity*) look up the corresponding input
+ marker groups of the marker's successor activity.
+ Keeps only the most frequent ones and adds them to the
+ *filtered_input_marker_groups* structure.
+
+ Parameters
+ ----------
+ most_frequent_marker_group : OCCausalNet.MarkerGroup
+ activity : str
+ """
+ for marker in most_frequent_marker_group.markers:
+ succ_activity = marker.related_activity
+ if succ_activity in input_marker_groups.keys():
+ possible_input_marker_groups = [
+ x
+ for x in input_marker_groups[succ_activity]
+ if (activity, marker.object_type)
+ in [(y.related_activity, y.object_type) for y in x.markers]
+ ]
+ most_frequent_marker_group = getMostFrequent(possible_input_marker_groups)
+ addToFilteredInputMarkerGroups(most_frequent_marker_group, succ_activity)
+
+ def addToFilteredOutputMarkerGroups(most_frequent_marker_group, activity):
+ """
+ Inserts *most_frequent_marker_group* into *filtered_output_marker_groups* and
+ triggers the recursive traversal to the input side.
+
+ Parameters
+ ----------
+ most_frequent_marker_group : OCCausalNet.MarkerGroup
+ activity : str
+ """
+ if most_frequent_marker_group not in filtered_output_marker_groups[activity]:
+ filtered_output_marker_groups[activity].append(most_frequent_marker_group)
+ getSubsequentInputMarkerGroups(most_frequent_marker_group, activity)
+
+ def getSubsequentOutputMarkerGroups(most_frequent_marker_group, activity):
+ """
+ For every marker in *most_frequent_marker_group* (which belongs to an
+ **input** marker_group of *activity*) look up the corresponding output
+ marker groups of the marker's predecessor activity.
+ Keeps only the most frequent ones and adds them to the
+ *filtered_output_marker_groups* structure.
+
+ Parameters
+ ----------
+ most_frequent_marker_group : OCCausalNet.MarkerGroup
+ activity : str
+ """
+ for marker in most_frequent_marker_group.markers:
+ pred_activity = marker.related_activity
+ if pred_activity in output_marker_groups.keys():
+ possible_output_marker_groups = [
+ x
+ for x in output_marker_groups[pred_activity]
+ if (activity, marker.object_type)
+ in [(y.related_activity, y.object_type) for y in x.markers]
+ ]
+ most_frequent_marker_group = getMostFrequent(possible_output_marker_groups)
+ addToFilteredOutputMarkerGroups(most_frequent_marker_group, pred_activity)
+
+ def addToFilteredInputMarkerGroups(most_frequent_marker_group, activity):
+ """
+ Inserts *most_frequent_marker_group* into *filtered_input_marker_groups* and
+ triggers the recursive traversal to the output side.
+
+ Parameters
+ ----------
+ most_frequent_marker_group : OCCausalNet.MarkerGroup
+ activity : str
+ """
+ if most_frequent_marker_group not in filtered_input_marker_groups[activity]:
+ filtered_input_marker_groups[activity].append(most_frequent_marker_group)
+ getSubsequentOutputMarkerGroups(most_frequent_marker_group, activity)
+
+ filtered_output_marker_groups = {act: [] for act in output_marker_groups.keys()}
+ filtered_input_marker_groups = {act: [] for act in input_marker_groups.keys()}
+
+ for act in filtered_output_marker_groups.keys():
+ filteredMarkerGroups = filterByTreshold(output_marker_groups[act], act)
+ for marker_group in filteredMarkerGroups:
+ addToFilteredOutputMarkerGroups(marker_group, act)
+
+ for act in filtered_input_marker_groups.keys():
+ filteredMarkerGroups = filterByTreshold(input_marker_groups[act], act)
+ for marker_group in filteredMarkerGroups:
+ addToFilteredInputMarkerGroups(marker_group, act)
+
+ return filtered_input_marker_groups, filtered_output_marker_groups
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/occn_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/occn_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5eb001d9f8a447995d746054d8255cf726db174
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/utils/occn_utils.py
@@ -0,0 +1,94 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Set
+
+
+
+def pre_set(occn, activity: str, object_type: str = None) -> Set:
+ """
+ Returns the set of predecessor activities for a given activity in an object-centric causal net.
+ Restricted to predecessors connected using arcs of the specified object type, if provided.
+
+ Parameters
+ ----------
+ occn : OCCausalNet
+ The object-centric causal net to query
+ activity : str
+ The name of the activity for which to get the predecessors
+ object_type : str, optional
+ The object type to restrict the predecessors to (default is None)
+
+ Returns
+ -------
+ Set
+ Set of predecessor activities of the specified object type.
+ """
+ if activity not in occn.activities:
+ return set()
+
+ dg = occn.dependency_graph
+
+ if object_type is None:
+ return dg.predecessors(activity)
+
+ return {
+ predecessor
+ for predecessor, _, edge_key in dg.in_edges(activity, keys=True)
+ if edge_key == object_type
+ }
+
+def post_set(occn, activity: str, object_type: str = None) -> Set:
+ """
+ Returns the set of successor activities for a given activity in an object-centric causal net.
+ Restricted to successors connected using arcs of the specified object type, if provided.
+
+ Parameters
+ ----------
+ occn : OCCausalNet
+ The object-centric causal net to query
+ activity : str
+ The name of the activity for which to get the successors
+ object_type : str, optional
+ The object type to restrict the successors to (default is None)
+
+ Returns
+ -------
+ Set
+ Set of successor activities of the specified object type.
+ """
+ if activity not in occn.activities:
+ return set()
+
+ dg = occn.dependency_graph
+
+ if object_type is None:
+ return dg.successors(activity)
+
+ return {
+ successor
+ for _, successor, edge_key in dg.out_edges(activity, keys=True)
+ if edge_key == object_type
+ }
+
+
+
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f067c90bdbf0e266ffba32a2f19843407b5c4484
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.oc_causal_net.variants import to_ocpn
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/variants/to_ocpn.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/variants/to_ocpn.py
new file mode 100644
index 0000000000000000000000000000000000000000..da3a81b927a96fd0723f81e93fcc4c4725ba996b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/oc_causal_net/variants/to_ocpn.py
@@ -0,0 +1,1621 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.oc_causal_net.obj import OCCausalNet
+from pm4py.objects.ocpn.obj import OCPetriNet
+
+# object type for binding places used to redstric the OCPN to firing one input and output marker group per firing of the activity
+BINDING_OBJECT_TYPE = "_binding"
+
+# prefix for silent transitions in the OCPN
+SILENT_TRANSITION_PREFIX = "_silent"
+
+
+def apply(occn: OCCausalNet, parameters=None) -> OCPetriNet:
+ r"""
+ Converts an Object-centric Causal Net (OCCN) to an Object-centric Petri Net (OCPN) with empty markings.
+ All cardinalities c!=(1,1) are treated as c=(0, \*). Keys for input marker groups are ignored.
+
+ Parameters
+ ----------
+ occn : OCCausalNet
+ The Object-centric Causal Net to convert. Start and end activities must be labeled "START_{object_type}" and "END_{object_type}" respectively.
+
+ parameters : dict, optional
+ Additional parameters for the conversion (not used in this implementation).
+
+ Returns
+ -------
+ OCPetriNet
+ The converted Object-centric Petri Net with empty markings.
+"""
+ activities = occn.activities
+ object_types = occn.object_types
+ img = occn.input_marker_groups
+ omg = occn.output_marker_groups
+
+ assert (
+ BINDING_OBJECT_TYPE not in object_types
+ ), f"The binding object type {BINDING_OBJECT_TYPE} must not be present in the OCCN."
+
+ assert not (
+ any(activity.startswith(SILENT_TRANSITION_PREFIX) for activity in activities)
+ ), f"The OCCN must not contain any activities with prefix {SILENT_TRANSITION_PREFIX}."
+
+ assert (
+ all(f"START_{object_type}" in activities for object_type in object_types)
+ ), "All object types must have a corresponding start activity labeled 'START_{object_type}'."
+
+ assert (
+ all(f"END_{object_type}" in activities for object_type in object_types)
+ ), "All object types must have a corresponding end activity labeled 'END_{object_type}'."
+
+ ordered_key_groups_input = build_ordered_key_groups(activities, img)
+ ordered_key_groups_output = build_ordered_key_groups(activities, omg)
+
+ places = set()
+ place_names = set()
+ transitions = set()
+ arcs = set()
+
+ # create global input binding place
+ p_input_binding = OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}_global_input",
+ object_type=BINDING_OBJECT_TYPE,
+ )
+
+ places.add(p_input_binding)
+
+ # recursively create OCPN for every activity
+ for activity in activities:
+ transform_activity(
+ activity=activity,
+ places=places,
+ places_names=place_names,
+ transitions=transitions,
+ arcs=arcs,
+ input_marker_groups=ordered_key_groups_input.get(activity, []),
+ output_marker_groups=ordered_key_groups_output.get(activity, []),
+ object_types=object_types,
+ p_input_binding=p_input_binding,
+ )
+
+ # create OCPN
+ ocpn = OCPetriNet(
+ places=places,
+ transitions=transitions,
+ arcs=arcs,
+ )
+
+ return ocpn
+
+
+
+def build_ordered_key_groups(activities, marker_groups):
+ """
+ Builds a hierarchy of object type groups, key groups and markers for each activity in the given list of activities.
+ Object type groups are ordered by object type name.
+ Key groups are ordered by the number of markers and by the number of markers with min_count=1 and max_count=1.
+ Markers in key groups are ordered by min_count and max_count, effectively putting markers with (1,1) first.
+
+ Parameters
+ ----------
+ activities: list
+ List of activities for which to build the key groups.
+ marker_groups: dict
+ Dictionary mapping activities to their corresponding marker groups.
+ The keys are activity names and the values are lists of marker groups.
+
+ Returns
+ -------
+ dict
+ A dictionary where keys are activities and values are lists of lists of tuples (object_type, object_type_group),
+ where each object_type_group is a sorted list of tuples (marker_key, marker_key_group),
+ where each marker_key_group is a sorted list of markers.
+ """
+ # build the hiearchy of key groups, object type groups and ks for each marker group
+ key_groups = {}
+ for a in activities:
+ key_groups[a] = []
+ # key_groups[a] is a list of marker groups (dicts)
+ # key: values of a marker group is object type: object type group
+ # key: values of object type groups are marker_key: key group
+ for marker_group in marker_groups.get(a, []):
+ marker_group_dict = {}
+ for marker in marker_group.markers:
+ # add the marker to the key group
+ marker_key = marker.marker_key
+ object_type = marker.object_type
+ if object_type not in marker_group_dict:
+ marker_group_dict[object_type] = {}
+ if marker_key not in marker_group_dict[object_type]:
+ marker_group_dict[object_type][marker_key] = []
+ marker_group_dict[object_type][marker_key].append(marker)
+ if marker_group_dict:
+ key_groups[a].append(marker_group_dict)
+
+
+ # sort the key groups
+ for a in activities:
+ for i, marker_group in enumerate(key_groups[a]):
+ for object_type in marker_group:
+ for marker_key in marker_group[object_type]:
+ # sort markers by c=(1,1) and then by min_count and max_count
+ marker_group[object_type][marker_key].sort(
+ key=lambda m: (m.min_count != 1, m.max_count != 1, m.min_count, m.max_count)
+ )
+ # sort key groups where key groups are ordered by the number of markers.
+ # Of the same number, key groups with more markers with c=(1,1) come first,
+ # effectively putting key groups with size 1 with 1 marker with c=(1,1) first
+ marker_group[object_type] = sorted(
+ marker_group[object_type].items(),
+ key=lambda x: (
+ len(x[1]), # fewer markers first
+ -sum(
+ 1 for m in x[1] if m.min_count == 1 and m.max_count == 1
+ ), # more (1,1) markers first
+ ),
+ )
+ # sort the object type groups by alphabetical order of object types
+ marker_group = sorted(
+ marker_group.items(), key=lambda x: x[0] # sort by object type name
+ )
+ key_groups[a][i] = marker_group
+ # marker groups for an activity do not need to be sorted
+ return key_groups
+
+
+def transform_activity(
+ places,
+ places_names,
+ transitions,
+ arcs,
+ activity,
+ input_marker_groups,
+ output_marker_groups,
+ object_types,
+ p_input_binding
+):
+ """
+ Creates the necessary places, transitions, and arcs for an activity in the OCPN.
+
+ Parameters
+ ----------
+ places: set
+ Set of places in the OCPN.
+ places_names: set
+ Set of place names in the OCPN to avoid duplications.
+ transitions: set
+ Set of transitions in the OCPN.
+ arcs: set
+ Set of arcs in the OCPN.
+ activity: str
+ The name of the activity to transform.
+ input_marker_groups: list
+ List of input marker groups for the activity, where each marker group is a list of object type groups.
+ output_marker_groups: list
+ List of output marker groups for the activity, where each marker group is a list of object type groups.
+ object_types: set
+ Set of all object types in the OCPN.
+ p_input_binding: OCPetriNet.Place
+ The input binding place for the activity construct.
+ """
+ is_start = activity.startswith("START_")
+ if is_start:
+ assert not input_marker_groups, f"Start activity {activity} is a START activity and must not have input marker groups."
+ is_end = activity.startswith("END_")
+ if is_end:
+ assert not output_marker_groups, f"End activity {activity} is an END activity and must not have output marker groups."
+
+ # transition
+ t = OCPetriNet.Transition(name=activity, label=activity)
+ transitions.add(t)
+
+
+ # input and output places
+ non_variable_object_types, variable_object_types = get_activity_object_types(
+ object_types, input_marker_groups, output_marker_groups
+ )
+
+
+ for object_type in non_variable_object_types | variable_object_types:
+ is_variable = object_type in variable_object_types
+
+ p_i = add_place(
+ OCPetriNet.Place(
+ name=label_activity_place(activity, True, object_type),
+ object_type=object_type,
+ ),
+ places,
+ places_names
+ )
+ p_o = add_place(
+ OCPetriNet.Place(
+ name=label_activity_place(activity, False, object_type),
+ object_type=object_type,
+ ),
+ places,
+ places_names
+ )
+
+ # arcs for input and output places
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_i,
+ target=t,
+ object_type=object_type,
+ is_variable=is_variable,
+ ),
+ arcs
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t,
+ target=p_o,
+ object_type=object_type,
+ is_variable=is_variable,
+ ),
+ arcs
+ )
+
+ # binding places
+ if not is_start:
+ p_i_t = add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{activity}_input",
+ object_type=BINDING_OBJECT_TYPE
+ ),
+ places,
+ places_names,
+ )
+ if not is_end:
+ p_o_t = add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{activity}_output",
+ object_type=BINDING_OBJECT_TYPE
+ ),
+ places,
+ places_names,
+ )
+
+ # arcs for binding places
+ if is_start:
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t,
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ arcs
+ )
+ else:
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_i_t,
+ target=t,
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ arcs
+ )
+ if is_end:
+ add_arc(
+ OCPetriNet.Arc(
+ source=t,
+ target=p_input_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ arcs
+ )
+ else:
+ add_arc(
+ OCPetriNet.Arc(
+ source=t,
+ target=p_o_t,
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ arcs
+ )
+
+ # add marker groups
+ for marker_group in input_marker_groups:
+ transform_marker_group(
+ activity=activity,
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ marker_group=marker_group,
+ p_input_binding=p_input_binding,
+ p_output_binding=p_i_t,
+ is_output_marker_group=False,
+ )
+ for marker_group in output_marker_groups:
+ transform_marker_group(
+ activity=activity,
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ marker_group=marker_group,
+ p_input_binding=p_o_t,
+ p_output_binding=p_input_binding,
+ is_output_marker_group=True,
+ )
+
+
+
+
+def get_activity_object_types(object_types, input_marker_groups, output_marker_groups):
+ """
+ Returns a set of non-variable object types and a set of variable object types for the given marker groups.
+ Non-variable object types are those where exactly one object of that type is involved in every firing of the activity.
+
+ Parameters
+ ----------
+ object_types: set
+ Set of all object types in the OCPN.
+ input_marker_groups: list
+ List of input marker groups for the activity, where each marker group is a list of object type groups.
+ output_marker_groups: list
+ List of output marker groups for the activity, where each marker group is a list of object type groups.
+
+ Returns
+ -------
+ tuple
+ A tuple containing two sets:
+ - The first set contains non-variable object types.
+ - The second set contains variable object types.
+ """
+ found_object_types = set()
+ # all object types are non-variable unless found otherwise
+ non_variable_object_types = {ot: True for ot in object_types}
+
+ for marker_group in input_marker_groups + output_marker_groups:
+ for object_type in object_types:
+ # Find object type group in the marker_group
+ # (needs to be done like this to catch object types only present in input or output markers)
+ matches = [otg for otg in marker_group if otg[0] == object_type]
+ if len(matches) > 1:
+ raise ValueError(f"More than one object type group found for object type {object_type} in marker_group.")
+ object_type_group = matches[0] if matches else (object_type, [])
+
+ object_type = object_type_group[0]
+ if matches:
+ found_object_types.add(object_type)
+ markers = [m for key_group in object_type_group[1] for m in key_group[1]]
+ # non-variable object types have exactly one marker in its object type group and its cardinalities are (1,1)
+ if not (
+ len(markers) == 1
+ and markers[0].min_count == 1
+ and markers[0].max_count == 1
+ ):
+ # not a non-variable object type
+ non_variable_object_types[object_type] = False
+
+ variable_object_types = set(
+ ot for ot in found_object_types if not non_variable_object_types[ot]
+ )
+ non_variable_object_types = set(
+ ot for ot in found_object_types if non_variable_object_types[ot]
+ )
+
+ return non_variable_object_types, variable_object_types
+
+
+def transform_marker_group(
+ activity,
+ places,
+ places_names,
+ transitions,
+ arcs,
+ marker_group,
+ p_input_binding,
+ p_output_binding,
+ is_output_marker_group,
+):
+ """
+ Transforms a marker group into a construct of places, transitions, and arcs in the OCPN.
+ Places, transitions, and arcs are updated to include the marker group.
+
+ Parameters
+ ----------
+ activity: str
+ The name of the activity which the marker group belongs to.
+ places: set
+ Set of places in the OCPN.
+ places_names: set
+ Set of place names in the OCPN to avoid duplications.
+ transitions: set
+ Set of transitions in the OCPN.
+ arcs: set
+ Set of arcs in the OCPN.
+ marker_group: list
+ The marker group to transform, which is a list of object type groups (tuples of object type and list of key groups).
+ p_input_binding: OCPetriNet.Place
+ The input binding place for the marker group construct.
+ p_output_binding: OCPetriNet.Place
+ The output binding place for the marker group construct.
+ is_output_marker_group: bool
+ Indicates if the marker group is an output marker group (True) or an input marker group (False).
+ """
+ silent_id = get_next_id()
+ p_b_i = p_input_binding
+ p_b_o = (
+ p_output_binding
+ if len(marker_group) == 1
+ else add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_1",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ )
+ for i, object_type_group in enumerate(marker_group):
+ # create construct
+
+ if is_output_marker_group:
+ transform_output_object_type_group(
+ activity=activity,
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ object_type_group=object_type_group,
+ p_input_binding=p_b_i,
+ p_output_binding=p_b_o,
+ )
+ else:
+ transform_input_object_type_group(
+ activity=activity,
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ object_type_group=object_type_group,
+ p_input_binding=p_b_i,
+ p_output_binding=p_b_o,
+ )
+
+ # next input and output binding places
+ p_b_i = p_b_o
+ # for last object type group, p_output_binding is used. We check for >= in case len is 1.
+ p_b_o = (
+ p_output_binding
+ if (i >= len(marker_group) - 2)
+ else add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_{i + 2}",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ )
+
+
+def transform_input_object_type_group(
+ activity,
+ places,
+ places_names,
+ transitions,
+ arcs,
+ object_type_group,
+ p_input_binding,
+ p_output_binding,
+):
+ """
+ Transforms an object type group of an input marker group into a construct of places, transitions, and arcs in the OCPN.
+ Places, transitions, and arcs are updated to include the object type group.
+ For input marker groups, we treat all keys as unique.
+
+ Parameters
+ ----------
+ activity: str
+ The name of the activity which the object type group belongs to.
+ places: set
+ Set of places in the OCPN.
+ places_names: set
+ Set of place names in the OCPN to avoid duplications.
+ transitions: set
+ Set of transitions in the OCPN.
+ arcs: set
+ Set of arcs in the OCPN.
+ object_type_group: (object_type, list)
+ The object type group to transform, which is a tuple of the object type and a sorted list of key groups.
+ p_input_binding: OCPetriNet.Place
+ The input binding place for the object type group construct.
+ p_output_binding: OCPetriNet.Place
+ The output binding place for the object type group construct.
+ """
+ silent_id = get_next_id()
+ # we skip the key groups for input marker groups, as we ignore input marker keys
+ # grab all markers of the object type group
+ markers = [marker for key_group in object_type_group[1] for marker in key_group[1]]
+ # sort them by by c=(1,1) and then by min_count and max_count
+ markers.sort(key=lambda m: (m.min_count != 1, m.max_count != 1, m.min_count, m.max_count))
+
+ # proceed with the construct
+ ot = object_type_group[0]
+ p_b_i = p_input_binding
+ p_b_o = (
+ p_output_binding
+ if len(markers) == 1
+ else add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_1",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ )
+ for i, marker in enumerate(markers):
+ # transform the marker
+ # input and output place
+ pi = add_place(
+ OCPetriNet.Place(
+ name=label_arc_place(marker.related_activity, activity, ot),
+ object_type=ot,
+ ),
+ places,
+ places_names,
+ )
+ po = add_place(
+ OCPetriNet.Place(
+ name=label_activity_place(activity, True, ot), object_type=ot
+ ),
+ places,
+ places_names,
+ )
+ # create construct
+ transform_marker(
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ marker=marker,
+ p_input=pi,
+ p_output=po,
+ p_input_binding=p_b_i,
+ p_output_binding=p_b_o,
+ is_output_marker=False,
+ key_group_length=1, # does not matter for input markers
+ is_last_key_group=True, # does not matter for input markers
+ is_first_marker=i==0
+ )
+
+ # next input and output binding places
+ p_b_i = p_b_o
+ # for last key group, p_output_binding is used. We check for >= in case len is 1.
+ p_b_o = (
+ p_output_binding
+ if (i >= len(markers) - 2)
+ else add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_{i + 2}",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ )
+
+
+def transform_output_object_type_group(
+ activity,
+ places,
+ places_names,
+ transitions,
+ arcs,
+ object_type_group,
+ p_input_binding,
+ p_output_binding,
+):
+ """
+ Transforms an object type group of an output marker group into a construct of places, transitions, and arcs in the OCPN.
+ Places, transitions, and arcs are updated to include the object type group.
+
+ Parameters
+ ----------
+ activity: str
+ The name of the activity which the object type group belongs to.
+ places: set
+ Set of places in the OCPN.
+ places_names: set
+ Set of place names in the OCPN to avoid duplications.
+ transitions: set
+ Set of transitions in the OCPN.
+ arcs: set
+ Set of arcs in the OCPN.
+ object_type_group: (object_type, list)
+ The object type group to transform, which is a tuple of the object type and a sorted list of key groups.
+ p_input_binding: OCPetriNet.Place
+ The input binding place for the object type group construct.
+ p_output_binding: OCPetriNet.Place
+ The output binding place for the object type group construct.
+ """
+ silent_id = get_next_id()
+ p_b_i = p_input_binding
+ p_b_o = (
+ p_output_binding
+ if len(object_type_group[1]) == 1
+ else add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_1",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ )
+ for i, key_group in enumerate(object_type_group[1]):
+ # transform the key group
+ is_last_key_group = i == len(object_type_group[1]) - 1
+ transform_output_key_group(
+ activity=activity,
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ key_group=key_group,
+ p_input_binding=p_b_i,
+ p_output_binding=p_b_o,
+ is_last_key_group=is_last_key_group,
+ )
+
+ # next input and output binding places
+ p_b_i = p_b_o
+ # for last key group, p_output_binding is used. We check for >= in case len is 1.
+ p_b_o = (
+ p_output_binding
+ if (i >= len(object_type_group[1]) - 2)
+ else add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_{i + 2}",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ )
+
+
+def transform_output_key_group(
+ activity,
+ places,
+ places_names,
+ transitions,
+ arcs,
+ key_group,
+ p_input_binding,
+ p_output_binding,
+ is_last_key_group,
+ p_input=None,
+):
+ """
+ Transforms a key group of an output marker group into a construct of places, transitions, and arcs in the OCPN.
+ Places, transitions, and arcs are updated to include the key group.
+
+ Parameters
+ ----------
+ activity: str
+ The name of the activity which the key group belongs to.
+ places: set
+ Set of places in the OCPN.
+ places_names: set
+ Set of place names in the OCPN to avoid duplications.
+ transitions: set
+ Set of transitions in the OCPN.
+ arcs: set
+ Set of arcs in the OCPN.
+ key_group: (marker_key, list)
+ The key group to transform, which is a tupel of the marker key and a sorted list of markers.
+ p_input_binding: OCPetriNet.Place
+ The input binding place for the key group construct.
+ p_output_binding: OCPetriNet.Place
+ The output binding place for the key group construct.
+ is_last_key_group: bool
+ Indicates if the key group is the last key group of its object type group.
+ p_input: OCPetriNet.Place, optional
+ The input place for case 2 of this construct. Only to be set when recursively calling this function from case 3.
+ """
+ ot = key_group[1][0].object_type
+ # 3 cases can occur
+ if len(key_group[1]) == 1:
+ # case 1: key group with one marker
+ marker = key_group[1][0]
+ # input and output place
+ pi = add_place(
+ OCPetriNet.Place(
+ name=label_activity_place(activity, False, ot), object_type=ot
+ ),
+ places,
+ places_names,
+ )
+ po = add_place(
+ OCPetriNet.Place(
+ name=label_arc_place(activity, marker.related_activity, ot),
+ object_type=ot,
+ ),
+ places,
+ places_names,
+ )
+ # create construct
+ transform_marker(
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ marker=marker,
+ p_input=pi,
+ p_output=po,
+ p_input_binding=p_input_binding,
+ p_output_binding=p_output_binding,
+ is_output_marker=True,
+ key_group_length=len(key_group[1]),
+ is_last_key_group=is_last_key_group,
+ is_first_marker=True
+ )
+ else:
+ silent_id = get_next_id()
+ if is_last_key_group:
+ # case 2: key group with multiple markers, last key group of its object type group
+ p_b_i = p_input_binding
+ p_b_o = add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_1",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+
+ for i, marker in enumerate(key_group[1]):
+ # input and output place
+ pi = (
+ p_input
+ if p_input is not None
+ else add_place( # p_input is set when recursively calling this function from case 3
+ OCPetriNet.Place(
+ name=label_activity_place(activity, False, ot),
+ object_type=ot,
+ ),
+ places,
+ places_names,
+ )
+ )
+ po = add_place(
+ OCPetriNet.Place(
+ name=label_arc_place(activity, marker.related_activity, ot),
+ object_type=ot,
+ ),
+ places,
+ places_names,
+ )
+ # create construct
+ transform_marker(
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ marker=marker,
+ p_input=pi,
+ p_output=po,
+ p_input_binding=p_b_i,
+ p_output_binding=p_b_o,
+ is_output_marker=True,
+ key_group_length=len(key_group[1]),
+ is_last_key_group=is_last_key_group,
+ is_first_marker=i == 0,
+ )
+
+ # next input and output binding places
+ p_b_i = p_b_o
+ # for last marker, p_output_binding is used
+ p_b_o = (
+ p_output_binding
+ if i >= (len(key_group[1]) - 2)
+ else add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_{i + 2}",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ )
+ else:
+ # case 3: key group with multiple markers, not the last key group of its object type group
+ # this is the same as case 2 with some extra on top, so we create the extra and thenn call case 2
+
+ # places
+ px = add_place(
+ OCPetriNet.Place(
+ name=f"p#{silent_id}_X",
+ object_type=ot,
+ ),
+ places,
+ places_names,
+ )
+ p_alpha = add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_alpha",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ p_beta = add_place(
+ OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}_beta",
+ object_type=BINDING_OBJECT_TYPE,
+ ),
+ places,
+ places_names,
+ )
+ # transitions
+ t1 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_1",
+ )
+ t2 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_2",
+ )
+ transitions.update([t1, t2])
+ # arcs
+ p_a_o_ot = add_place(
+ OCPetriNet.Place(
+ name=label_activity_place(activity, False, ot),
+ object_type=ot,
+ ),
+ places,
+ places_names,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_a_o_ot,
+ target=t1,
+ object_type=ot,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_a_o_ot,
+ object_type=ot,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=px,
+ object_type=ot,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_a_o_ot,
+ target=t2,
+ object_type=ot,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=px,
+ object_type=ot,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t2,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_alpha,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_alpha,
+ target=t1,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_beta,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+
+ # call case 2 by setting is_last_key_group to True, provide px as input place
+ transform_output_key_group(
+ activity=activity,
+ places=places,
+ places_names=places_names,
+ transitions=transitions,
+ arcs=arcs,
+ key_group=key_group,
+ p_input_binding=p_beta,
+ p_output_binding=p_output_binding,
+ is_last_key_group=True,
+ p_input=px,
+ )
+
+
+def transform_marker(
+ places,
+ places_names,
+ transitions,
+ arcs,
+ marker,
+ p_input,
+ p_output,
+ p_input_binding,
+ p_output_binding,
+ is_output_marker,
+ key_group_length,
+ is_last_key_group,
+ is_first_marker
+):
+ """
+ Transforms a marker into a construct of places, transitions, and arcs in the OCPN.
+ Places, transitions, and arcs are updated to include the marker.
+
+ Parameters
+ ----------
+ places: set
+ Set of places in the OCPN.
+ places_names: set
+ Set of place names in the OCPN to which the place name will be added.
+ transitions: set
+ Set of transitions in the OCPN.
+ arcs: set
+ Set of arcs in the OCPN.
+ marker: Marker
+ The marker to transform.
+ p_input: OCPetriNet.Place
+ The input place for the marker construct.
+ p_output: OCPetriNet.Place
+ The output place for the marker construct.
+ p_input_binding: OCPetriNet.Place
+ The input binding place for the marker construct.
+ p_output_binding: OCPetriNet.Place
+ The output binding place for the marker construct.
+ is_output_marker: bool
+ True if the marker is part of an output marker group, False if it is part of an input marker group.
+ key_group_length: int
+ The length of the key group to which the marker belongs. Does not matter for input markers.
+ is_last_key_group: bool
+ Indicates if the marker is in the last key group of its object type group. Does not matter for input markers.
+ is_first_marker: bool
+ Indicates if the marker is the first marker in its input object type group. Does not matter for output markers.
+ """
+ # id to avoid name clashes
+ silent_id = get_next_id()
+
+ # 6 cases can occur
+ if marker.min_count == 1 and marker.max_count == 1:
+ if is_output_marker and not is_last_key_group and key_group_length == 1:
+ # case 1: (1,1) marker with duplication
+ # places
+ for p in [p_input, p_output, p_input_binding, p_output_binding]:
+ add_place(p, places, places_names)
+ # transitions
+ t1 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_1",
+ )
+ t2 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_2",
+ )
+ transitions.update([t1, t2])
+ # arcs
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t1,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_input,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t2,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t1,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t2,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ elif (not is_output_marker) and (not is_first_marker):
+ # case 2: (1,1) marker with unification
+ # places
+ for p in [p_input, p_output, p_input_binding, p_output_binding]:
+ add_place(p, places, places_names)
+ # transitions
+ t1 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_1",
+ )
+ t2 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_2",
+ )
+ transitions.update([t1, t2])
+ # arcs
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t1,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_output,
+ target=t1,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t2,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t1,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t2,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ else:
+ # case 2: (1,1) marker without duplication/unification
+ # places
+ places.update([p_input, p_output, p_input_binding, p_output_binding])
+ # transitions
+ t = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}",
+ )
+ transitions.add(t)
+ # arcs
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ else:
+ # marker with min_count != 1 or max_count != 1
+ if is_output_marker and not is_last_key_group and key_group_length == 1:
+ # case 4: square marker with duplication
+ # places
+ px = OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}",
+ object_type=BINDING_OBJECT_TYPE,
+ )
+ places.update([p_input, p_output, p_input_binding, p_output_binding, px])
+ # transitions
+ t1 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_1",
+ )
+ t2 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_2",
+ )
+ transitions.update([t1, t2])
+ # arcs
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t1,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_input,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t2,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t2,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=px,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=px,
+ target=t1,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ elif (not is_output_marker) and (not is_first_marker):
+ # case 5: square marker with unification
+ # places
+ px = OCPetriNet.Place(
+ name=f"p{BINDING_OBJECT_TYPE}#{silent_id}",
+ object_type=BINDING_OBJECT_TYPE,
+ )
+ places.update([p_input, p_output, p_input_binding, p_output_binding, px])
+ # transitions
+ t1 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_1",
+ )
+ t2 = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}_2",
+ )
+ transitions.update([t1, t2])
+ # arcs
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t1,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_output,
+ target=t1,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t2,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t1,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t1,
+ target=px,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=px,
+ target=t2,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t2,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ else:
+ # case 6: square marker without duplication/unification
+ # places
+ places.update([p_input, p_output, p_input_binding, p_output_binding])
+ # transitions
+ t = OCPetriNet.Transition(
+ name=f"{SILENT_TRANSITION_PREFIX}#{silent_id}",
+ )
+ transitions.add(t)
+ # arcs
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input,
+ target=t,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t,
+ target=p_output,
+ object_type=marker.object_type,
+ is_variable=True,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=p_input_binding,
+ target=t,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+ add_arc(
+ OCPetriNet.Arc(
+ source=t,
+ target=p_output_binding,
+ object_type=BINDING_OBJECT_TYPE,
+ is_variable=False,
+ ),
+ arcs,
+ )
+
+
+def add_arc(arc, arcs):
+ """
+ Adds an arc to the OCPN and its source and target.
+
+ Parameters
+ ----------
+ arc: OCPetriNet.Arc
+ The arc to add to the OCPN.
+ arcs: set
+ Set of arcs in the OCPN to which the arc will be added.
+ """
+ arcs.add(arc)
+ arc.source.add_out_arc(arc)
+ arc.target.add_in_arc(arc)
+
+
+def add_place(place, places, places_names) -> OCPetriNet.Place:
+ """
+ Adds a place to the OCPN and its name to the set of place names.
+ Does not add the place if a place with the same name already exists in the OCPN.
+ Returns the place if it was added, otherwise returns the existing place.
+
+ Parameters
+ ----------
+ place: OCPetriNet.Place
+ The place to add to the OCPN.
+ places: set
+ Set of places in the OCPN to which the place will be added.
+ places_names: set
+ Set of place names in the OCPN to which the place name will be added.
+
+ Returns
+ -------
+ OCPetriNet.Place
+ The place that was added or the existing place if it was not added.
+ """
+ if place.name not in places_names:
+ places.add(place)
+ places_names.add(place.name)
+ return place
+ else:
+ # if the place already exists, return the existing place
+ for p in places:
+ if p.name == place.name:
+ return p
+ raise ValueError(f"Place with name {place.name} not found in places.")
+
+
+def label_activity_place(activity_name, is_input, object_type):
+ """
+ Returns the name for an input / output place of an activity.
+
+ Parameters
+ ----------
+ activity_name: str
+ The name of the activity.
+ is_input: bool
+ Indicates if the place is an input place (True) or an output place (False).
+ object_type: str
+ The object type of the activity.
+
+ Returns
+ -------
+ str
+ The name of the place.
+ """
+ prefix = f"p_{activity_name}_i" if is_input else f"p_{activity_name}_o"
+ return f"{prefix}_{object_type}"
+
+
+def label_arc_place(source, target, object_type):
+ """
+ Returns the name for the place corresponding to an arc between two activities.
+
+ Parameters
+ ----------
+ source: str
+ The name of the source activity.
+ target: str
+ The name of the target activity.
+ object_type: str
+ The object type of the arc.
+ """
+ return f"p_arc({source},{target})_{object_type}"
+
+
+def get_next_id():
+ """
+ Returns a unique id for a silent transition, starting from 0.
+ """
+ # initialize on first call
+ if not hasattr(get_next_id, "counter"):
+ get_next_id.counter = 0
+ current = get_next_id.counter
+ get_next_id.counter += 1
+ return current
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6064fba761c0c06812769432e24769850696b107
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/__init__.py
@@ -0,0 +1,32 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+
+from pm4py.objects.ocel import (
+ constants,
+ obj,
+ exporter,
+ importer,
+ util,
+ validation,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/constants.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..78ad92b301c12fb8a07ed04880f41415eb0e58b8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/constants.py
@@ -0,0 +1,66 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+PARAM_EVENT_ID = "param:event:id"
+PARAM_EVENT_ACTIVITY = "param:event:activity"
+PARAM_EVENT_TIMESTAMP = "param:event:timestamp"
+PARAM_OBJECT_ID = "param:object:id"
+PARAM_OBJECT_TYPE = "param:object:type"
+PARAM_OBJECT_TYPE_PREFIX_EXTENDED = "param:object:type:prefix:extended"
+PARAM_QUALIFIER = "param:qualifier"
+PARAM_CHNGD_FIELD = "param:chngfield"
+
+DEFAULT_EVENT_ID = "ocel:eid"
+DEFAULT_EVENT_ACTIVITY = "ocel:activity"
+DEFAULT_EVENT_TIMESTAMP = "ocel:timestamp"
+DEFAULT_OBJECT_ID = "ocel:oid"
+DEFAULT_OBJECT_TYPE = "ocel:type"
+DEFAULT_OBJECT_TYPE_PREFIX_EXTENDED = "ocel:type:"
+DEFAULT_QUALIFIER = "ocel:qualifier"
+DEFAULT_CHNGD_FIELD = "ocel:field"
+
+OCEL_PREFIX = "ocel:"
+OCEL_EVENTS_KEY = "ocel:events"
+OCEL_OBJECTS_KEY = "ocel:objects"
+OCEL_ID_KEY = "ocel:id"
+OCEL_OMAP_KEY = "ocel:omap"
+OCEL_TYPED_OMAP_KEY = "ocel:typedOmap"
+OCEL_VMAP_KEY = "ocel:vmap"
+OCEL_OVMAP_KEY = "ocel:ovmap"
+OCEL_O2O_KEY = "ocel:o2o"
+OCEL_OBJCHANGES_KEY = "ocel:objectChanges"
+OCEL_EVTYPES_KEY = "ocel:eventTypes"
+OCEL_OBJTYPES_KEY = "ocel:objectTypes"
+OCEL_GLOBAL_LOG = "ocel:global-log"
+OCEL_GLOBAL_LOG_ATTRIBUTE_NAMES = "ocel:attribute-names"
+OCEL_GLOBAL_LOG_OBJECT_TYPES = "ocel:object-types"
+OCEL_GLOBAL_LOG_VERSION = "ocel:version"
+OCEL_GLOBAL_LOG_ORDERING = "ocel:ordering"
+OCEL_GLOBAL_EVENT = "ocel:global-event"
+OCEL_GLOBAL_OBJECT = "ocel:global-object"
+
+PARAM_INTERNAL_INDEX = "param:internal:index"
+DEFAULT_INTERNAL_INDEX = "@@index"
+
+DEFAULT_GLOBAL_EVENT = {"ocel:activity": "__INVALID__"}
+DEFAULT_GLOBAL_OBJECT = {"ocel:type": "__INVALID__"}
+DEFAULT_ORDERING = "timestamp"
+CURRENT_VERSION = "1.0"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3dadd229aa38cf21315aa17fd139ed780885957
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/__init__.py
@@ -0,0 +1,29 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter import bundled, util, csv, jsonocel
+import importlib.util
+
+if importlib.util.find_spec("lxml"):
+ from pm4py.objects.ocel.exporter import xmlocel
+
+if importlib.util.find_spec("sqlite3"):
+ from pm4py.objects.ocel.exporter import sqlite
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a2f3c06991d69d182fe9d075cd2cb228f18b147
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.bundled import exporter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..e31302a11f5ae9d592ea6fac9b16e8596e273c86
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/exporter.py
@@ -0,0 +1,45 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.exporter.bundled.variants import ocel20
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ OCEL20 = ocel20
+
+
+def apply(
+ ocel: OCEL,
+ target_path: str,
+ variant=Variants.OCEL20,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Exports an OCEL 2.0 log to the bundled CSV/Parquet format.
+ """
+ return exec_utils.get_variant(variant).apply(
+ ocel, target_path, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fdeb5e6e060f7548aac6d8e8e452e227185d5e9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.bundled.variants import ocel20
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8fce458b09cb4f13a5e72af09f18b6c40f3b858
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/bundled/variants/ocel20.py
@@ -0,0 +1,646 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any, List, Tuple
+import codecs
+import csv
+import datetime as dt
+from decimal import Decimal
+import io
+import json
+import math
+import os
+import zipfile
+
+import numpy as np
+import pandas as pd
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import constants as pm4_constants, exec_utils, pandas_utils
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ ENCODING = "encoding"
+ STORAGE_FORMAT = "storage_format"
+
+
+_SAFE_FILENAME_BYTES = set(
+ b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-"
+)
+
+
+def _require_utf8(encoding: str) -> str:
+ try:
+ normalized = codecs.lookup(encoding).name
+ except LookupError as exc:
+ raise ValueError("Unknown OCEL bundle encoding '%s'." % encoding) from exc
+ if normalized != "utf-8":
+ raise ValueError("OCEL bundle metadata and CSV tables must use UTF-8 encoding.")
+ return "utf-8"
+
+
+def _percent_encode(value: str) -> str:
+ encoded = []
+ for byte in value.encode("utf-8"):
+ encoded.append(chr(byte) if byte in _SAFE_FILENAME_BYTES else "%%%02X" % byte)
+ return "".join(encoded)
+
+
+def _is_null(value) -> bool:
+ return clean_dataframes.is_null(value)
+
+
+def _values_equal(left: Any, right: Any) -> bool:
+ if (
+ isinstance(left, (int, float, np.integer, np.floating))
+ and not isinstance(left, (bool, np.bool_))
+ and isinstance(right, (int, float, np.integer, np.floating))
+ and not isinstance(right, (bool, np.bool_))
+ ):
+ return Decimal(str(left)) == Decimal(str(right))
+ return type(left) is type(right) and left == right
+
+
+def _attribute_columns(dataframe: pd.DataFrame, reserved: List[str]) -> List[str]:
+ columns = []
+ for column in dataframe.columns:
+ if column in reserved or str(column).startswith("ocel:"):
+ continue
+ if not isinstance(column, str) or not column:
+ raise ValueError("OCEL bundle attribute names must be non-empty strings.")
+ columns.append(column)
+ return columns
+
+
+def _primitive_type_from_values(values: List[Any]) -> str:
+ non_null = [value for value in values if not _is_null(value)]
+ if not non_null:
+ return "string"
+ if all(isinstance(value, (bool, np.bool_)) for value in non_null):
+ return "boolean"
+ if all(
+ isinstance(value, (int, np.integer))
+ and not isinstance(value, (bool, np.bool_))
+ for value in non_null
+ ):
+ return "integer"
+ if all(
+ isinstance(value, (int, float, np.integer, np.floating))
+ and not isinstance(value, (bool, np.bool_))
+ and math.isfinite(float(value))
+ for value in non_null
+ ):
+ return "float"
+ if all(
+ isinstance(value, (pd.Timestamp, dt.datetime, dt.date, np.datetime64))
+ for value in non_null
+ ):
+ return "time"
+ return "string"
+
+
+def _timestamp(value: Any, label: str) -> pd.Timestamp:
+ if _is_null(value):
+ raise ValueError("%s cannot be missing." % label)
+ try:
+ timestamp = value if isinstance(value, pd.Timestamp) else pd.Timestamp(value)
+ except BaseException as exc:
+ raise ValueError("%s is not a timestamp." % label) from exc
+ if timestamp.tzinfo is None or timestamp.utcoffset() is None:
+ timestamp = timestamp.tz_localize("UTC")
+ return timestamp.tz_convert("UTC")
+
+
+def _coerce_value(value: Any, primitive_type: str, label: str, optional: bool):
+ if _is_null(value):
+ if optional:
+ return None
+ raise ValueError("%s cannot be missing." % label)
+ value = clean_dataframes.normalize_value(value)
+ if primitive_type == "string":
+ if isinstance(value, (list, dict, tuple, set)):
+ raise ValueError("%s must be a scalar string value." % label)
+ return str(value)
+ if primitive_type == "integer":
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)):
+ raise ValueError("%s must be an integer." % label)
+ return int(value)
+ if primitive_type == "float":
+ if isinstance(value, (bool, np.bool_)) or not isinstance(
+ value, (int, float, np.integer, np.floating)
+ ):
+ raise ValueError("%s must be a floating-point number." % label)
+ value = float(value)
+ if not math.isfinite(value):
+ raise ValueError("%s must be finite." % label)
+ return value
+ if primitive_type == "boolean":
+ if not isinstance(value, (bool, np.bool_)):
+ raise ValueError("%s must be boolean." % label)
+ return bool(value)
+ return _timestamp(value, label)
+
+
+def _prepare_table(
+ dataframe: pd.DataFrame,
+ fixed: List[Tuple[str, str, bool]],
+ attributes: List[Tuple[str, str]],
+) -> pd.DataFrame:
+ expected = [name for name, _, _ in fixed] + [name for name, _ in attributes]
+ dataframe = dataframe.copy()
+ for column in expected:
+ if column not in dataframe.columns:
+ dataframe[column] = None
+ dataframe = dataframe[expected]
+ fixed_names = {name for name, _, _ in fixed}
+ type_by_name = {name: primitive_type for name, primitive_type, _ in fixed}
+ type_by_name.update(attributes)
+ allow_empty = {name for name, _, empty_allowed in fixed if empty_allowed}
+ for column in expected:
+ optional = column not in fixed_names
+ values = [
+ _coerce_value(value, type_by_name[column], column, optional)
+ for value in dataframe[column].tolist()
+ ]
+ if column in fixed_names and column not in allow_empty and any(value == "" for value in values):
+ raise ValueError("Fixed column '%s' cannot contain empty strings." % column)
+ dataframe[column] = pd.Series(
+ values, index=dataframe.index, dtype="object"
+ )
+ return dataframe
+
+
+def _csv_value(value: Any, primitive_type: str) -> str:
+ if value is None or _is_null(value):
+ return ""
+ if primitive_type == "boolean":
+ return "true" if value else "false"
+ if primitive_type == "time":
+ return _timestamp(value, "timestamp").isoformat()
+ if primitive_type == "integer":
+ return str(int(value))
+ if primitive_type == "float":
+ return repr(float(value))
+ return str(value)
+
+
+def _table_csv_bytes(
+ dataframe: pd.DataFrame,
+ fixed: List[Tuple[str, str, bool]],
+ attributes: List[Tuple[str, str]],
+ encoding: str,
+) -> bytes:
+ type_by_name = {name: primitive_type for name, primitive_type, _ in fixed}
+ type_by_name.update(attributes)
+ buffer = io.StringIO(newline="")
+ writer = csv.writer(buffer, dialect="excel", lineterminator="\r\n")
+ writer.writerow(dataframe.columns)
+ for row in dataframe.itertuples(index=False, name=None):
+ writer.writerow(
+ [_csv_value(value, type_by_name[column]) for column, value in zip(dataframe.columns, row)]
+ )
+ return buffer.getvalue().encode(encoding)
+
+
+def _arrow_type(primitive_type: str):
+ try:
+ import pyarrow as pa
+ except ImportError as exc:
+ raise ImportError(
+ "pyarrow is required for specification-compliant OCEL Parquet bundles."
+ ) from exc
+ return {
+ "string": pa.string(),
+ "integer": pa.int64(),
+ "float": pa.float64(),
+ "boolean": pa.bool_(),
+ "time": pa.timestamp("us", tz="UTC"),
+ }[primitive_type]
+
+
+def _table_parquet_bytes(
+ dataframe: pd.DataFrame,
+ fixed: List[Tuple[str, str, bool]],
+ attributes: List[Tuple[str, str]],
+) -> bytes:
+ try:
+ import pyarrow as pa
+ import pyarrow.parquet as pq
+ except ImportError as exc:
+ raise ImportError(
+ "pyarrow is required for specification-compliant OCEL Parquet bundles."
+ ) from exc
+ fields = [
+ pa.field(name, _arrow_type(primitive_type), nullable=False)
+ for name, primitive_type, _ in fixed
+ ] + [
+ pa.field(name, _arrow_type(primitive_type), nullable=True)
+ for name, primitive_type in attributes
+ ]
+ schema = pa.schema(fields)
+ arrays = []
+ for field in fields:
+ values = dataframe[field.name].tolist()
+ if pa.types.is_timestamp(field.type):
+ values = [
+ None
+ if value is None or _is_null(value)
+ else _timestamp(value, field.name).floor("us")
+ for value in values
+ ]
+ arrays.append(pa.array(values, type=field.type))
+ table = pa.Table.from_arrays(arrays, schema=schema)
+ buffer = io.BytesIO()
+ pq.write_table(
+ table,
+ buffer,
+ version="2.6",
+ coerce_timestamps="us",
+ allow_truncated_timestamps=False,
+ )
+ return buffer.getvalue()
+
+
+def _table_bytes(
+ dataframe: pd.DataFrame,
+ storage_format: str,
+ fixed: List[Tuple[str, str, bool]],
+ attributes: List[Tuple[str, str]],
+ encoding: str,
+) -> bytes:
+ dataframe = _prepare_table(dataframe, fixed, attributes)
+ if storage_format == "csv":
+ return _table_csv_bytes(dataframe, fixed, attributes, encoding)
+ return _table_parquet_bytes(dataframe, fixed, attributes)
+
+
+def _write_archive(target_path: str, files: Dict[str, bytes]):
+ with zipfile.ZipFile(target_path, "w", zipfile.ZIP_DEFLATED) as archive:
+ for path, content in files.items():
+ archive.writestr(path, content)
+
+
+def _cleanup_known_bundle_files(root_path: str):
+ for relative_dir in ("events", "objects", "object_changes", "relations"):
+ full_dir = os.path.join(root_path, relative_dir)
+ if not os.path.isdir(full_dir):
+ continue
+ for filename in os.listdir(full_dir):
+ if filename.endswith(".csv") or filename.endswith(".parquet"):
+ os.remove(os.path.join(full_dir, filename))
+
+
+def _write_directory(target_path: str, files: Dict[str, bytes]):
+ os.makedirs(target_path, exist_ok=True)
+ _cleanup_known_bundle_files(target_path)
+ for path, content in files.items():
+ full_path = os.path.join(target_path, *path.split("/"))
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
+ with open(full_path, "wb") as file:
+ file.write(content)
+
+
+def _normalized_string(value: Any, label: str, allow_empty: bool = False) -> str:
+ if _is_null(value):
+ if allow_empty:
+ return ""
+ raise ValueError("%s cannot be missing." % label)
+ value = str(clean_dataframes.normalize_value(value))
+ if not value and not allow_empty:
+ raise ValueError("%s cannot be empty." % label)
+ return value
+
+
+def _require_unique(values: List[str], label: str):
+ if len(values) != len(set(values)):
+ raise ValueError("OCEL bundle %s identifiers must be unique." % label)
+
+
+def _relation_dataframe(records: List[Dict[str, Any]], columns: List[str]) -> pd.DataFrame:
+ return pandas_utils.instantiate_dataframe(records, columns=columns)
+
+
+def apply(ocel: OCEL, target_path: str, parameters: Optional[Dict[Any, Any]] = None):
+ """Exports an OCEL 2.0 log to the bundled CSV/Parquet format."""
+ if parameters is None:
+ parameters = {}
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+ encoding = _require_utf8(encoding)
+ storage_format = exec_utils.get_param_value(Parameters.STORAGE_FORMAT, parameters, "parquet")
+ if storage_format not in {"csv", "parquet"}:
+ raise ValueError("OCEL bundle storage format must be 'csv' or 'parquet'.")
+
+ event_id = exec_utils.get_param_value(Parameters.EVENT_ID, parameters, ocel.event_id_column)
+ event_activity = exec_utils.get_param_value(Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity)
+ event_timestamp = exec_utils.get_param_value(Parameters.EVENT_TIMESTAMP, parameters, ocel.event_timestamp)
+ object_id = exec_utils.get_param_value(Parameters.OBJECT_ID, parameters, ocel.object_id_column)
+ object_type = exec_utils.get_param_value(Parameters.OBJECT_TYPE, parameters, ocel.object_type_column)
+ qualifier = exec_utils.get_param_value(Parameters.QUALIFIER, parameters, ocel.qualifier)
+ changed_field = exec_utils.get_param_value(Parameters.CHANGED_FIELD, parameters, ocel.changed_field)
+
+ events = ocel.events.copy()
+ objects = ocel.objects.copy().reset_index(drop=True)
+ relations = ocel.relations.copy()
+ o2o = ocel.o2o.copy()
+ changes = ocel.object_changes.copy()
+ for dataframe, required, label in (
+ (events, [event_id, event_activity, event_timestamp], "events"),
+ (objects, [object_id, object_type], "objects"),
+ (relations, [event_id, object_id, qualifier], "E2O relations"),
+ (o2o, [object_id, object_id + "_2", qualifier], "O2O relations"),
+ (changes, [object_id, event_timestamp, changed_field], "object changes"),
+ ):
+ missing = [column for column in required if column not in dataframe.columns]
+ if missing:
+ raise ValueError("OCEL %s are missing columns: %s." % (label, ", ".join(missing)))
+
+ event_ids = [_normalized_string(value, "event id") for value in events[event_id].tolist()]
+ object_ids = [_normalized_string(value, "object id") for value in objects[object_id].tolist()]
+ _require_unique(event_ids, "event")
+ _require_unique(object_ids, "object")
+ events[event_id] = event_ids
+ objects[object_id] = object_ids
+ events[event_activity] = [
+ _normalized_string(value, "event type") for value in events[event_activity].tolist()
+ ]
+ objects[object_type] = [
+ _normalized_string(value, "object type") for value in objects[object_type].tolist()
+ ]
+ event_id_set = set(event_ids)
+ object_type_by_id = dict(zip(object_ids, objects[object_type].tolist()))
+ object_index_by_id = dict(zip(object_ids, objects.index))
+
+ event_attribute_columns = _attribute_columns(
+ events, [event_id, event_activity, event_timestamp]
+ )
+ object_attribute_columns = _attribute_columns(objects, [object_id, object_type])
+ change_attribute_columns = _attribute_columns(
+ changes, [object_id, object_type, event_timestamp, changed_field]
+ )
+ if set(event_attribute_columns).intersection({"ocel_id", "ocel_time"}):
+ raise ValueError("Event attribute name collides with a fixed bundle column.")
+ if set(object_attribute_columns + change_attribute_columns).intersection(
+ {"ocel_id", "ocel_time", "ocel_changed_field"}
+ ):
+ raise ValueError("Object attribute name collides with a fixed bundle column.")
+
+ normalized_changes = []
+ change_keys = {}
+ for record in changes.to_dict(orient="records"):
+ oid = _normalized_string(record.get(object_id), "object-change id")
+ if oid not in object_type_by_id:
+ raise ValueError("Object change references unknown object '%s'." % oid)
+ record_type = record.get(object_type, object_type_by_id[oid])
+ if not _is_null(record_type) and str(record_type) != object_type_by_id[oid]:
+ raise ValueError("Object change type does not match object '%s'." % oid)
+ field = _normalized_string(record.get(changed_field), "changed field")
+ if field not in record or _is_null(record.get(field)):
+ raise ValueError("Object change for '%s' has no value for '%s'." % (oid, field))
+ populated_fields = [
+ column
+ for column in change_attribute_columns
+ if column in record and not _is_null(record.get(column))
+ ]
+ if populated_fields != [field]:
+ raise ValueError("An object-change row must assign exactly its changed field.")
+ normalized_timestamp = _timestamp(
+ record.get(event_timestamp), "object-change timestamp"
+ )
+ value = clean_dataframes.normalize_value(record.get(field))
+ if normalized_timestamp.value == 0:
+ # time-0 assignments are initial values and live in the object table only
+ if field not in objects.columns:
+ objects[field] = None
+ object_attribute_columns.append(field)
+ row_index = object_index_by_id[oid]
+ existing = objects.at[row_index, field]
+ if not _is_null(existing) and not _values_equal(
+ clean_dataframes.normalize_value(existing), value
+ ):
+ raise ValueError(
+ "Object '%s' has conflicting time-0 values for attribute '%s'."
+ % (oid, field)
+ )
+ objects.at[row_index, field] = value
+ continue
+ key = (oid, normalized_timestamp.value, field)
+ if key in change_keys:
+ if not _values_equal(change_keys[key], value):
+ raise ValueError("Object attribute has conflicting values at one timestamp.")
+ raise ValueError("Duplicate object attribute assignment cannot be exported.")
+ change_keys[key] = value
+ normalized = dict(record)
+ normalized[object_id] = oid
+ normalized[object_type] = object_type_by_id[oid]
+ normalized[event_timestamp] = normalized_timestamp
+ normalized[changed_field] = field
+ normalized_changes.append(normalized)
+ if field not in change_attribute_columns:
+ change_attribute_columns.append(field)
+ changes = pandas_utils.instantiate_dataframe(normalized_changes) if normalized_changes else changes.iloc[0:0].copy()
+
+ extension = storage_format
+ meta = {
+ "ocelVersion": "2.0",
+ "bundleFormatVersion": "1.0",
+ "storageFormat": storage_format,
+ "eventTypes": {},
+ "objectTypes": {},
+ "relations": {
+ "e2o": "relations/e2o.%s" % extension,
+ "o2o": "relations/o2o.%s" % extension,
+ },
+ }
+ table_specs = {}
+
+ for event_type_name in sorted(set(events[event_activity].tolist())):
+ selected = events[events[event_activity] == event_type_name].copy()
+ attributes = [
+ column
+ for column in event_attribute_columns
+ if selected[column].notna().any()
+ ]
+ attribute_types = [
+ (column, _primitive_type_from_values(selected[column].tolist()))
+ for column in attributes
+ ]
+ table_path = "events/event_%s.%s" % (_percent_encode(event_type_name), extension)
+ table = selected[[event_id, event_timestamp] + attributes].rename(
+ columns={event_id: "ocel_id", event_timestamp: "ocel_time"}
+ )
+ fixed = [("ocel_id", "string", False), ("ocel_time", "time", False)]
+ table_specs[table_path] = (table, fixed, attribute_types)
+ meta["eventTypes"][event_type_name] = {
+ "file": table_path,
+ "attributes": [
+ {"name": name, "type": primitive_type}
+ for name, primitive_type in attribute_types
+ ],
+ }
+
+ for object_type_name in sorted(set(objects[object_type].tolist())):
+ selected = objects[objects[object_type] == object_type_name].copy()
+ type_changes = (
+ changes[changes[object_type] == object_type_name].copy()
+ if len(changes) > 0 and object_type in changes.columns
+ else changes.iloc[0:0].copy()
+ )
+ attributes = []
+ for column in object_attribute_columns:
+ if selected[column].notna().any() and column not in attributes:
+ attributes.append(column)
+ if len(type_changes) > 0:
+ for field in type_changes[changed_field].tolist():
+ if field not in attributes:
+ attributes.append(field)
+ reserved = {"ocel_id", "ocel_time", "ocel_changed_field"}
+ if any(attribute in reserved for attribute in attributes):
+ raise ValueError("Object attribute name collides with a fixed bundle column.")
+
+ attribute_types = []
+ for column in attributes:
+ values = selected[column].tolist() if column in selected.columns else []
+ if column in type_changes.columns:
+ values += type_changes[column].tolist()
+ attribute_types.append((column, _primitive_type_from_values(values)))
+
+ encoded_type = _percent_encode(object_type_name)
+ table_path = "objects/object_%s.%s" % (encoded_type, extension)
+ changes_path = "object_changes/object_changes_%s.%s" % (encoded_type, extension)
+ object_table = selected[[object_id] + [column for column in attributes if column in selected.columns]].copy()
+ for column in attributes:
+ if column not in object_table.columns:
+ object_table[column] = None
+ object_table = object_table[[object_id] + attributes].rename(columns={object_id: "ocel_id"})
+ table_specs[table_path] = (object_table, [("ocel_id", "string", False)], attribute_types)
+
+ change_records = []
+ for record in type_changes.to_dict(orient="records"):
+ field = record[changed_field]
+ row = {
+ "ocel_id": record[object_id],
+ "ocel_time": record[event_timestamp],
+ "ocel_changed_field": field,
+ }
+ for attribute in attributes:
+ row[attribute] = record.get(attribute) if attribute == field else None
+ change_records.append(row)
+ change_columns = ["ocel_id", "ocel_time", "ocel_changed_field"] + attributes
+ change_table = pandas_utils.instantiate_dataframe(change_records, columns=change_columns)
+ table_specs[changes_path] = (
+ change_table,
+ [
+ ("ocel_id", "string", False),
+ ("ocel_time", "time", False),
+ ("ocel_changed_field", "string", False),
+ ],
+ attribute_types,
+ )
+ meta["objectTypes"][object_type_name] = {
+ "file": table_path,
+ "changesFile": changes_path,
+ "attributes": [
+ {"name": name, "type": primitive_type}
+ for name, primitive_type in attribute_types
+ ],
+ }
+
+ e2o_records = []
+ e2o_keys = set()
+ for record in relations.to_dict(orient="records"):
+ eid = _normalized_string(record.get(event_id), "E2O event id")
+ oid = _normalized_string(record.get(object_id), "E2O object id")
+ relation_qualifier = _normalized_string(record.get(qualifier), "E2O qualifier", allow_empty=True)
+ if eid not in event_id_set or oid not in object_type_by_id:
+ raise ValueError("E2O relation references an unknown event or object.")
+ key = (eid, oid, relation_qualifier)
+ if key in e2o_keys:
+ raise ValueError("Duplicate E2O relation cannot be exported.")
+ e2o_keys.add(key)
+ e2o_records.append(
+ {"ocel_event_id": eid, "ocel_object_id": oid, "ocel_qualifier": relation_qualifier}
+ )
+ e2o_fixed = [
+ ("ocel_event_id", "string", False),
+ ("ocel_object_id", "string", False),
+ ("ocel_qualifier", "string", True),
+ ]
+ table_specs[meta["relations"]["e2o"]] = (
+ _relation_dataframe(e2o_records, [name for name, _, _ in e2o_fixed]),
+ e2o_fixed,
+ [],
+ )
+
+ o2o_records = []
+ o2o_keys = set()
+ for record in o2o.to_dict(orient="records"):
+ source = _normalized_string(record.get(object_id), "O2O source id")
+ target = _normalized_string(record.get(object_id + "_2"), "O2O target id")
+ relation_qualifier = _normalized_string(record.get(qualifier), "O2O qualifier", allow_empty=True)
+ if source not in object_type_by_id or target not in object_type_by_id:
+ raise ValueError("O2O relation references an unknown object.")
+ key = (source, target, relation_qualifier)
+ if key in o2o_keys:
+ raise ValueError("Duplicate O2O relation cannot be exported.")
+ o2o_keys.add(key)
+ o2o_records.append(
+ {"ocel_source_id": source, "ocel_target_id": target, "ocel_qualifier": relation_qualifier}
+ )
+ o2o_fixed = [
+ ("ocel_source_id", "string", False),
+ ("ocel_target_id", "string", False),
+ ("ocel_qualifier", "string", True),
+ ]
+ table_specs[meta["relations"]["o2o"]] = (
+ _relation_dataframe(o2o_records, [name for name, _, _ in o2o_fixed]),
+ o2o_fixed,
+ [],
+ )
+
+ files = {
+ "ocel-meta.json": json.dumps(
+ meta, ensure_ascii=False, indent=2, allow_nan=False
+ ).encode(encoding)
+ }
+ for table_path, (dataframe, fixed, attributes) in table_specs.items():
+ files[table_path] = _table_bytes(
+ dataframe, storage_format, fixed, attributes, encoding
+ )
+
+ target_path = str(target_path)
+ if target_path.lower().endswith(".ocel.zip"):
+ _write_archive(target_path, files)
+ elif target_path.lower().endswith(".zip"):
+ raise ValueError("Bundled OCEL archives use the '.ocel.zip' extension.")
+ else:
+ _write_directory(target_path, files)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..80143a8807b3cfd67e9460bdbafbfbafc3eeff68
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.csv import variants, exporter
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e1dd2d03b648aba4c1a9bf71232ea2db06cd006
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/exporter.py
@@ -0,0 +1,61 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.exporter.csv.variants import pandas, ocel20
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ PANDAS = pandas
+ OCEL20 = ocel20
+
+
+def apply(
+ ocel: OCEL,
+ output_path: str,
+ variant=Variants.PANDAS,
+ objects_path=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Exports an object-centric event log in a CSV file
+
+ Parameters
+ -----------------
+ ocel
+ Object-centric event log
+ output_path
+ Destination file
+ variant
+ Variant of the algorithm that should be used, possible values:
+ - Variants.PANDAS
+ objects_path
+ Optional path, where the objects dataframe is stored
+ parameters
+ Parameters of the algorithm
+ """
+ return exec_utils.get_variant(variant).apply(
+ ocel, output_path, objects_path=objects_path, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c78eab3924957db1dc003bebb2d28adad691ab9e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.csv.variants import pandas, ocel20
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eac8c88f7f760ad24cbe69c81b006affb053a38
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/ocel20.py
@@ -0,0 +1,518 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any, List
+import codecs
+from decimal import Decimal
+import json
+import math
+
+import pandas as pd
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.util import exec_utils, constants as pm4_constants, pandas_utils
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ ENCODING = "encoding"
+ OBJECT_TYPE_PREFIX = "object_type_prefix"
+ O2O_ACTIVITY = "o2o_activity"
+ CSV_EVENT_ID = "csv_event_id"
+ CSV_EVENT_ACTIVITY = "csv_event_activity"
+ CSV_EVENT_TIMESTAMP = "csv_event_timestamp"
+
+
+def _is_null(value) -> bool:
+ return clean_dataframes.is_null(value)
+
+
+def _timestamp_value(value):
+ timestamp = value if isinstance(value, pd.Timestamp) else pd.Timestamp(value)
+ if timestamp.tzinfo is None or timestamp.utcoffset() is None:
+ timestamp = timestamp.tz_localize("UTC")
+ return timestamp.tz_convert("UTC")
+
+
+def _timestamp_sort_key(value):
+ return _timestamp_value(value).value
+
+
+def _format_timestamp(value) -> str:
+ if _is_null(value):
+ return ""
+ try:
+ return _timestamp_value(value).isoformat()
+ except BaseException:
+ raise ValueError(
+ "OCEL2 CSV timestamps must be ISO 8601 timestamps with timezone information."
+ )
+
+
+def _validate_reference_part(value: Any, name: str) -> str:
+ value = clean_dataframes.normalize_value(value)
+ if _is_null(value):
+ raise ValueError("OCEL2 CSV %s values cannot be empty." % name)
+ if isinstance(value, (list, dict, tuple, set)):
+ raise ValueError("OCEL2 CSV %s values must be scalar." % name)
+ value = str(value)
+ if value != value.strip():
+ raise ValueError(
+ "OCEL2 CSV %s values cannot contain leading or trailing whitespace." % name
+ )
+ if not value:
+ raise ValueError("OCEL2 CSV %s values cannot be empty." % name)
+ return value
+
+
+def _escape_reference_part(value: str) -> str:
+ return (
+ value.replace("\\", "\\\\")
+ .replace("/", "\\/")
+ .replace("#", "\\#")
+ .replace("{", "\\{")
+ )
+
+
+def _validate_json_attribute_value(value: Any):
+ if isinstance(value, (list, dict, tuple, set)):
+ raise ValueError(
+ "JSON arrays and objects are not valid OCEL2 CSV attribute values."
+ )
+ if isinstance(value, float) and not math.isfinite(value):
+ raise ValueError(
+ "Non-finite JSON numbers are not valid OCEL2 CSV attribute values."
+ )
+
+
+def _json_dumps(attrs: Dict[str, Any]) -> str:
+ normalized = {}
+ for key, value in attrs.items():
+ if _is_null(value):
+ continue
+ value = clean_dataframes.normalize_value(value)
+ _validate_json_attribute_value(value)
+ normalized[str(key)] = value
+ if not normalized:
+ return ""
+ return json.dumps(
+ normalized, ensure_ascii=False, separators=(",", ":"), allow_nan=False
+ )
+
+
+def _format_reference(object_id: Any, qualifier: Any = None, attrs: Optional[Dict[str, Any]] = None) -> str:
+ value = _escape_reference_part(_validate_reference_part(object_id, "object id"))
+ if not _is_null(qualifier) and str(qualifier) != "":
+ value += "#" + _escape_reference_part(
+ _validate_reference_part(qualifier, "qualifier")
+ )
+ if attrs:
+ value += _json_dumps(attrs)
+ return value
+
+
+def _non_ocel_attribute_columns(df: pd.DataFrame, reserved: List[str]) -> List[str]:
+ return [
+ column
+ for column in df.columns
+ if column not in reserved and not str(column).startswith("ocel:")
+ ]
+
+
+def _reference_sort_value(value: Any) -> str:
+ return str(clean_dataframes.normalize_value(value))
+
+
+def _new_row(header_len: int) -> List[str]:
+ return [""] * header_len
+
+
+def _require_utf8(encoding: str) -> str:
+ try:
+ normalized = codecs.lookup(encoding).name
+ except LookupError as exc:
+ raise ValueError("Unknown OCEL2 CSV encoding '%s'." % encoding) from exc
+ if normalized != "utf-8":
+ raise ValueError("OCEL2 CSV files must use UTF-8 encoding.")
+ return "utf-8"
+
+
+def _require_unique(df: pd.DataFrame, column: str, kind: str):
+ if column not in df.columns or df[column].isna().any():
+ raise ValueError("OCEL2 CSV %s must have non-empty '%s' values." % (kind, column))
+ if df[column].duplicated().any():
+ duplicate = df.loc[df[column].duplicated(), column].iloc[0]
+ raise ValueError("Duplicate %s id '%s' cannot be exported." % (kind, duplicate))
+
+
+def _require_trimmed(value: Any, kind: str) -> str:
+ value = clean_dataframes.normalize_value(value)
+ if _is_null(value):
+ raise ValueError("OCEL2 CSV %s values cannot be empty." % kind)
+ value = str(value)
+ if not value or value != value.strip():
+ raise ValueError(
+ "OCEL2 CSV %s values must be non-empty and contain no leading or trailing whitespace."
+ % kind
+ )
+ return value
+
+
+def _values_equal(left: Any, right: Any) -> bool:
+ left = clean_dataframes.normalize_value(left)
+ right = clean_dataframes.normalize_value(right)
+ if (
+ isinstance(left, (int, float))
+ and not isinstance(left, bool)
+ and isinstance(right, (int, float))
+ and not isinstance(right, bool)
+ ):
+ return Decimal(str(left)) == Decimal(str(right))
+ return type(left) is type(right) and left == right
+
+
+def apply(
+ ocel: OCEL,
+ output_path: str,
+ objects_path=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Exports an OCEL 2.0 object-centric event log to the compact CSV format.
+ """
+ if parameters is None:
+ parameters = {}
+ output_path = str(output_path)
+ if not output_path.lower().endswith(".ocel.csv"):
+ raise ValueError("OCEL2 compact CSV exports use the '.ocel.csv' extension.")
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+ encoding = _require_utf8(encoding)
+ event_id_column = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ event_activity_column = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ event_timestamp_column = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP, parameters, ocel.event_timestamp
+ )
+ object_id_column = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type_column = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+ qualifier_column = exec_utils.get_param_value(
+ Parameters.QUALIFIER, parameters, ocel.qualifier
+ )
+ changed_field_column = exec_utils.get_param_value(
+ Parameters.CHANGED_FIELD, parameters, ocel.changed_field
+ )
+ object_type_prefix = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE_PREFIX, parameters, "ot:"
+ )
+ o2o_activity = exec_utils.get_param_value(
+ Parameters.O2O_ACTIVITY, parameters, "o2o"
+ )
+ csv_event_id = exec_utils.get_param_value(
+ Parameters.CSV_EVENT_ID, parameters, "id"
+ )
+ csv_event_activity = exec_utils.get_param_value(
+ Parameters.CSV_EVENT_ACTIVITY, parameters, "activity"
+ )
+ csv_event_timestamp = exec_utils.get_param_value(
+ Parameters.CSV_EVENT_TIMESTAMP, parameters, "timestamp"
+ )
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+
+ _require_unique(ocel.events, event_id_column, "event")
+ _require_unique(ocel.objects, object_id_column, "object")
+
+ object_types = sorted(
+ str(x)
+ for x in pandas_utils.format_unique(ocel.objects[object_type_column].dropna().unique())
+ )
+ object_type_columns = [object_type_prefix + object_type for object_type in object_types]
+
+ event_attribute_columns = _non_ocel_attribute_columns(
+ ocel.events, [event_id_column, event_activity_column, event_timestamp_column]
+ )
+ object_attribute_columns = _non_ocel_attribute_columns(
+ ocel.objects, [object_id_column, object_type_column]
+ )
+ reserved_output_columns = {
+ csv_event_id,
+ csv_event_activity,
+ csv_event_timestamp,
+ *object_type_columns,
+ }
+ duplicate_attributes = reserved_output_columns.intersection(event_attribute_columns)
+ if duplicate_attributes:
+ raise ValueError(
+ "Event attribute columns collide with reserved OCEL2 CSV columns: %s."
+ % ", ".join(sorted(str(value) for value in duplicate_attributes))
+ )
+
+ object_type = (
+ ocel.objects[[object_id_column, object_type_column]]
+ .drop_duplicates(subset=[object_id_column])
+ .set_index(object_id_column)[object_type_column]
+ .to_dict()
+ )
+ object_records = ocel.objects.to_dict(orient="records")
+ for record in object_records:
+ if _is_null(record.get(object_id_column)) or _is_null(record.get(object_type_column)):
+ raise ValueError("OCEL2 CSV objects must have non-empty ids and types.")
+ _validate_reference_part(record[object_id_column], "object id")
+
+ object_attrs = {}
+ for record in object_records:
+ attrs = {}
+ for column in object_attribute_columns:
+ value = record.get(column)
+ if not _is_null(value):
+ attrs[column] = value
+ if attrs:
+ object_attrs[record[object_id_column]] = attrs
+
+ type_established_ids = set()
+ event_relations = {}
+ relation_columns = [
+ event_id_column,
+ object_id_column,
+ object_type_column,
+ qualifier_column,
+ ]
+ event_ids = set(ocel.events[event_id_column].tolist())
+ relation_keys = set()
+ for event_id, object_id, relation_object_type, qualifier in ocel.relations[
+ relation_columns
+ ].itertuples(index=False, name=None):
+ if event_id not in event_ids:
+ raise ValueError("Relation references unknown event '%s'." % event_id)
+ known_object_type = object_type.get(object_id)
+ if _is_null(known_object_type):
+ raise ValueError("Relation references unknown object '%s'." % object_id)
+ if not _is_null(relation_object_type) and str(relation_object_type) != str(known_object_type):
+ raise ValueError(
+ "Relation object type for '%s' does not match the object table." % object_id
+ )
+ relation_key = (event_id, object_id, "" if _is_null(qualifier) else str(qualifier))
+ if relation_key in relation_keys:
+ raise ValueError("Duplicate event-to-object relation cannot be exported.")
+ relation_keys.add(relation_key)
+ event_relations.setdefault(event_id, []).append(
+ (object_id, known_object_type, qualifier)
+ )
+
+ timed_change_groups = {}
+ epoch = pd.Timestamp("1970-01-01T00:00:00Z")
+ for change_index, record in enumerate(ocel.object_changes.to_dict(orient="records")):
+ oid = record.get(object_id_column)
+ known_type = object_type.get(oid)
+ record_type = record.get(object_type_column, known_type)
+ timestamp = record.get(event_timestamp_column)
+ changed_attr = record.get(changed_field_column)
+ if _is_null(oid) or _is_null(known_type):
+ raise ValueError("Object change references an unknown object.")
+ if not _is_null(record_type) and str(record_type) != str(known_type):
+ raise ValueError("Object change type does not match object '%s'." % oid)
+ if _is_null(timestamp) or _is_null(changed_attr):
+ raise ValueError("Object changes require a timestamp and changed field.")
+ if changed_attr not in record or _is_null(record.get(changed_attr)):
+ raise ValueError(
+ "Object change for '%s' does not contain a value in column '%s'."
+ % (oid, changed_attr)
+ )
+ value = record.get(changed_attr)
+ normalized_timestamp = _timestamp_value(timestamp)
+ if normalized_timestamp == epoch:
+ existing = object_attrs.setdefault(oid, {}).get(changed_attr)
+ if existing is not None and not _values_equal(existing, value):
+ raise ValueError(
+ "Object '%s' has conflicting time-0 values for attribute '%s'."
+ % (oid, changed_attr)
+ )
+ object_attrs[oid][changed_attr] = value
+ continue
+ key = (normalized_timestamp.value, str(known_type), oid)
+ group = timed_change_groups.setdefault(
+ key,
+ {
+ "timestamp": normalized_timestamp,
+ "object_type": str(known_type),
+ "object_id": oid,
+ "first_index": change_index,
+ "attributes": {},
+ },
+ )
+ existing = group["attributes"].get(changed_attr)
+ if existing is not None and not _values_equal(existing, value):
+ raise ValueError(
+ "Object '%s' has conflicting values for attribute '%s' at %s."
+ % (oid, changed_attr, normalized_timestamp.isoformat())
+ )
+ group["attributes"][changed_attr] = value
+
+ header = (
+ [csv_event_id, csv_event_activity, csv_event_timestamp]
+ + object_type_columns
+ + event_attribute_columns
+ )
+ header_index = {column: index for index, column in enumerate(header)}
+ object_type_column_index = {
+ object_type: header_index[object_type_prefix + object_type]
+ for object_type in object_types
+ }
+ rows = []
+ header_len = len(header)
+
+ event_records = list(enumerate(ocel.events.to_dict(orient="records")))
+ event_records = sorted(
+ event_records,
+ key=lambda item: (_timestamp_sort_key(item[1][event_timestamp_column]), item[0]),
+ )
+
+ for _, event in event_records:
+ row = _new_row(header_len)
+ event_id = _require_trimmed(event[event_id_column], "event id")
+ event_activity = _require_trimmed(
+ event[event_activity_column], "event activity"
+ )
+ if event_activity.casefold() == str(o2o_activity).casefold():
+ raise ValueError("An event type named 'o2o' is not representable in OCEL2 CSV.")
+ row[header_index[csv_event_id]] = event_id
+ row[header_index[csv_event_activity]] = event_activity
+ row[header_index[csv_event_timestamp]] = _format_timestamp(event[event_timestamp_column])
+
+ for column in event_attribute_columns:
+ value = event.get(column)
+ if not _is_null(value):
+ row[header_index[column]] = clean_dataframes.normalize_value(value)
+
+ entries = {object_type: [] for object_type in object_types}
+ for oid, ot, qualifier in event_relations.get(event_id, []):
+ if _is_null(ot):
+ ot = object_type.get(oid)
+ if _is_null(ot):
+ raise ValueError(
+ "Cannot export OCEL2 CSV relation for object '%s' without an object type."
+ % oid
+ )
+ type_established_ids.add(oid)
+ entries.setdefault(str(ot), []).append(
+ _format_reference(oid, qualifier)
+ )
+
+ for ot, values in entries.items():
+ if values:
+ row[object_type_column_index[ot]] = "/".join(values)
+ rows.append(row)
+
+ declaration_records = sorted(
+ object_records,
+ key=lambda record: (
+ str(record[object_type_column]),
+ _reference_sort_value(record[object_id_column]),
+ ),
+ )
+ for record in declaration_records:
+ oid = record[object_id_column]
+ attrs = object_attrs.get(oid, {})
+ if oid in type_established_ids and not attrs:
+ continue
+ ot = str(record[object_type_column])
+ row = _new_row(header_len)
+ row[object_type_column_index[ot]] = _format_reference(oid, attrs=attrs)
+ rows.append(row)
+
+ o2o_entries = {}
+ o2o_columns = [object_id_column, object_id_column + "_2", qualifier_column]
+ o2o_keys = set()
+ for source_id, target_id, qualifier in ocel.o2o[o2o_columns].itertuples(
+ index=False, name=None
+ ):
+ source_type = object_type.get(source_id)
+ target_type = object_type.get(target_id)
+ if _is_null(source_id) or _is_null(source_type):
+ raise ValueError(
+ "Cannot export OCEL2 CSV object-to-object source '%s' without an object type."
+ % source_id
+ )
+ if _is_null(target_id) or _is_null(target_type):
+ raise ValueError(
+ "Cannot export OCEL2 CSV object-to-object target '%s' without an object type."
+ % target_id
+ )
+ o2o_key = (source_id, target_id, "" if _is_null(qualifier) else str(qualifier))
+ if o2o_key in o2o_keys:
+ raise ValueError("Duplicate object-to-object relation cannot be exported.")
+ o2o_keys.add(o2o_key)
+ o2o_entries.setdefault(source_id, {}).setdefault(str(target_type), []).append(
+ _format_reference(target_id, qualifier)
+ )
+
+ for source_id in sorted(o2o_entries, key=_reference_sort_value):
+ entries = o2o_entries[source_id]
+ row = _new_row(header_len)
+ row[header_index[csv_event_id]] = source_id
+ row[header_index[csv_event_activity]] = o2o_activity
+ for ot in sorted(entries):
+ row[object_type_column_index[ot]] = "/".join(sorted(entries[ot]))
+ rows.append(row)
+
+ change_groups = sorted(
+ timed_change_groups.values(),
+ key=lambda group: (group["timestamp"].value, group["first_index"]),
+ )
+ for group in change_groups:
+ row = _new_row(header_len)
+ row[header_index[csv_event_timestamp]] = _format_timestamp(group["timestamp"])
+ row[object_type_column_index[group["object_type"]]] = _format_reference(
+ group["object_id"], attrs=group["attributes"]
+ )
+ rows.append(row)
+
+ dataframe = pandas_utils.instantiate_dataframe(rows, columns=header)
+ dataframe.to_csv(
+ output_path,
+ index=False,
+ na_rep="",
+ encoding=encoding,
+ lineterminator="\r\n",
+ )
+
+ if objects_path is not None:
+ ocel.objects.to_csv(objects_path, index=False, na_rep="", encoding=encoding)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/pandas.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/pandas.py
new file mode 100644
index 0000000000000000000000000000000000000000..60d3185628846d5d47ed1f4f83da850e19a14c47
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/csv/variants/pandas.py
@@ -0,0 +1,73 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import filtering_utils
+from enum import Enum
+from pm4py.util import exec_utils, constants as pm4_constants
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def apply(
+ ocel: OCEL,
+ output_path: str,
+ objects_path=None,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Exports an object-centric event log in a CSV file, using Pandas as backend
+
+ Parameters
+ -----------------
+ ocel
+ Object-centric event log
+ output_path
+ Destination file
+ objects_path
+ Optional path, where the objects dataframe is stored
+ parameters
+ Parameters of the algorithm
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(
+ ocel, parameters=parameters
+ )
+
+ ocel.get_extended_table().to_csv(
+ output_path, index=False, na_rep="", encoding=encoding
+ )
+
+ if objects_path is not None:
+ ocel.objects.to_csv(
+ objects_path, index=False, na_rep="", encoding=encoding
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..34ec7c71011117ac0744d7f0a08c72610d3f534e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.jsonocel import exporter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..7204ef666541aba232302fd0608569b342805011
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/exporter.py
@@ -0,0 +1,61 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.exporter.jsonocel.variants import (
+ classic,
+ ocel20,
+ ocel20_standard,
+)
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ CLASSIC = classic
+ OCEL20 = ocel20
+ OCEL20_STANDARD = ocel20_standard
+
+
+def apply(
+ ocel: OCEL,
+ target_path: str,
+ variant=Variants.CLASSIC,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Exports an object-centric event log in a JSONOCEL file
+
+ Parameters
+ ------------------
+ ocel
+ Object-centric event log
+ target_path
+ Destination path
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.CLASSIC
+ parameters
+ Variant-specific parameters
+ """
+ return exec_utils.get_variant(variant).apply(ocel, target_path, parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4794323d1938d0024832c18443a02f1137c268ad
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/__init__.py
@@ -0,0 +1,26 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.jsonocel.variants import (
+ classic,
+ ocel20,
+ ocel20_standard,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..42343dc8872434c20b85b78d7e4754d503a7cd6f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/classic.py
@@ -0,0 +1,183 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import json
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import attributes_names
+from pm4py.objects.ocel.util import compression
+from pm4py.objects.ocel.util import related_objects
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.util import exec_utils, constants as pm4_constants, pandas_utils
+from pm4py.objects.ocel.util import ocel_consistency
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ ENCODING = "encoding"
+
+
+def get_base_json_object(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+):
+ if parameters is None:
+ parameters = {}
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+
+ all_object_types = pandas_utils.format_unique(
+ ocel.objects[object_type].unique()
+ )
+ all_attribute_names = attributes_names.get_attribute_names(
+ ocel, parameters=parameters
+ )
+ global_event_items = (
+ ocel.globals[constants.OCEL_GLOBAL_EVENT]
+ if constants.OCEL_GLOBAL_EVENT in ocel.globals
+ else constants.DEFAULT_GLOBAL_EVENT
+ )
+ global_object_items = (
+ ocel.globals[constants.OCEL_GLOBAL_OBJECT]
+ if constants.OCEL_GLOBAL_OBJECT in ocel.globals
+ else constants.DEFAULT_GLOBAL_OBJECT
+ )
+ rel_objs = related_objects.related_objects_dct_overall(
+ ocel, parameters=parameters
+ )
+
+ events_items, objects_items = clean_dataframes.get_dataframes_from_ocel(
+ ocel, parameters=parameters
+ )
+
+ base_object = {}
+ base_object[constants.OCEL_GLOBAL_EVENT] = global_event_items
+ base_object[constants.OCEL_GLOBAL_OBJECT] = global_object_items
+ base_object[constants.OCEL_GLOBAL_LOG] = {}
+ base_object[constants.OCEL_GLOBAL_LOG][
+ constants.OCEL_GLOBAL_LOG_OBJECT_TYPES
+ ] = all_object_types
+ base_object[constants.OCEL_GLOBAL_LOG][
+ constants.OCEL_GLOBAL_LOG_ATTRIBUTE_NAMES
+ ] = all_attribute_names
+ base_object[constants.OCEL_GLOBAL_LOG][
+ constants.OCEL_GLOBAL_LOG_VERSION
+ ] = constants.CURRENT_VERSION
+ base_object[constants.OCEL_GLOBAL_LOG][
+ constants.OCEL_GLOBAL_LOG_ORDERING
+ ] = constants.DEFAULT_ORDERING
+ base_object[constants.OCEL_EVENTS_KEY] = {}
+ base_object[constants.OCEL_OBJECTS_KEY] = {}
+
+ events_items = events_items.to_dict(orient="records")
+ i = 0
+ while i < len(events_items):
+ event = events_items[i]
+ eid = event[event_id]
+ del event[event_id]
+ event = {k: v for k, v in event.items() if pd.notnull(v)}
+ vmap = {
+ k: v
+ for k, v in event.items()
+ if not k.startswith(constants.OCEL_PREFIX)
+ }
+ event = {
+ k: v
+ for k, v in event.items()
+ if k.startswith(constants.OCEL_PREFIX)
+ }
+ event[constants.OCEL_VMAP_KEY] = vmap
+ event[constants.OCEL_OMAP_KEY] = list(rel_objs[eid])
+ base_object[constants.OCEL_EVENTS_KEY][eid] = event
+ i = i + 1
+ del events_items
+
+ objects_items = objects_items.to_dict(orient="records")
+ i = 0
+ while i < len(objects_items):
+ object = objects_items[i]
+ oid = object[object_id]
+ del object[object_id]
+ ovmap = {
+ k: v
+ for k, v in object.items()
+ if pd.notnull(v) and not k.startswith(constants.OCEL_PREFIX)
+ }
+ object = {
+ object_type: object[object_type],
+ constants.OCEL_OVMAP_KEY: ovmap,
+ }
+ base_object[constants.OCEL_OBJECTS_KEY][oid] = object
+ i = i + 1
+ del objects_items
+
+ return base_object
+
+
+def apply(
+ ocel: OCEL, target_path: str, parameters: Optional[Dict[Any, Any]] = None
+):
+ """
+ Exports an object-centric event log in a JSONOCEL file, using the classic JSON dump
+
+ Parameters
+ ------------------
+ ocel
+ Object-centric event log
+ target_path
+ Destination path
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the event ID column
+ - Parameters.OBJECT_ID => the object ID column
+ - Parameters.OBJECT_TYPE => the object type column
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(
+ ocel, parameters=parameters
+ )
+
+ base_object = get_base_json_object(ocel, parameters=parameters)
+
+ with compression.open_text(target_path, "wt", encoding=encoding) as F:
+ json.dump(base_object, F, indent=2)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..9020f89031bd45cf6a17eb672d46f4b932271583
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/ocel20.py
@@ -0,0 +1,181 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import json
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils, constants as pm4_constants
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.objects.ocel.exporter.jsonocel.variants import classic
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+from pm4py.objects.ocel.util import attributes_per_type
+from pm4py.objects.ocel.util import compression
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ ENCODING = "encoding"
+
+
+def get_enriched_object(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+):
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP, parameters, ocel.event_timestamp
+ )
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(
+ ocel, parameters=parameters
+ )
+
+ base_object = classic.get_base_json_object(ocel, parameters=parameters)
+
+ ets, ots = attributes_per_type.get(ocel, parameters=parameters)
+
+ base_object[constants.OCEL_EVTYPES_KEY] = {}
+ for et in ets:
+ base_object[constants.OCEL_EVTYPES_KEY][et] = {}
+ et_atts = ets[et]
+ for k, v in et_atts.items():
+ this_type = "string"
+ if "date" in v or "time" in v:
+ this_type = "date"
+ elif "float" in v or "double" in v:
+ this_type = "float"
+ base_object[constants.OCEL_EVTYPES_KEY][et][k] = this_type
+
+ base_object[constants.OCEL_OBJTYPES_KEY] = {}
+ for ot in ots:
+ base_object[constants.OCEL_OBJTYPES_KEY][ot] = {}
+ ot_atts = ots[ot]
+ for k, v in ot_atts.items():
+ this_type = "string"
+ if "date" in v or "time" in v:
+ this_type = "date"
+ elif "float" in v or "double" in v:
+ this_type = "float"
+ base_object[constants.OCEL_OBJTYPES_KEY][ot][k] = this_type
+
+ base_object[constants.OCEL_OBJCHANGES_KEY] = []
+ if len(ocel.object_changes) > 0:
+ object_changes = ocel.object_changes.to_dict(orient="records")
+ for i in range(len(object_changes)):
+ change = object_changes[i]
+ for k in list(change.keys()):
+ value = clean_dataframes.normalize_value(change[k])
+ if clean_dataframes.is_null(value):
+ del change[k]
+ continue
+ change[k] = value
+
+ base_object[constants.OCEL_OBJCHANGES_KEY] = object_changes
+
+ e2o_list = ocel.relations[
+ [event_id, object_id, constants.DEFAULT_QUALIFIER]
+ ].to_dict(orient="records")
+ eids = set()
+
+ for elem in e2o_list:
+ eid = elem[event_id]
+ oid = elem[object_id]
+ qualifier = elem[constants.DEFAULT_QUALIFIER]
+
+ if eid not in eids:
+ base_object[constants.OCEL_EVENTS_KEY][eid][
+ constants.OCEL_TYPED_OMAP_KEY
+ ] = []
+ eids.add(eid)
+
+ base_object[constants.OCEL_EVENTS_KEY][eid][
+ constants.OCEL_TYPED_OMAP_KEY
+ ].append({object_id: oid, constants.DEFAULT_QUALIFIER: qualifier})
+
+ o2o_list = ocel.o2o.to_dict(orient="records")
+ oids = set()
+
+ for elem in o2o_list:
+ oid = elem[object_id]
+ oid2 = elem[object_id + "_2"]
+ qualifier = elem[constants.DEFAULT_QUALIFIER]
+
+ if oid not in oids:
+ base_object[constants.OCEL_OBJECTS_KEY][oid][
+ constants.OCEL_O2O_KEY
+ ] = []
+ oids.add(oid)
+
+ base_object[constants.OCEL_OBJECTS_KEY][oid][
+ constants.OCEL_O2O_KEY
+ ].append({object_id: oid2, constants.DEFAULT_QUALIFIER: qualifier})
+
+ return base_object
+
+
+def apply(
+ ocel: OCEL, target_path: str, parameters: Optional[Dict[Any, Any]] = None
+):
+ """
+ Exports an object-centric event log (OCEL 2.0) in a JSONOCEL 2.0 file, using the classic JSON dump
+
+ Parameters
+ ------------------
+ ocel
+ Object-centric event log
+ target_path
+ Destination path
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the event ID column
+ - Parameters.OBJECT_ID => the object ID column
+ - Parameters.OBJECT_TYPE => the object type column
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+
+ json_object = get_enriched_object(ocel, parameters=parameters)
+
+ with compression.open_text(target_path, "wt", encoding=encoding) as F:
+ json.dump(json_object, F, indent=2)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/ocel20_standard.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/ocel20_standard.py
new file mode 100644
index 0000000000000000000000000000000000000000..61df54d07d7f6326199cd1f026a7a4a857c25dd2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/jsonocel/variants/ocel20_standard.py
@@ -0,0 +1,161 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.jsonocel.variants import ocel20
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from enum import Enum
+import json
+from pm4py.util import exec_utils, constants as pm4_constants
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+from pm4py.objects.ocel.util import compression
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def apply(
+ ocel: OCEL, target_path: str, parameters: Optional[Dict[Any, Any]] = None
+):
+ """
+ Exports an object-centric event log (OCEL 2.0) in a JSON-OCEL 2.0 standard file
+
+ Parameters
+ ------------------
+ ocel
+ Object-centric event log
+ target_path
+ Destination path
+ parameters
+ Possible parameters of the method, including:
+ - Parameters.ENCODING
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+
+ legacy_object = ocel20.get_enriched_object(ocel)
+
+ json_object = {}
+ json_object["objectTypes"] = []
+ json_object["eventTypes"] = []
+ json_object["objects"] = []
+ json_object["events"] = []
+
+ for ot, attrs in legacy_object["ocel:objectTypes"].items():
+ descr = {
+ "name": ot,
+ "attributes": [{"name": x, "type": y} for x, y in attrs.items()],
+ }
+ json_object["objectTypes"].append(descr)
+
+ for et, attrs in legacy_object["ocel:eventTypes"].items():
+ descr = {
+ "name": et,
+ "attributes": [{"name": x, "type": y} for x, y in attrs.items()],
+ }
+ json_object["eventTypes"].append(descr)
+
+ obj_idx = {}
+ for objid, obj in legacy_object["ocel:objects"].items():
+ descr = {}
+ descr["id"] = objid
+ descr["type"] = obj["ocel:type"]
+ if "ocel:ovmap" in obj and obj["ocel:ovmap"]:
+ descr["attributes"] = []
+ for k, v in obj["ocel:ovmap"].items():
+ norm_value = clean_dataframes.normalize_value(v)
+ if clean_dataframes.is_null(norm_value):
+ continue
+ descr["attributes"].append(
+ {
+ "name": k,
+ "time": "1970-01-01T00:00:00Z",
+ "value": norm_value,
+ }
+ )
+ if "ocel:o2o" in obj and obj["ocel:o2o"]:
+ descr["relationships"] = []
+ for v in obj["ocel:o2o"]:
+ descr["relationships"].append(
+ {
+ "objectId": v["ocel:oid"],
+ "qualifier": v["ocel:qualifier"],
+ }
+ )
+ json_object["objects"].append(descr)
+ obj_idx[objid] = len(obj_idx)
+
+ eve_idx = {}
+ for evid, eve in legacy_object["ocel:events"].items():
+ descr = {}
+ descr["id"] = evid
+ descr["type"] = eve["ocel:activity"]
+ descr["time"] = eve["ocel:timestamp"]
+ if "ocel:vmap" in eve and eve["ocel:vmap"]:
+ descr["attributes"] = []
+ for k, v in eve["ocel:vmap"].items():
+ norm_value = clean_dataframes.normalize_value(v)
+ if clean_dataframes.is_null(norm_value):
+ continue
+ descr["attributes"].append(
+ {"name": k, "value": norm_value}
+ )
+ if "ocel:typedOmap" in eve and eve["ocel:typedOmap"]:
+ descr["relationships"] = []
+ for v in eve["ocel:typedOmap"]:
+ descr["relationships"].append(
+ {
+ "objectId": v["ocel:oid"],
+ "qualifier": v["ocel:qualifier"],
+ }
+ )
+ json_object["events"].append(descr)
+ eve_idx[evid] = len(eve_idx)
+
+ for change in legacy_object["ocel:objectChanges"]:
+ field = change.get("ocel:field")
+ if field is None or field not in change:
+ continue
+ oid = change["ocel:oid"]
+ obj = json_object["objects"][obj_idx[oid]]
+
+ norm_value = clean_dataframes.normalize_value(
+ change[field]
+ )
+ if clean_dataframes.is_null(norm_value):
+ continue
+ obj.setdefault("attributes", []).append(
+ {
+ "name": field,
+ "time": change["ocel:timestamp"],
+ "value": norm_value,
+ }
+ )
+
+ json_object["objects"][obj_idx[oid]] = obj
+
+ with compression.open_text(target_path, "wt", encoding=encoding) as F:
+ json.dump(json_object, F, indent=2)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c6a2af9ab30d07d4d11ef62c34748ef6551a333
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/__init__.py
@@ -0,0 +1,23 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.exporter.sqlite import exporter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..77fac47a447f197a170a78534a4d9fbbf2ccda10
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/exporter.py
@@ -0,0 +1,61 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from enum import Enum
+from pm4py.util import exec_utils
+from pm4py.objects.ocel.exporter.sqlite.variants import pandas_exporter, ocel20
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+
+
+class Variants(Enum):
+ PANDAS_EXPORTER = pandas_exporter
+ OCEL20 = ocel20
+
+
+def apply(
+ ocel: OCEL,
+ target_path: str,
+ variant=Variants.PANDAS_EXPORTER,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Exports an OCEL to a SQLite database
+
+ Parameters
+ -------------
+ ocel
+ Object-centric event log
+ target_path
+ Path to the SQLite database
+ variant
+ Variant to use. Possible values:
+ - Variants.PANDAS_EXPORTER => Pandas exporter
+ parameters
+ Variant-specific parameters
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).apply(
+ ocel, target_path, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd60be46b49017a8be6c26061ad2a993ee0cf051
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/__init__.py
@@ -0,0 +1,23 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.sqlite.variants import pandas_exporter, ocel20
+
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb241583d884c9d3b888d7e71d6c4593bcc8e781
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/ocel20.py
@@ -0,0 +1,202 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+import os
+import pandas as pd
+from pm4py.objects.ocel.util import names_stripping
+from enum import Enum
+from pm4py.util import exec_utils, pandas_utils
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+
+
+class Parameters(Enum):
+ ENABLE_NAMES_STRIPPING = "enable_names_stripping"
+
+
+def _build_type_mapping(types, enable_names_stripping):
+ """Builds deterministic, SQLite-safe, injective type table names."""
+ mapping = {}
+ used = set()
+ for type_name in types:
+ type_name = str(type_name)
+ base = (
+ names_stripping.apply(type_name)
+ if enable_names_stripping
+ else type_name
+ )
+ if not base:
+ base = "Type"
+ candidate = base
+ suffix = 2
+ while candidate.casefold() in used:
+ candidate = "%s_%d" % (base, suffix)
+ suffix += 1
+ used.add(candidate.casefold())
+ mapping[type_name] = candidate
+ return mapping
+
+
+def apply(ocel: OCEL, file_path: str, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Exports the given OCEL (OCEL 2.0) into a SQLite database.
+ Automatically converts the event and object 'ocel:timestamp' fields
+ to Python datetime objects to avoid SQLite binding errors.
+ """
+ if parameters is None:
+ parameters = {}
+
+ enable_names_stripping = exec_utils.get_param_value(Parameters.ENABLE_NAMES_STRIPPING, parameters, True)
+
+ import sqlite3
+
+ # If the target file already exists, remove it to avoid conflicts
+ if os.path.exists(file_path):
+ os.remove(file_path)
+
+ # Enforce consistency checks and propagate filtering
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(ocel, parameters=parameters)
+
+ event_id = ocel.event_id_column
+ event_activity = ocel.event_activity
+ event_timestamp = ocel.event_timestamp
+ object_id = ocel.object_id_column
+ object_type = ocel.object_type_column
+ qualifier = ocel.qualifier
+ changed_field = ocel.changed_field
+
+ conn = sqlite3.connect(file_path)
+
+ # Write the "event" table
+ EVENTS = ocel.events[[event_id, event_activity]].rename(
+ columns={event_id: "ocel_id", event_activity: "ocel_type"}
+ )
+ EVENTS = EVENTS.drop_duplicates()
+ EVENTS.to_sql("event", conn, index=False)
+
+ # Write the "object" table
+ OBJECTS = ocel.objects[[object_id, object_type]].rename(
+ columns={object_id: "ocel_id", object_type: "ocel_type"}
+ )
+ OBJECTS = OBJECTS.drop_duplicates()
+ OBJECTS.to_sql("object", conn, index=False)
+
+ # Prepare event and object type mappings
+ event_types = sorted(pandas_utils.format_unique(EVENTS["ocel_type"].unique()))
+ object_types = sorted(pandas_utils.format_unique(OBJECTS["ocel_type"].unique()))
+ event_type_mapping = _build_type_mapping(
+ event_types, enable_names_stripping
+ )
+ object_type_mapping = _build_type_mapping(
+ object_types, enable_names_stripping
+ )
+
+ EVENT_CORR_TYPE = pandas_utils.instantiate_dataframe(
+ {
+ "ocel_type": event_types,
+ "ocel_type_map": [event_type_mapping[str(x)] for x in event_types],
+ }
+ )
+ OBJECT_CORR_TYPE = pandas_utils.instantiate_dataframe(
+ {
+ "ocel_type": object_types,
+ "ocel_type_map": [object_type_mapping[str(x)] for x in object_types],
+ }
+ )
+
+ EVENT_CORR_TYPE.to_sql("event_map_type", conn, index=False)
+ OBJECT_CORR_TYPE.to_sql("object_map_type", conn, index=False)
+
+ # Write the event-object relationships
+ E2O = ocel.relations[[event_id, object_id, qualifier]].rename(
+ columns={event_id: "ocel_event_id", object_id: "ocel_object_id", qualifier: "ocel_qualifier"}
+ )
+ E2O.to_sql("event_object", conn, index=False)
+
+ # Write the object-object relationships
+ O2O = ocel.o2o.rename(
+ columns={
+ object_id: "ocel_source_id",
+ object_id + "_2": "ocel_target_id",
+ qualifier: "ocel_qualifier",
+ }
+ )
+ O2O.to_sql("object_object", conn, index=False)
+
+ # Export event tables by activity
+ e_types = sorted(pandas_utils.format_unique(ocel.events[event_activity].unique()))
+ for act in e_types:
+ df = ocel.events[ocel.events[event_activity] == act].dropna(how="all", axis="columns")
+ # Rename timestamp column
+ df = df.rename(columns={event_id: "ocel_id", event_timestamp: "ocel_time"})
+
+ # Force ID to string
+ df["ocel_id"] = df["ocel_id"].astype("string")
+
+ # Convert 'ocel_time' to Python datetime (if it's a pandas Timestamp or string)
+ df["ocel_time"] = pd.to_datetime(df["ocel_time"], errors="coerce")
+ for col in df.columns:
+ if str(df[col].dtype) == "object":
+ df[col] = df[col].map(clean_dataframes.normalize_value)
+
+ act_red = event_type_mapping[str(act)]
+
+ df = df.drop_duplicates()
+ df.to_sql("event_" + act_red, conn, index=False)
+
+ # Export object tables by type
+ o_types = sorted(pandas_utils.format_unique(ocel.objects[object_type].unique()))
+ for ot in o_types:
+ df = ocel.objects[ocel.objects[object_type] == ot].dropna(how="all", axis="columns")
+ df = df.rename(columns={object_id: "ocel_id"})
+ del df[object_type]
+
+ # Object changes table
+ df2 = ocel.object_changes[ocel.object_changes[object_type] == ot].dropna(how="all", axis="columns")
+ if len(df2) > 0:
+ del df2[object_type]
+ df2 = df2.rename(
+ columns={
+ object_id: "ocel_id",
+ event_timestamp: "ocel_time",
+ changed_field: "ocel_changed_field",
+ }
+ )
+
+ # Convert 'ocel_time' to Python datetime (if it's a pandas Timestamp or string)
+ df2["ocel_time"] = pd.to_datetime(df2["ocel_time"], errors="coerce")
+
+ df = pandas_utils.concat([df, df2], axis=0)
+
+ df["ocel_id"] = df["ocel_id"].astype("string")
+ for col in df.columns:
+ if str(df[col].dtype) == "object":
+ df[col] = df[col].map(clean_dataframes.normalize_value)
+
+ ot_red = object_type_mapping[str(ot)]
+
+ df.to_sql("object_" + ot_red, conn, index=False)
+
+ conn.close()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/pandas_exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/pandas_exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6cdc1481d2a2420de6050de1bb9e83146ce0631
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/sqlite/variants/pandas_exporter.py
@@ -0,0 +1,64 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Dict, Any, Optional
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import filtering_utils
+import os
+
+
+def apply(
+ ocel: OCEL, target_path: str, parameters: Optional[Dict[Any, Any]] = None
+):
+ """
+ Exports an OCEL to a SQLite database using Pandas
+
+ Parameters
+ ---------------
+ ocel
+ Object-centric event log
+ target_path
+ Path to the SQLite database
+ parameters
+ Parameters of the exporter
+ """
+ if parameters is None:
+ parameters = {}
+
+ import sqlite3
+
+ if os.path.exists(target_path):
+ os.remove(target_path)
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(
+ ocel, parameters=parameters
+ )
+
+ conn = sqlite3.connect(target_path)
+
+ ocel.events.to_sql("EVENTS", conn, index=False)
+ ocel.relations.to_sql("RELATIONS", conn, index=False)
+ ocel.objects.to_sql("OBJECTS", conn, index=False)
+
+ conn.close()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/util/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad3cee78a780fd4c6a1a4ff76b949edb8b167bf8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/util/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.util import clean_dataframes
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/util/clean_dataframes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/util/clean_dataframes.py
new file mode 100644
index 0000000000000000000000000000000000000000..d89e86809b912975c7ec00c50d98f913f40f8251
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/util/clean_dataframes.py
@@ -0,0 +1,80 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any, Tuple
+import datetime as dt
+
+import numpy as np
+import pandas as pd
+
+from pm4py.objects.ocel.obj import OCEL
+
+
+def is_null(value) -> bool:
+ if value is None:
+ return True
+ if isinstance(value, (list, dict, tuple, set)):
+ return False
+ try:
+ return bool(pd.isna(value))
+ except Exception:
+ return False
+
+
+def normalize_value(value):
+ if is_null(value):
+ return None
+ if isinstance(value, (list, dict, tuple, set)):
+ return value
+ if isinstance(value, pd.Timestamp):
+ return value.isoformat()
+ if isinstance(value, (dt.datetime, dt.date)):
+ return value.isoformat()
+ if isinstance(value, np.datetime64):
+ return pd.to_datetime(value).isoformat()
+ if isinstance(value, np.timedelta64):
+ return str(pd.to_timedelta(value))
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def get_dataframes_from_ocel(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> Tuple[pd.DataFrame, pd.DataFrame]:
+ if parameters is None:
+ parameters = {}
+
+ events = ocel.events.copy()
+ for col in events.columns:
+ if str(events[col].dtype) == "object":
+ events[col] = events[col].map(normalize_value)
+ elif "date" in str(events[col].dtype):
+ events[col] = events[col].dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ objects = ocel.objects.copy()
+ for col in objects.columns:
+ if str(objects[col].dtype) == "object":
+ objects[col] = objects[col].map(normalize_value)
+ elif "date" in str(objects[col].dtype):
+ objects[col] = objects[col].dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ return events, objects
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9811457eeb9f253083f5b53c5269a505ffe693d6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.xmlocel import exporter, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..396f921e09657e000166965e87c3e93d4b63b79e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/exporter.py
@@ -0,0 +1,56 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.exporter.xmlocel.variants import classic, ocel20
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ CLASSIC = classic
+ OCEL20 = ocel20
+
+
+def apply(
+ ocel: OCEL,
+ target_path: str,
+ variant=Variants.CLASSIC,
+ parameters: Optional[Dict[Any, Any]] = None,
+):
+ """
+ Exports an object-centric event log to a XML-OCEL file.
+
+ Parameters
+ -----------------
+ ocel
+ Object-centric event log
+ target_path
+ Destination path
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.CLASSIC
+ parameters
+ Variant-specific parameters
+ """
+ return exec_utils.get_variant(variant).apply(ocel, target_path, parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2213c1bca330b673e9b5dc4252773fb443ecaf1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.exporter.xmlocel.variants import classic, ocel20
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..189f63b05f13075252c1a13b74ed4e248edc18f6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/classic.py
@@ -0,0 +1,246 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+from lxml import etree
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import attributes_names
+from pm4py.objects.ocel.util import compression
+from pm4py.objects.ocel.util import related_objects
+from pm4py.util import exec_utils, constants as pm4_constants, pandas_utils
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import filtering_utils
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ ENCODING = "encoding"
+
+
+def get_type(t0):
+ if "float" in str(t0).lower() or "double" in str(t0).lower():
+ return "float"
+ elif "date" in str(t0).lower():
+ return "date"
+ elif "object" in str(t0).lower():
+ return "string"
+ else:
+ return "string"
+
+
+def apply(
+ ocel: OCEL, target_path: str, parameters: Optional[Dict[Any, Any]] = None
+):
+ """
+ Exports an object-centric event log to a XML-OCEL file, using LXML.
+
+ Parameters
+ -----------------
+ ocel
+ Object-centric event log
+ target_path
+ Destination path
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the event ID column
+ - Parameters.OBJECT_ID => the object ID column
+ - Parameters.OBJECT_TYPE => the object type column
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(
+ ocel, parameters=parameters
+ )
+
+ all_object_types = pandas_utils.format_unique(
+ ocel.objects[object_type].unique()
+ )
+ all_attribute_names = attributes_names.get_attribute_names(
+ ocel, parameters=parameters
+ )
+ global_event_items = (
+ ocel.globals[constants.OCEL_GLOBAL_EVENT]
+ if constants.OCEL_GLOBAL_EVENT in ocel.globals
+ else constants.DEFAULT_GLOBAL_EVENT
+ )
+ global_object_items = (
+ ocel.globals[constants.OCEL_GLOBAL_OBJECT]
+ if constants.OCEL_GLOBAL_OBJECT in ocel.globals
+ else constants.DEFAULT_GLOBAL_OBJECT
+ )
+ rel_objs = related_objects.related_objects_dct_overall(
+ ocel, parameters=parameters
+ )
+
+ ev_cols_dtypes = {
+ x: get_type(str(ocel.events[x].dtype)) for x in ocel.events.columns
+ }
+ ob_cols_dtypes = {
+ x: get_type(str(ocel.objects[x].dtype)) for x in ocel.objects.columns
+ }
+
+ events_items, objects_items = clean_dataframes.get_dataframes_from_ocel(
+ ocel, parameters=parameters
+ )
+
+ root = etree.Element("log")
+
+ global_event = etree.SubElement(root, "global")
+ global_event.set("scope", "event")
+ for k, v in global_event_items.items():
+ child = etree.SubElement(global_event, "string")
+ child.set("key", k)
+ child.set("value", v)
+
+ global_object = etree.SubElement(root, "global")
+ global_object.set("scope", "object")
+ for k, v in global_object_items.items():
+ child = etree.SubElement(global_object, "string")
+ child.set("key", k)
+ child.set("value", v)
+
+ global_log = etree.SubElement(root, "global")
+ global_log.set("scope", "log")
+ attribute_names = etree.SubElement(global_log, "list")
+ attribute_names.set("key", "attribute-names")
+ object_types = etree.SubElement(global_log, "list")
+ object_types.set("key", "object-types")
+
+ for k in all_attribute_names:
+ subel = etree.SubElement(attribute_names, "string")
+ subel.set("key", "attribute-name")
+ subel.set("value", k)
+ for k in all_object_types:
+ subel = etree.SubElement(object_types, "string")
+ subel.set("key", "object-type")
+ subel.set("value", k)
+ version = etree.SubElement(global_log, "string")
+ version.set("key", "version")
+ version.set("value", constants.CURRENT_VERSION)
+ ordering = etree.SubElement(global_log, "string")
+ ordering.set("key", "ordering")
+ ordering.set("value", constants.DEFAULT_ORDERING)
+
+ events = etree.SubElement(root, "events")
+ objects = etree.SubElement(root, "objects")
+
+ events_items = events_items.to_dict(orient="records")
+ i = 0
+ while i < len(events_items):
+ event = etree.SubElement(events, "event")
+ event_item = events_items[i]
+ eid = event_item[event_id]
+ event_item = {k: v for k, v in event_item.items() if pd.notnull(v)}
+ vmap = {
+ k: v
+ for k, v in event_item.items()
+ if not k.startswith(constants.OCEL_PREFIX)
+ }
+ event_item = {
+ k: v
+ for k, v in event_item.items()
+ if k.startswith(constants.OCEL_PREFIX) and k != event_id
+ }
+ event_omap_items = rel_objs[eid]
+ xml_event_id = etree.SubElement(event, "string")
+ xml_event_id.set(
+ "key", constants.OCEL_ID_KEY.split(constants.OCEL_PREFIX)[1]
+ )
+ xml_event_id.set("value", str(eid))
+ for k, v in event_item.items():
+ typ = ev_cols_dtypes[k]
+ prop = etree.SubElement(event, typ)
+ prop.set("key", k.split(constants.OCEL_PREFIX)[1])
+ prop.set("value", v)
+ event_omap = etree.SubElement(event, "list")
+ event_omap.set("key", "omap")
+ for kk in event_omap_items:
+ obj = etree.SubElement(event_omap, "string")
+ obj.set("key", "object-id")
+ obj.set("value", str(kk))
+ event_vmap = etree.SubElement(event, "list")
+ event_vmap.set("key", "vmap")
+ for k, v in vmap.items():
+ typ = ev_cols_dtypes[k]
+ attr = etree.SubElement(event_vmap, typ)
+ attr.set("key", k)
+ attr.set("value", str(v))
+ i = i + 1
+ del events_items
+
+ objects_items = objects_items.to_dict(orient="records")
+ i = 0
+ while i < len(objects_items):
+ object = etree.SubElement(objects, "object")
+ object_item = objects_items[i]
+ oid = object_item[object_id]
+ xml_object_id = etree.SubElement(object, "string")
+ xml_object_id.set(
+ "key", constants.OCEL_ID_KEY.split(constants.OCEL_PREFIX)[1]
+ )
+ xml_object_id.set("value", str(oid))
+ xml_object_type = etree.SubElement(object, "string")
+ xml_object_type.set("key", object_type.split(constants.OCEL_PREFIX)[1])
+ xml_object_type.set("value", object_item[object_type])
+ xml_ovmap = etree.SubElement(object, "list")
+ xml_ovmap.set(
+ "key", constants.OCEL_OVMAP_KEY.split(constants.OCEL_PREFIX)[1]
+ )
+ ovmap = {
+ k: v
+ for k, v in object_item.items()
+ if pd.notnull(v) and not k.startswith(constants.OCEL_PREFIX)
+ }
+ for k, v in ovmap.items():
+ typ = ob_cols_dtypes[k]
+ attr = etree.SubElement(xml_ovmap, typ)
+ attr.set("key", k)
+ attr.set("value", str(v))
+ i = i + 1
+ del objects_items
+
+ tree = etree.ElementTree(root)
+
+ with compression.open_binary(target_path, "wb") as F:
+ tree.write(F, pretty_print=True, xml_declaration=True, encoding=encoding)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8985e999d4f37992774ee95b1ff5f37a2f1ac06
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/exporter/xmlocel/variants/ocel20.py
@@ -0,0 +1,247 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+from lxml import etree
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils, constants as pm4_constants
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import attributes_per_type
+from pm4py.objects.ocel.util import compression
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.objects.ocel.exporter.util import clean_dataframes
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ ENCODING = "encoding"
+
+
+RELOBJ_TAG = "relationship"
+
+
+def apply(
+ ocel: OCEL, target_path: str, parameters: Optional[Dict[Any, Any]] = None
+):
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+ event_id_column = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ event_activity_column = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ event_timestamp_column = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP, parameters, ocel.event_timestamp
+ )
+ object_id_column = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type_column = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+ qualifier_column = exec_utils.get_param_value(
+ Parameters.QUALIFIER, parameters, ocel.qualifier
+ )
+ changed_field_column = exec_utils.get_param_value(
+ Parameters.CHANGED_FIELD, parameters, ocel.changed_field
+ )
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(
+ ocel, parameters=parameters
+ )
+
+ objects0 = ocel.objects.to_dict(orient="records")
+ events0 = ocel.events.to_dict(orient="records")
+ object_changes0 = ocel.object_changes.to_dict(orient="records")
+ o2o_dict = ocel.o2o.groupby(object_id_column).agg(list).to_dict(orient="tight")
+ o2o_dict = {
+ o2o_dict["index"][i]: o2o_dict["data"][i]
+ for i in range(len(o2o_dict["index"]))
+ }
+
+ relations0 = (
+ ocel.relations.groupby(event_id_column)[
+ [object_id_column, qualifier_column]
+ ]
+ .agg(list)
+ .to_dict()
+ )
+ relations0_obj_ids = relations0[object_id_column]
+ relations0_qualifiers = relations0[qualifier_column]
+
+ objects0 = {x[object_id_column]: x for x in objects0}
+ events0 = {x[event_id_column]: x for x in events0}
+ object_changes1 = {}
+ object_changes2 = {}
+ object_changes3 = {}
+
+ for objid, obj in objects0.items():
+ obj = {
+ x: y
+ for x, y in obj.items()
+ if not x.startswith("ocel:") and y is not None and not pd.isna(y)
+ }
+ if len(obj) > 0:
+ object_changes2[objid] = {}
+ object_changes3[objid] = []
+ for x, y in obj.items():
+ object_changes2[objid][x] = [(y, "1970-01-01T00:00:00Z")]
+ object_changes3[objid].append((x, y, "1970-01-01T00:00:00Z"))
+
+ for chng in object_changes0:
+ oid = chng[object_id_column]
+ if oid not in object_changes1:
+ object_changes1[oid] = {}
+ if oid not in object_changes2:
+ object_changes2[oid] = {}
+ if oid not in object_changes3:
+ object_changes3[oid] = []
+ chng_time = chng[event_timestamp_column]
+ if chng_time not in object_changes1[oid]:
+ object_changes1[oid][chng_time] = []
+ chng_field = chng[changed_field_column]
+ if chng_field not in object_changes2[oid]:
+ object_changes2[oid][chng_field] = []
+
+ chng_value = chng[chng_field]
+ object_changes1[oid][chng_time].append((chng_field, chng_value))
+ object_changes2[oid][chng_field].append(
+ (chng_value, chng_time.isoformat())
+ )
+ object_changes3[oid].append(
+ (chng_field, chng_value, chng_time.isoformat())
+ )
+
+ ets, ots = attributes_per_type.get(ocel, parameters=parameters)
+
+ root = etree.Element("log")
+ object_types = etree.SubElement(root, "object-types")
+ for ot in ots:
+ object_type = etree.SubElement(object_types, "object-type")
+ object_type.set("name", str(ot))
+ object_type_attributes = etree.SubElement(object_type, "attributes")
+ if len(ots[ot]) > 0:
+ for k, v in ots[ot].items():
+ this_type = "string"
+ if "date" in v or "time" in v:
+ this_type = "date"
+ elif "float" in v or "double" in v:
+ this_type = "float"
+ object_type_attribute = etree.SubElement(
+ object_type_attributes, "attribute"
+ )
+ object_type_attribute.set("name", k)
+ object_type_attribute.set("type", this_type)
+
+ event_types = etree.SubElement(root, "event-types")
+ for et in ets:
+ event_type = etree.SubElement(event_types, "event-type")
+ event_type.set("name", str(et))
+ event_type_attributes = etree.SubElement(event_type, "attributes")
+ if len(ets[et]) > 0:
+ for k, v in ets[et].items():
+ this_type = "string"
+ if "date" in v or "time" in v:
+ this_type = "date"
+ elif "float" in v or "double" in v:
+ this_type = "float"
+ event_type_attribute = etree.SubElement(
+ event_type_attributes, "attribute"
+ )
+ event_type_attribute.set("name", k)
+ event_type_attribute.set("type", this_type)
+
+ objects = etree.SubElement(root, "objects")
+ for objid, obj in objects0.items():
+ object = etree.SubElement(objects, "object")
+ object.set("id", str(objid))
+ object.set("type", str(obj[object_type_column]))
+
+ object_attributes = etree.SubElement(object, "attributes")
+ if objid in object_changes3:
+ for val in object_changes3[objid]:
+ object_attribute = etree.SubElement(
+ object_attributes, "attribute"
+ )
+ object_attribute.set("name", val[0])
+ object_attribute.set("time", val[2])
+ object_attribute.text = str(
+ clean_dataframes.normalize_value(val[1])
+ )
+
+ if objid in o2o_dict:
+ object_objects = etree.SubElement(object, "objects")
+ for i in range(len(o2o_dict[objid][0])):
+ object_object = etree.SubElement(object_objects, RELOBJ_TAG)
+ object_object.set("object-id", o2o_dict[objid][0][i])
+ object_object.set("qualifier", o2o_dict[objid][1][i])
+
+ events = etree.SubElement(root, "events")
+ for evid, eve in events0.items():
+ event = etree.SubElement(events, "event")
+ event.set("id", str(evid))
+ event.set("type", str(eve[event_activity_column]))
+ event.set("time", eve[event_timestamp_column].isoformat())
+ event_attributes = etree.SubElement(event, "attributes")
+ event_objects = etree.SubElement(event, "objects")
+ if evid in relations0_obj_ids:
+ this_ids = relations0_obj_ids[evid]
+ this_qualifiers = relations0_qualifiers[evid]
+ for i in range(len(this_ids)):
+ event_object = etree.SubElement(event_objects, RELOBJ_TAG)
+ event_object.set("object-id", str(this_ids[i]))
+ event_object.set("qualifier", str(this_qualifiers[i]))
+ eve = {
+ x: y
+ for x, y in eve.items()
+ if not x.startswith("ocel:") and y is not None and not pd.isna(y)
+ }
+ if len(eve) > 0:
+ for k, v in eve.items():
+ event_attribute = etree.SubElement(
+ event_attributes, "attribute"
+ )
+ event_attribute.set("name", k)
+ event_attribute.text = str(
+ clean_dataframes.normalize_value(v)
+ )
+
+ tree = etree.ElementTree(root)
+
+ with compression.open_binary(target_path, "wb") as F:
+ tree.write(F, pretty_print=True, xml_declaration=True, encoding=encoding)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a391f8ab70950a22bf3ecf28b4ac0474b50cd2ef
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/__init__.py
@@ -0,0 +1,29 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer import bundled, csv, jsonocel
+import importlib.util
+
+if importlib.util.find_spec("lxml"):
+ from pm4py.objects.ocel.importer import xmlocel
+
+if importlib.util.find_spec("sqlite3"):
+ from pm4py.objects.ocel.importer import sqlite
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b15f57c3fdef081ac916a2520b69e1c5fd9a4833
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.bundled import importer, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a76d03143fc581cbe49276699ea6d8d80eb0185
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/importer.py
@@ -0,0 +1,42 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.importer.bundled.variants import ocel20
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ OCEL20 = ocel20
+
+
+def apply(
+ file_path: str,
+ variant=Variants.OCEL20,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Imports an OCEL 2.0 log from the bundled CSV/Parquet format.
+ """
+ return exec_utils.get_variant(variant).apply(file_path, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a0086a780d7725abfb2b33320c762724338b1e6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.bundled.variants import ocel20
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff855f5899852c2548680b6e05cc45857a0a1c54
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/bundled/variants/ocel20.py
@@ -0,0 +1,579 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from pathlib import PurePosixPath
+from typing import Optional, Dict, Any, List, Tuple
+import codecs
+import csv
+import io
+import json
+import math
+import os
+import re
+import zipfile
+
+import pandas as pd
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.util import constants as pm4_constants, exec_utils, pandas_utils
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ ENCODING = "encoding"
+
+
+_ATTRIBUTE_TYPES = {"string", "time", "integer", "float", "boolean"}
+_SAFE_FILENAME_BYTES = set(
+ b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-"
+)
+_INTEGER_RE = re.compile(r"^[+-]?\d+$")
+_FLOAT_RE = re.compile(
+ r"^[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:[eE][+-]?\d+)?$"
+)
+_TIMEZONE_RE = re.compile(r"(?:Z|[+-]\d{2}:?\d{2})$")
+
+
+def _instantiate_dataframe(records: List[Dict[str, Any]], columns: List[str]):
+ if records:
+ return pandas_utils.instantiate_dataframe(records)
+ return pandas_utils.instantiate_dataframe({column: [] for column in columns})
+
+
+def _require_utf8(encoding: str) -> str:
+ try:
+ normalized = codecs.lookup(encoding).name
+ except LookupError as exc:
+ raise ValueError("Unknown OCEL bundle encoding '%s'." % encoding) from exc
+ if normalized != "utf-8":
+ raise ValueError("OCEL bundle metadata and CSV tables must use UTF-8 encoding.")
+ return "utf-8"
+
+
+def _percent_encode(value: str) -> str:
+ encoded = []
+ for byte in value.encode("utf-8"):
+ encoded.append(chr(byte) if byte in _SAFE_FILENAME_BYTES else "%%%02X" % byte)
+ return "".join(encoded)
+
+
+def _validate_relative_path(path: Any, label: str) -> str:
+ if not isinstance(path, str) or not path or "\\" in path:
+ raise ValueError("%s must be a non-empty POSIX relative path." % label)
+ parsed = PurePosixPath(path)
+ if parsed.is_absolute() or any(part in {"", ".", ".."} for part in parsed.parts):
+ raise ValueError("%s must contain no root, '.' or '..' component." % label)
+ return path
+
+
+def _attribute_descriptors(
+ descriptor: Dict[str, Any], label: str, reserved: set
+) -> List[Tuple[str, str]]:
+ attributes = descriptor.get("attributes")
+ if not isinstance(attributes, list):
+ raise ValueError("%s attributes must be an array." % label)
+ result = []
+ names = set()
+ for attribute in attributes:
+ if not isinstance(attribute, dict):
+ raise ValueError("%s attribute declarations must be objects." % label)
+ name = attribute.get("name")
+ primitive_type = attribute.get("type")
+ if not isinstance(name, str) or not name:
+ raise ValueError("%s attribute names must be non-empty strings." % label)
+ if name in names:
+ raise ValueError("Duplicate attribute '%s' in %s metadata." % (name, label))
+ if name in reserved:
+ raise ValueError("Attribute '%s' collides with a fixed %s column." % (name, label))
+ if primitive_type not in _ATTRIBUTE_TYPES:
+ raise ValueError(
+ "Attribute '%s' in %s has unsupported type '%s'."
+ % (name, label, primitive_type)
+ )
+ names.add(name)
+ result.append((name, primitive_type))
+ return result
+
+
+def _validate_metadata(meta: Any) -> Dict[str, Any]:
+ if not isinstance(meta, dict):
+ raise ValueError("ocel-meta.json must contain a JSON object.")
+ if meta.get("ocelVersion") != "2.0":
+ raise ValueError("OCEL bundle ocelVersion must be '2.0'.")
+ if meta.get("bundleFormatVersion") != "1.0":
+ raise ValueError("OCEL bundle bundleFormatVersion must be '1.0'.")
+ storage_format = meta.get("storageFormat")
+ if storage_format not in {"csv", "parquet"}:
+ raise ValueError("OCEL bundle storageFormat must be 'csv' or 'parquet'.")
+ event_types = meta.get("eventTypes")
+ object_types = meta.get("objectTypes")
+ relations = meta.get("relations")
+ if not isinstance(event_types, dict) or not isinstance(object_types, dict):
+ raise ValueError("OCEL bundle eventTypes and objectTypes must be objects.")
+ if not isinstance(relations, dict):
+ raise ValueError("OCEL bundle relations must be an object.")
+
+ extension = storage_format
+ declared_paths = []
+ for event_type, descriptor in event_types.items():
+ if not isinstance(event_type, str) or not isinstance(descriptor, dict):
+ raise ValueError("Event type metadata entries must map strings to objects.")
+ expected = "events/event_%s.%s" % (_percent_encode(event_type), extension)
+ path = _validate_relative_path(descriptor.get("file"), "Event table path")
+ if path != expected:
+ raise ValueError("Event table for '%s' must be '%s'." % (event_type, expected))
+ descriptor["_attributes"] = _attribute_descriptors(
+ descriptor, "event type '%s'" % event_type, {"ocel_id", "ocel_time"}
+ )
+ declared_paths.append(path)
+
+ for object_type, descriptor in object_types.items():
+ if not isinstance(object_type, str) or not isinstance(descriptor, dict):
+ raise ValueError("Object type metadata entries must map strings to objects.")
+ encoded = _percent_encode(object_type)
+ expected = "objects/object_%s.%s" % (encoded, extension)
+ changes_expected = "object_changes/object_changes_%s.%s" % (
+ encoded,
+ extension,
+ )
+ path = _validate_relative_path(descriptor.get("file"), "Object table path")
+ changes_path = _validate_relative_path(
+ descriptor.get("changesFile"), "Object-change table path"
+ )
+ if path != expected or changes_path != changes_expected:
+ raise ValueError(
+ "Object tables for '%s' must use the deterministic bundle paths."
+ % object_type
+ )
+ descriptor["_attributes"] = _attribute_descriptors(
+ descriptor,
+ "object type '%s'" % object_type,
+ {"ocel_id", "ocel_time", "ocel_changed_field"},
+ )
+ declared_paths.extend([path, changes_path])
+
+ expected_e2o = "relations/e2o.%s" % extension
+ expected_o2o = "relations/o2o.%s" % extension
+ e2o_path = _validate_relative_path(relations.get("e2o"), "E2O table path")
+ o2o_path = _validate_relative_path(relations.get("o2o"), "O2O table path")
+ if e2o_path != expected_e2o or o2o_path != expected_o2o:
+ raise ValueError("Relation tables must use the deterministic bundle paths.")
+ declared_paths.extend([e2o_path, o2o_path])
+ if len(declared_paths) != len(set(declared_paths)):
+ raise ValueError("OCEL bundle metadata declares the same table path more than once.")
+ meta["_declared_paths"] = declared_paths
+ return meta
+
+
+def _read_meta(file_path: str, encoding: str) -> Dict[str, Any]:
+ if os.path.isdir(file_path):
+ meta_path = os.path.join(file_path, "ocel-meta.json")
+ with open(meta_path, "r", encoding=encoding) as file:
+ return _validate_metadata(json.load(file))
+ if not str(file_path).lower().endswith(".ocel.zip"):
+ raise ValueError("Bundled OCEL archives use the '.ocel.zip' extension.")
+ with zipfile.ZipFile(file_path, "r") as archive:
+ try:
+ content = archive.read("ocel-meta.json")
+ except KeyError as exc:
+ raise ValueError("OCEL bundle is missing root ocel-meta.json.") from exc
+ return _validate_metadata(json.loads(content.decode(encoding)))
+
+
+def _container_entries(file_path: str) -> set:
+ if os.path.isdir(file_path):
+ entries = set()
+ root = os.path.realpath(file_path)
+ for current_root, _, files in os.walk(file_path):
+ for filename in files:
+ full_path = os.path.join(current_root, filename)
+ real_path = os.path.realpath(full_path)
+ if os.path.commonpath([root, real_path]) != root:
+ raise ValueError("OCEL bundle table path escapes the container root.")
+ entries.add(os.path.relpath(full_path, file_path).replace(os.sep, "/"))
+ return entries
+
+ with zipfile.ZipFile(file_path, "r") as archive:
+ names = [info.filename for info in archive.infolist()]
+ if len(names) != len(set(names)):
+ raise ValueError("OCEL bundle archives cannot contain duplicate entry names.")
+ entries = set()
+ for name in names:
+ normalized = name[:-1] if name.endswith("/") else name
+ if normalized:
+ _validate_relative_path(normalized, "Archive entry name")
+ if not name.endswith("/"):
+ entries.add(name)
+ return entries
+
+
+def _validate_container(file_path: str, meta: Dict[str, Any]):
+ entries = _container_entries(file_path)
+ required = {"ocel-meta.json", *meta["_declared_paths"]}
+ missing = required.difference(entries)
+ if missing:
+ raise ValueError("OCEL bundle is missing declared tables: %s." % ", ".join(sorted(missing)))
+ opposite_extension = ".parquet" if meta["storageFormat"] == "csv" else ".csv"
+ mixed = sorted(path for path in entries if path.lower().endswith(opposite_extension))
+ if mixed:
+ raise ValueError("OCEL bundle mixes CSV and Parquet table files.")
+
+
+def _table_bytes(file_path: str, table_path: str) -> bytes:
+ if os.path.isdir(file_path):
+ root = os.path.realpath(file_path)
+ full_path = os.path.realpath(os.path.join(file_path, *table_path.split("/")))
+ if os.path.commonpath([root, full_path]) != root:
+ raise ValueError("OCEL bundle table path escapes the container root.")
+ with open(full_path, "rb") as file:
+ return file.read()
+ with zipfile.ZipFile(file_path, "r") as archive:
+ return archive.read(table_path)
+
+
+def _read_csv_table(data: bytes, encoding: str, table_path: str) -> pd.DataFrame:
+ try:
+ text = data.decode(encoding)
+ rows = list(csv.reader(io.StringIO(text, newline=""), dialect="excel", strict=True))
+ except (UnicodeDecodeError, csv.Error) as exc:
+ raise ValueError("Invalid UTF-8/RFC 4180 CSV table '%s'." % table_path) from exc
+ if not rows:
+ raise ValueError("CSV table '%s' must contain a header row." % table_path)
+ header = rows[0]
+ if len(header) != len(set(header)):
+ raise ValueError("CSV table '%s' has duplicate columns." % table_path)
+ for line_number, row in enumerate(rows[1:], start=2):
+ if len(row) != len(header):
+ raise ValueError(
+ "CSV table '%s' row %d has the wrong number of fields."
+ % (table_path, line_number)
+ )
+ return pandas_utils.instantiate_dataframe(rows[1:], columns=header, dtype="object")
+
+
+def _parse_time(value: str, label: str) -> pd.Timestamp:
+ if not isinstance(value, str) or not _TIMEZONE_RE.search(value):
+ raise ValueError("%s must be an ISO 8601 timestamp with timezone information." % label)
+ try:
+ return pd.to_datetime(value, utc=True)
+ except BaseException as exc:
+ raise ValueError("%s is not a valid ISO 8601 timestamp." % label) from exc
+
+
+def _parse_csv_value(value: str, primitive_type: str, label: str):
+ if value == "":
+ return None
+ if primitive_type == "string":
+ return value
+ if primitive_type == "integer":
+ if not _INTEGER_RE.match(value):
+ raise ValueError("%s is not a signed decimal integer." % label)
+ return int(value)
+ if primitive_type == "float":
+ if not _FLOAT_RE.match(value):
+ raise ValueError("%s is not a decimal floating-point number." % label)
+ parsed = float(value)
+ if not math.isfinite(parsed):
+ raise ValueError("%s is not a finite floating-point number." % label)
+ return parsed
+ if primitive_type == "boolean":
+ if value not in {"true", "false"}:
+ raise ValueError("%s must be 'true' or 'false'." % label)
+ return value == "true"
+ return _parse_time(value, label)
+
+
+def _arrow_type(primitive_type: str):
+ try:
+ import pyarrow as pa
+ except ImportError as exc:
+ raise ImportError("pyarrow is required for specification-compliant OCEL Parquet bundles.") from exc
+ return {
+ "string": pa.string(),
+ "integer": pa.int64(),
+ "float": pa.float64(),
+ "boolean": pa.bool_(),
+ "time": pa.timestamp("us", tz="UTC"),
+ }[primitive_type]
+
+
+def _read_table(
+ file_path: str,
+ table_path: str,
+ storage_format: str,
+ encoding: str,
+ fixed: List[Tuple[str, str]],
+ attributes: List[Tuple[str, str]],
+ non_empty_fixed: set,
+) -> pd.DataFrame:
+ data = _table_bytes(file_path, table_path)
+ expected = fixed + attributes
+ expected_names = [name for name, _ in expected]
+ if storage_format == "csv":
+ dataframe = _read_csv_table(data, encoding, table_path)
+ if set(dataframe.columns) != set(expected_names):
+ raise ValueError("CSV table '%s' columns do not match its metadata." % table_path)
+ dataframe = dataframe[expected_names]
+ fixed_names = {name for name, _ in fixed}
+ for name, primitive_type in expected:
+ if name in fixed_names and primitive_type == "string":
+ values = dataframe[name].tolist()
+ else:
+ values = [
+ _parse_csv_value(value, primitive_type, "%s.%s" % (table_path, name))
+ for value in dataframe[name].tolist()
+ ]
+ if primitive_type == "time":
+ dataframe[name] = pd.to_datetime(values, utc=True)
+ else:
+ dataframe[name] = pd.Series(
+ values, index=dataframe.index, dtype="object"
+ )
+ else:
+ try:
+ import pyarrow.parquet as pq
+ except ImportError as exc:
+ raise ImportError("pyarrow is required for specification-compliant OCEL Parquet bundles.") from exc
+ table = pq.read_table(io.BytesIO(data))
+ if set(table.column_names) != set(expected_names):
+ raise ValueError("Parquet table '%s' columns do not match its metadata." % table_path)
+ schema = table.schema
+ fixed_names = {name for name, _ in fixed}
+ for name, primitive_type in expected:
+ field = schema.field(name)
+ if field.type != _arrow_type(primitive_type):
+ raise ValueError(
+ "Parquet column '%s.%s' has type %s; expected %s."
+ % (table_path, name, field.type, _arrow_type(primitive_type))
+ )
+ if name in fixed_names and field.nullable:
+ raise ValueError("Parquet fixed column '%s.%s' must be required." % (table_path, name))
+ if name not in fixed_names and not field.nullable:
+ raise ValueError("Parquet attribute column '%s.%s' must be optional." % (table_path, name))
+ dataframe = table.select(expected_names).to_pandas()
+
+ for name, primitive_type in expected:
+ if primitive_type == "time":
+ dataframe[name] = pd.to_datetime(dataframe[name], utc=True)
+ else:
+ dataframe[name] = pd.Series(
+ [None if pd.isna(value) else value for value in dataframe[name].tolist()],
+ index=dataframe.index,
+ dtype="object",
+ )
+
+ for name in non_empty_fixed:
+ if dataframe[name].isna().any() or (dataframe[name].astype(str) == "").any():
+ raise ValueError("Fixed column '%s.%s' cannot contain missing values." % (table_path, name))
+ return dataframe
+
+
+def _reject_duplicates(dataframe: pd.DataFrame, columns: List[str], label: str):
+ if len(dataframe) > 0 and dataframe.duplicated(subset=columns).any():
+ raise ValueError("%s contains duplicate rows for its OCEL set key." % label)
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """Imports an OCEL 2.0 log from the bundled CSV/Parquet format."""
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+ encoding = _require_utf8(encoding)
+ event_id = exec_utils.get_param_value(Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID)
+ event_activity = exec_utils.get_param_value(Parameters.EVENT_ACTIVITY, parameters, constants.DEFAULT_EVENT_ACTIVITY)
+ event_timestamp = exec_utils.get_param_value(Parameters.EVENT_TIMESTAMP, parameters, constants.DEFAULT_EVENT_TIMESTAMP)
+ object_id = exec_utils.get_param_value(Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID)
+ object_type = exec_utils.get_param_value(Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE)
+ internal_index = exec_utils.get_param_value(Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX)
+ qualifier = exec_utils.get_param_value(Parameters.QUALIFIER, parameters, constants.DEFAULT_QUALIFIER)
+ changed_field = exec_utils.get_param_value(Parameters.CHANGED_FIELD, parameters, constants.DEFAULT_CHNGD_FIELD)
+
+ file_path = str(file_path)
+ meta = _read_meta(file_path, encoding)
+ _validate_container(file_path, meta)
+ storage_format = meta["storageFormat"]
+
+ event_frames = []
+ event_id_type = {}
+ event_id_time = {}
+ for event_type_name, descriptor in meta["eventTypes"].items():
+ attributes = descriptor["_attributes"]
+ dataframe = _read_table(
+ file_path,
+ descriptor["file"],
+ storage_format,
+ encoding,
+ [("ocel_id", "string"), ("ocel_time", "time")],
+ attributes,
+ {"ocel_id", "ocel_time"},
+ ).rename(columns={"ocel_id": event_id, "ocel_time": event_timestamp})
+ for eid, timestamp in dataframe[[event_id, event_timestamp]].itertuples(index=False, name=None):
+ if eid in event_id_type:
+ raise ValueError("Event id '%s' occurs more than once in the bundle." % eid)
+ event_id_type[eid] = event_type_name
+ event_id_time[eid] = timestamp
+ dataframe[event_activity] = event_type_name
+ event_frames.append(dataframe)
+
+ object_frames = []
+ object_change_frames = []
+ object_id_type = {}
+ for object_type_name, descriptor in meta["objectTypes"].items():
+ attributes = descriptor["_attributes"]
+ dataframe = _read_table(
+ file_path,
+ descriptor["file"],
+ storage_format,
+ encoding,
+ [("ocel_id", "string")],
+ attributes,
+ {"ocel_id"},
+ ).rename(columns={"ocel_id": object_id})
+ for oid in dataframe[object_id].tolist():
+ if oid in object_id_type:
+ raise ValueError("Object id '%s' occurs more than once in the bundle." % oid)
+ object_id_type[oid] = object_type_name
+ dataframe[object_type] = object_type_name
+ object_frames.append(dataframe)
+
+ changes = _read_table(
+ file_path,
+ descriptor["changesFile"],
+ storage_format,
+ encoding,
+ [
+ ("ocel_id", "string"),
+ ("ocel_time", "time"),
+ ("ocel_changed_field", "string"),
+ ],
+ attributes,
+ {"ocel_id", "ocel_time", "ocel_changed_field"},
+ ).rename(
+ columns={
+ "ocel_id": object_id,
+ "ocel_time": event_timestamp,
+ "ocel_changed_field": changed_field,
+ }
+ )
+ changes[object_type] = object_type_name
+ attribute_names = {name for name, _ in attributes}
+ for record in changes.to_dict(orient="records"):
+ oid = record[object_id]
+ field = record[changed_field]
+ if field not in attribute_names:
+ raise ValueError("Object-change field '%s' is not declared." % field)
+ if pd.Timestamp(record[event_timestamp]).value == 0:
+ raise ValueError(
+ "Object-change tables cannot contain assignments at the UNIX epoch; "
+ "initial values belong in the object table."
+ )
+ if pd.isna(record.get(field)):
+ raise ValueError("Object-change row for '%s' has no changed value." % oid)
+ if any(
+ name != field and not pd.isna(record.get(name))
+ for name in attribute_names
+ ):
+ raise ValueError("An object-change row must assign exactly one attribute.")
+ object_change_frames.append(changes)
+
+ events = pandas_utils.concat(event_frames, ignore_index=True) if event_frames else _instantiate_dataframe([], [event_id, event_timestamp, event_activity])
+ objects = pandas_utils.concat(object_frames, ignore_index=True) if object_frames else _instantiate_dataframe([], [object_id, object_type])
+ object_changes = pandas_utils.concat(object_change_frames, ignore_index=True) if object_change_frames else _instantiate_dataframe([], [object_id, event_timestamp, changed_field, object_type])
+ _reject_duplicates(
+ object_changes,
+ [object_id, event_timestamp, changed_field],
+ "Object-change tables",
+ )
+
+ for oid, change_type in object_changes[[object_id, object_type]].itertuples(index=False, name=None):
+ if object_id_type.get(oid) != change_type:
+ raise ValueError("Object change references an unknown or differently typed object '%s'." % oid)
+
+ relations_meta = meta["relations"]
+ e2o = _read_table(
+ file_path,
+ relations_meta["e2o"],
+ storage_format,
+ encoding,
+ [
+ ("ocel_event_id", "string"),
+ ("ocel_object_id", "string"),
+ ("ocel_qualifier", "string"),
+ ],
+ [],
+ {"ocel_event_id", "ocel_object_id"},
+ ).rename(columns={"ocel_event_id": event_id, "ocel_object_id": object_id, "ocel_qualifier": qualifier})
+ _reject_duplicates(e2o, [event_id, object_id, qualifier], "E2O table")
+ if any(eid not in event_id_type for eid in e2o[event_id].tolist()):
+ raise ValueError("E2O table references an unknown event.")
+ if any(oid not in object_id_type for oid in e2o[object_id].tolist()):
+ raise ValueError("E2O table references an unknown object.")
+ e2o[event_activity] = e2o[event_id].map(event_id_type)
+ e2o[event_timestamp] = e2o[event_id].map(event_id_time)
+ e2o[object_type] = e2o[object_id].map(object_id_type)
+
+ o2o = _read_table(
+ file_path,
+ relations_meta["o2o"],
+ storage_format,
+ encoding,
+ [
+ ("ocel_source_id", "string"),
+ ("ocel_target_id", "string"),
+ ("ocel_qualifier", "string"),
+ ],
+ [],
+ {"ocel_source_id", "ocel_target_id"},
+ ).rename(columns={"ocel_source_id": object_id, "ocel_target_id": object_id + "_2", "ocel_qualifier": qualifier})
+ _reject_duplicates(o2o, [object_id, object_id + "_2", qualifier], "O2O table")
+ if any(oid not in object_id_type for oid in o2o[object_id].tolist()):
+ raise ValueError("O2O table references an unknown source object.")
+ if any(oid not in object_id_type for oid in o2o[object_id + "_2"].tolist()):
+ raise ValueError("O2O table references an unknown target object.")
+
+ for dataframe in (events, e2o, object_changes):
+ if len(dataframe) > 0:
+ dataframe[internal_index] = dataframe.index
+ dataframe.sort_values([event_timestamp, internal_index], inplace=True)
+ del dataframe[internal_index]
+
+ ocel = OCEL(
+ events=events,
+ objects=objects,
+ relations=e2o,
+ o2o=o2o,
+ object_changes=object_changes,
+ parameters=parameters,
+ )
+ return ocel_consistency.apply(ocel, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..04b82720c3fcce701b7d9c6146835c1d8da20275
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.csv import variants, importer
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a135f11a96276610f26200d295a4bc4e47cfb0f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/importer.py
@@ -0,0 +1,63 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.importer.csv.variants import pandas, ocel20
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ PANDAS = pandas
+ OCEL20 = ocel20
+
+
+def apply(
+ file_path: str,
+ objects_path: str = None,
+ variant=Variants.PANDAS,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Imports an object-centric event log from a CSV file
+
+ Parameters
+ -----------------
+ file_path
+ Path to the object-centric event log
+ objects_path
+ Optional path to a CSV file containing the objects dataframe
+ variant
+ Variant of the algorithm that should be used, possible values:
+ - Variants.PANDAS
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ------------------
+ ocel
+ Object-centric event log
+ """
+ return exec_utils.get_variant(variant).apply(
+ file_path, objects_path, parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b691b636dc82389ac490c02a548c951c43c9524f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.csv.variants import pandas, ocel20
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f755132b8a0ea40c34c733852039fae9afe4bd5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/ocel20.py
@@ -0,0 +1,851 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any, List, Tuple
+import codecs
+import csv
+from decimal import Decimal
+import json
+import math
+import re
+
+import pandas as pd
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.util import exec_utils, constants as pm4_constants, pandas_utils
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ ENCODING = "encoding"
+ OBJECT_TYPE_PREFIX = "object_type_prefix"
+ O2O_ACTIVITY = "o2o_activity"
+ CSV_EVENT_ID = "csv_event_id"
+ CSV_EVENT_ACTIVITY = "csv_event_activity"
+ CSV_EVENT_TIMESTAMP = "csv_event_timestamp"
+
+
+def _is_empty(value) -> bool:
+ if value is None:
+ return True
+ try:
+ if pd.isna(value):
+ return True
+ except BaseException:
+ pass
+ return str(value) == ""
+
+
+def _strip_value(value) -> str:
+ if _is_empty(value):
+ return ""
+ return str(value).strip()
+
+
+def _split_entries(value: Any) -> List[str]:
+ if _is_empty(value):
+ return []
+
+ value = str(value)
+ if not any(char in value for char in ("/", "{", "\\")):
+ return [value] if value else []
+
+ entries = []
+ current = []
+ in_string = False
+ escape = False
+ json_depth = 0
+
+ for char in value:
+ if escape:
+ current.append(char)
+ escape = False
+ continue
+ if char == "\\":
+ current.append(char)
+ if json_depth == 0 or in_string:
+ escape = True
+ continue
+ if char == '"':
+ current.append(char)
+ if json_depth > 0:
+ in_string = not in_string
+ continue
+ if not in_string:
+ if char == "{":
+ json_depth += 1
+ elif char == "}" and json_depth > 0:
+ json_depth -= 1
+ elif char == "/" and json_depth == 0:
+ entry = "".join(current)
+ if not entry:
+ raise ValueError("Object reference cells cannot contain empty references.")
+ entries.append(entry)
+ current = []
+ continue
+ current.append(char)
+
+ if escape:
+ raise ValueError("Object reference cells cannot end with a dangling escape character.")
+ entry = "".join(current)
+ if not entry:
+ raise ValueError("Object reference cells cannot contain empty references.")
+ entries.append(entry)
+ return entries
+
+
+def _find_unescaped(value: str, target: str) -> int:
+ escape = False
+ for index, char in enumerate(value):
+ if escape:
+ escape = False
+ elif char == "\\":
+ escape = True
+ elif char == target:
+ return index
+ return -1
+
+
+def _unescape_reference_part(value: str, name: str) -> str:
+ result = []
+ escape = False
+ for char in value:
+ if escape:
+ if char not in ("/", "#", "{", "\\"):
+ raise ValueError(
+ "Invalid escape sequence '\\%s' in an OCEL2 CSV %s." % (char, name)
+ )
+ result.append(char)
+ escape = False
+ elif char == "\\":
+ escape = True
+ elif char in ("/", "#", "{"):
+ raise ValueError(
+ "Unescaped '%s' in an OCEL2 CSV %s; escape it as '\\%s'." % (char, name, char)
+ )
+ else:
+ result.append(char)
+ if escape:
+ raise ValueError("Dangling escape character in an OCEL2 CSV %s." % name)
+ return "".join(result)
+
+
+def _split_reference(value: str) -> Tuple[str, Optional[str], Dict[str, Any]]:
+ attrs = {}
+ value = value.strip()
+
+ json_start = _find_unescaped(value, "{")
+ if json_start >= 0:
+ json_part = value[json_start:]
+ value = value[:json_start]
+ attrs = json.loads(
+ json_part,
+ parse_constant=lambda constant: (_ for _ in ()).throw(
+ ValueError(
+ "Non-finite JSON number '%s' is not valid JSON."
+ % constant
+ )
+ ),
+ )
+ if not isinstance(attrs, dict):
+ raise ValueError("Object reference JSON attributes must be a JSON object.")
+
+ hash_pos = _find_unescaped(value, "#")
+ if hash_pos >= 0:
+ object_id, qualifier = value[:hash_pos], value[hash_pos + 1:]
+ else:
+ object_id, qualifier = value, None
+
+ object_id = _unescape_reference_part(object_id, "object id").strip()
+ qualifier = (
+ _unescape_reference_part(qualifier, "qualifier").strip()
+ if qualifier is not None
+ else None
+ )
+
+ if not object_id:
+ raise ValueError("Object references must contain a non-empty object id.")
+ _validate_attribute_values(attrs)
+
+ return object_id, qualifier, attrs
+
+
+def _validate_attribute_values(attrs: Dict[str, Any]):
+ for value in attrs.values():
+ if isinstance(value, (list, dict)):
+ raise ValueError("JSON arrays and objects are not valid OCEL2 CSV attribute values.")
+ if isinstance(value, float) and not math.isfinite(value):
+ raise ValueError("Non-finite JSON numbers are not valid OCEL2 CSV attribute values.")
+
+
+def _register_object_type(
+ object_id_type: Dict[str, str], object_id: str, object_type: str
+):
+ existing = object_id_type.get(object_id)
+ if existing is not None and existing != object_type:
+ raise ValueError(
+ "Object '%s' appears with multiple object types: '%s' and '%s'."
+ % (object_id, existing, object_type)
+ )
+ object_id_type[object_id] = object_type
+
+
+def _instantiate_dataframe(records: List[Dict[str, Any]], columns: List[str]):
+ if records:
+ return pandas_utils.instantiate_dataframe(records)
+ return pandas_utils.instantiate_dataframe({column: [] for column in columns})
+
+
+_TIMEZONE_RE = re.compile(r"(?:Z|[+-]\d{2}:?\d{2})$")
+_CANONICAL_INTEGER_RE = re.compile(r"^-?(?:0|[1-9]\d*)$")
+_INT64_MIN = -(2 ** 63)
+_INT64_MAX = 2 ** 63 - 1
+_EPOCH = pd.Timestamp("1970-01-01T00:00:00Z")
+
+
+def _parse_canonical_integer(text: str):
+ """Parses text only when it is the canonical form of a 64-bit integer."""
+ if not _CANONICAL_INTEGER_RE.match(text):
+ return None
+ parsed = int(text)
+ if parsed < _INT64_MIN or parsed > _INT64_MAX:
+ return None
+ return parsed
+
+
+def _parse_canonical_float(text: str):
+ """Parses text only when it round-trips through an IEEE 754 double."""
+ try:
+ parsed = float(text)
+ except ValueError:
+ return None
+ if not math.isfinite(parsed):
+ return None
+ if repr(parsed) == text:
+ return parsed
+ integer = _parse_canonical_integer(text)
+ if integer is not None and float(integer) == integer:
+ return float(integer)
+ return None
+
+
+def _parse_timestamp(value, strip_whitespace=True):
+ value = _strip_value(value) if strip_whitespace else str(value)
+ if not value:
+ return ""
+ if not _TIMEZONE_RE.search(value):
+ raise ValueError("Timestamp '%s' does not contain timezone information." % value)
+ try:
+ return pd.to_datetime(value, utc=True)
+ except BaseException as exc:
+ raise ValueError("Timestamp '%s' cannot be parsed." % value) from exc
+
+
+def _parse_timestamp_column(series):
+ non_empty = series != ""
+ if not non_empty.any():
+ return [""] * len(series)
+
+ missing_timezone = non_empty & ~series.str.contains(_TIMEZONE_RE, regex=True)
+ if missing_timezone.any():
+ value = series[missing_timezone].iloc[0]
+ raise ValueError("Timestamp '%s' does not contain timezone information." % value)
+
+ parsed = pd.Series([""] * len(series), index=series.index, dtype="object")
+ try:
+ parsed_values = pd.to_datetime(series[non_empty], utc=True, format="mixed")
+ except TypeError:
+ parsed_values = pd.to_datetime(series[non_empty], utc=True)
+ except BaseException as exc:
+ raise ValueError("At least one timestamp cannot be parsed.") from exc
+
+ parsed.loc[non_empty] = list(parsed_values)
+ return parsed.tolist()
+
+
+def _collect_object_attribute(
+ object_attributes: Dict[Tuple[str, str], List[Tuple[int, Any, Any]]],
+ object_id: str,
+ attribute: str,
+ timestamp: Any,
+ value: Any,
+ index: int,
+):
+ object_attributes.setdefault((object_id, attribute), []).append((index, timestamp, value))
+
+
+def _attribute_sort_key(item):
+ index, timestamp, _ = item
+ if _is_empty(timestamp):
+ return (0, "", index)
+ return (1, pd.Timestamp(timestamp).isoformat(), index)
+
+
+def _try_parse_integer(values):
+ parsed = []
+ for value in values:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ parsed.append(value)
+ elif isinstance(value, str):
+ parsed_value = _parse_canonical_integer(value)
+ if parsed_value is None:
+ return None
+ parsed.append(parsed_value)
+ else:
+ return None
+ return parsed
+
+
+def _try_parse_float(values):
+ parsed = []
+ for value in values:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ parsed_value = float(value)
+ elif isinstance(value, str):
+ parsed_value = _parse_canonical_float(value)
+ if parsed_value is None:
+ return None
+ else:
+ return None
+ if not math.isfinite(parsed_value):
+ return None
+ parsed.append(parsed_value)
+ return parsed
+
+
+def _try_parse_boolean(values):
+ parsed = []
+ for value in values:
+ if isinstance(value, bool):
+ parsed.append(value)
+ elif isinstance(value, str) and value.casefold() in {"true", "false"}:
+ parsed.append(value.casefold() == "true")
+ else:
+ return None
+ return parsed
+
+
+def _try_parse_timestamp_values(values):
+ parsed = []
+ for value in values:
+ if isinstance(value, pd.Timestamp):
+ parsed.append(value)
+ elif isinstance(value, str):
+ try:
+ parsed.append(_parse_timestamp(value, strip_whitespace=False))
+ except ValueError:
+ return None
+ else:
+ return None
+ return parsed
+
+
+def _infer_values(values):
+ non_empty = [value for value in values if not _is_empty(value)]
+ if not non_empty:
+ return values
+
+ for parser in (
+ _try_parse_integer,
+ _try_parse_float,
+ _try_parse_boolean,
+ _try_parse_timestamp_values,
+ ):
+ parsed = parser(non_empty)
+ if parsed is not None:
+ iterator = iter(parsed)
+ return [next(iterator) if not _is_empty(value) else value for value in values]
+
+ return [str(value) if not _is_empty(value) else value for value in values]
+
+
+def _infer_column_type(df, column):
+ if len(df) == 0 or column not in df.columns:
+ return df
+ df = df.copy()
+ df[column] = _infer_values(df[column].tolist())
+ return df
+
+
+def _infer_event_attribute_types(df, attribute_columns):
+ for column in attribute_columns:
+ df = _infer_column_type(df, column)
+ return df
+
+
+def _infer_object_attribute_types(objects_df, object_changes_df, object_type_column, excluded_columns):
+ if len(objects_df) == 0:
+ return objects_df, object_changes_df
+
+ attribute_columns = [
+ column for column in objects_df.columns if column not in excluded_columns
+ ]
+ if len(object_changes_df) > 0:
+ for column in object_changes_df.columns:
+ if column not in excluded_columns and column not in attribute_columns:
+ attribute_columns.append(column)
+
+ objects_df = objects_df.copy()
+ object_changes_df = object_changes_df.copy()
+ object_type_indexes = {
+ object_type: objects_df.index[objects_df[object_type_column] == object_type].tolist()
+ for object_type in pandas_utils.format_unique(objects_df[object_type_column].dropna().unique())
+ }
+ change_type_indexes = {}
+ if len(object_changes_df) > 0 and object_type_column in object_changes_df.columns:
+ change_type_indexes = {
+ object_type: object_changes_df.index[
+ object_changes_df[object_type_column] == object_type
+ ].tolist()
+ for object_type in pandas_utils.format_unique(
+ object_changes_df[object_type_column].dropna().unique()
+ )
+ }
+
+ for column in attribute_columns:
+ if column not in objects_df.columns:
+ objects_df[column] = None
+ if column not in object_changes_df.columns:
+ object_changes_df[column] = None
+ objects_df[column] = objects_df[column].astype("object")
+ object_changes_df[column] = object_changes_df[column].astype("object")
+
+ for object_type, object_indexes in object_type_indexes.items():
+ change_indexes_for_type = change_type_indexes.get(object_type, [])
+ for column in attribute_columns:
+ values = []
+ change_indexes = []
+
+ values.extend(objects_df.loc[object_indexes, column].tolist())
+ change_indexes = change_indexes_for_type
+ values.extend(object_changes_df.loc[change_indexes, column].tolist())
+
+ inferred = _infer_values(values)
+ pos = 0
+ if object_indexes:
+ objects_df.loc[object_indexes, column] = inferred[pos:pos + len(object_indexes)]
+ pos += len(object_indexes)
+ if change_indexes:
+ object_changes_df.loc[change_indexes, column] = inferred[pos:pos + len(change_indexes)]
+
+ return objects_df, object_changes_df
+
+
+def _read_rfc4180(file_path: str, encoding: str) -> pd.DataFrame:
+ try:
+ with open(file_path, "r", encoding=encoding, newline="") as file:
+ rows = list(csv.reader(file, dialect="excel", strict=True))
+ except csv.Error as exc:
+ raise ValueError("Invalid RFC 4180 CSV syntax.") from exc
+
+ if not rows:
+ raise ValueError("An OCEL2 CSV file must contain a header row.")
+
+ header = rows[0]
+ if len(header) != len(set(header)):
+ raise ValueError("OCEL2 CSV column names must be unique.")
+ for line_number, row in enumerate(rows[1:], start=2):
+ if len(row) != len(header):
+ raise ValueError(
+ "CSV row %d has %d fields; expected %d."
+ % (line_number, len(row), len(header))
+ )
+ return pandas_utils.instantiate_dataframe(rows[1:], columns=header, dtype="object")
+
+
+def _require_utf8(encoding: str) -> str:
+ try:
+ normalized = codecs.lookup(encoding).name
+ except LookupError as exc:
+ raise ValueError("Unknown OCEL2 CSV encoding '%s'." % encoding) from exc
+ if normalized != "utf-8":
+ raise ValueError("OCEL2 CSV files must use UTF-8 encoding.")
+ return "utf-8"
+
+
+def _attribute_value_key(value: Any):
+ if value is None:
+ return ("null", None)
+ if isinstance(value, bool):
+ return ("boolean", value)
+ if isinstance(value, (int, float)):
+ return ("number", Decimal(str(value)))
+ return ("string", value)
+
+
+def _deduplicate_assignments(object_id: str, attribute: str, values):
+ unique = []
+ by_timestamp = {}
+ for index, timestamp, value in sorted(values, key=_attribute_sort_key):
+ normalized_timestamp = _EPOCH if _is_empty(timestamp) else pd.Timestamp(timestamp)
+ value_key = _attribute_value_key(value)
+ if normalized_timestamp in by_timestamp:
+ if by_timestamp[normalized_timestamp] != value_key:
+ raise ValueError(
+ "Object attribute '%s' of object '%s' has different values at timestamp %s."
+ % (attribute, object_id, normalized_timestamp.isoformat())
+ )
+ continue
+ by_timestamp[normalized_timestamp] = value_key
+ unique.append((index, normalized_timestamp, value))
+ return unique
+
+
+def apply(
+ file_path: str,
+ objects_path: str = None,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Imports an OCEL 2.0 object-centric event log from the compact CSV format.
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+ encoding = _require_utf8(encoding)
+ event_id_column = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID
+ )
+ event_activity_column = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, constants.DEFAULT_EVENT_ACTIVITY
+ )
+ event_timestamp_column = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP, parameters, constants.DEFAULT_EVENT_TIMESTAMP
+ )
+ object_id_column = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID
+ )
+ object_type_column = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE
+ )
+ internal_index_column = exec_utils.get_param_value(
+ Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX
+ )
+ qualifier_column = exec_utils.get_param_value(
+ Parameters.QUALIFIER, parameters, constants.DEFAULT_QUALIFIER
+ )
+ changed_field_column = exec_utils.get_param_value(
+ Parameters.CHANGED_FIELD, parameters, constants.DEFAULT_CHNGD_FIELD
+ )
+ object_type_prefix = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE_PREFIX, parameters, "ot:"
+ )
+ o2o_activity = exec_utils.get_param_value(
+ Parameters.O2O_ACTIVITY, parameters, "o2o"
+ )
+ csv_event_id = exec_utils.get_param_value(
+ Parameters.CSV_EVENT_ID, parameters, "id"
+ )
+ csv_event_activity = exec_utils.get_param_value(
+ Parameters.CSV_EVENT_ACTIVITY, parameters, "activity"
+ )
+ csv_event_timestamp = exec_utils.get_param_value(
+ Parameters.CSV_EVENT_TIMESTAMP, parameters, "timestamp"
+ )
+
+ table = _read_rfc4180(file_path, encoding)
+ for column in (csv_event_id, csv_event_activity, csv_event_timestamp):
+ if column not in table.columns:
+ raise ValueError("Missing required OCEL2 CSV column '%s'." % column)
+ table[csv_event_id] = table[csv_event_id].astype(str).str.strip()
+ table[csv_event_activity] = table[csv_event_activity].astype(str).str.strip()
+ table[csv_event_timestamp] = table[csv_event_timestamp].astype(str).str.strip()
+ parsed_timestamps = _parse_timestamp_column(table[csv_event_timestamp])
+
+ object_type_columns = [
+ column for column in table.columns if str(column).startswith(object_type_prefix)
+ ]
+ if any(str(column) == object_type_prefix for column in object_type_columns):
+ raise ValueError("OCEL2 CSV object type columns must name an object type.")
+ event_attribute_columns = [
+ column
+ for column in table.columns
+ if column not in {csv_event_id, csv_event_activity, csv_event_timestamp}
+ and column not in object_type_columns
+ ]
+
+ events = []
+ relations = []
+ o2o = []
+ object_id_type = {}
+ object_attributes = {}
+ declared_object_types = {}
+ event_ids = set()
+ relation_keys = set()
+ o2o_keys = set()
+
+ records = table.to_dict(orient="records")
+ object_type_column_pairs = [
+ (column, str(column)[len(object_type_prefix):]) for column in object_type_columns
+ ]
+
+ for index, row in enumerate(records):
+ row_id = row.get(csv_event_id, "")
+ row_activity = row.get(csv_event_activity, "")
+ row_timestamp = row.get(csv_event_timestamp, "")
+ parsed_timestamp = parsed_timestamps[index]
+
+ is_o2o_row = (
+ bool(row_activity)
+ and row_activity.casefold() == str(o2o_activity).casefold()
+ )
+ is_object_attribute_row = not row_id and not row_activity and bool(row_timestamp)
+ is_object_declaration_row = not row_id and not row_activity and not row_timestamp
+ is_event_row = bool(row_id) and bool(row_activity) and bool(row_timestamp) and not is_o2o_row
+
+ if is_o2o_row:
+ if not row_id:
+ raise ValueError("Object-to-object rows must contain a source object id.")
+ elif not (is_event_row or is_object_attribute_row or is_object_declaration_row):
+ raise ValueError(
+ "Invalid OCEL2 CSV row %d: unsupported id/activity/timestamp combination."
+ % (index + 2)
+ )
+
+ if not is_event_row and any(
+ not _is_empty(row.get(column, "")) for column in event_attribute_columns
+ ):
+ raise ValueError(
+ "Event attribute values are only valid in event rows (CSV row %d)."
+ % (index + 2)
+ )
+
+ if is_event_row:
+ if row_id in event_ids:
+ raise ValueError("Duplicate event id '%s' in OCEL2 CSV file." % row_id)
+ event_ids.add(row_id)
+ event = {
+ event_id_column: row_id,
+ event_activity_column: row_activity,
+ event_timestamp_column: parsed_timestamp,
+ }
+ for column in event_attribute_columns:
+ if not _is_empty(row.get(column, "")):
+ event[column] = row[column]
+ events.append(event)
+
+ if is_o2o_row:
+ if row_id not in declared_object_types:
+ raise ValueError(
+ "Source object '%s' in an object-to-object row has no previously declared object type."
+ % row_id
+ )
+ reference_count = 0
+ for column, object_type in object_type_column_pairs:
+ for entry in _split_entries(row.get(column, "")):
+ reference_count += 1
+ object_id, qualifier, attrs = _split_reference(entry)
+
+ _register_object_type(object_id_type, object_id, object_type)
+
+ if is_event_row:
+ declared_object_types[object_id] = object_type
+ relation_key = (
+ row_id,
+ object_id,
+ "" if qualifier is None else qualifier,
+ )
+ if relation_key in relation_keys:
+ raise ValueError("Duplicate event-to-object relation in OCEL2 CSV file.")
+ relation_keys.add(relation_key)
+ relations.append(
+ {
+ event_id_column: row_id,
+ event_activity_column: row_activity,
+ event_timestamp_column: parsed_timestamp,
+ object_id_column: object_id,
+ object_type_column: object_type,
+ qualifier_column: "" if qualifier is None else qualifier,
+ }
+ )
+ for attr, value in attrs.items():
+ _collect_object_attribute(
+ object_attributes, object_id, attr, parsed_timestamp, value, index
+ )
+ elif is_o2o_row:
+ declared_object_types[object_id] = object_type
+ o2o_key = (
+ row_id,
+ object_id,
+ "" if qualifier is None else qualifier,
+ )
+ if o2o_key in o2o_keys:
+ raise ValueError("Duplicate object-to-object relation in OCEL2 CSV file.")
+ o2o_keys.add(o2o_key)
+ o2o.append(
+ {
+ object_id_column: row_id,
+ object_id_column + "_2": object_id,
+ qualifier_column: "" if qualifier is None else qualifier,
+ }
+ )
+ if attrs and not parsed_timestamp:
+ raise ValueError(
+ "Object-to-object rows with JSON attributes must contain a timestamp."
+ )
+ for attr, value in attrs.items():
+ _collect_object_attribute(
+ object_attributes, object_id, attr, parsed_timestamp, value, index
+ )
+ elif is_object_attribute_row:
+ declared_object_types[object_id] = object_type
+ if not attrs:
+ raise ValueError(
+ "Object attribute rows must contain JSON attributes."
+ )
+ for attr, value in attrs.items():
+ _collect_object_attribute(
+ object_attributes, object_id, attr, parsed_timestamp, value, index
+ )
+ elif is_object_declaration_row:
+ if qualifier is not None:
+ raise ValueError(
+ "Object declaration rows cannot contain qualifiers."
+ )
+ declared_object_types[object_id] = object_type
+ for attr, value in attrs.items():
+ _collect_object_attribute(
+ object_attributes, object_id, attr, None, value, index
+ )
+
+ if is_object_attribute_row and reference_count == 0:
+ raise ValueError("Object attribute rows must contain an object reference.")
+ if is_o2o_row and reference_count == 0:
+ raise ValueError("Object-to-object rows must contain a target object reference.")
+
+ events_df = _instantiate_dataframe(
+ events, [event_id_column, event_activity_column, event_timestamp_column]
+ )
+ relations_df = _instantiate_dataframe(
+ relations,
+ [
+ event_id_column,
+ event_activity_column,
+ event_timestamp_column,
+ object_id_column,
+ object_type_column,
+ qualifier_column,
+ ],
+ )
+ o2o_df = _instantiate_dataframe(
+ o2o, [object_id_column, object_id_column + "_2", qualifier_column]
+ )
+
+ events_df = _infer_event_attribute_types(events_df, event_attribute_columns)
+
+ if object_id_type:
+ object_records = []
+ for object_id, object_type in object_id_type.items():
+ object_records.append(
+ {object_id_column: object_id, object_type_column: object_type}
+ )
+ else:
+ object_records = []
+
+ object_changes = []
+ object_records_by_id = {record[object_id_column]: record for record in object_records}
+
+ for (object_id, attr), values in object_attributes.items():
+ values = _deduplicate_assignments(object_id, attr, values)
+ object_type = object_id_type.get(object_id)
+ if object_id not in object_records_by_id:
+ object_records_by_id[object_id] = {
+ object_id_column: object_id,
+ object_type_column: object_type,
+ }
+
+ for _, timestamp, value in values:
+ if timestamp == _EPOCH:
+ object_records_by_id[object_id][attr] = value
+ else:
+ change = {
+ object_id_column: object_id,
+ object_type_column: object_type,
+ event_timestamp_column: timestamp,
+ changed_field_column: attr,
+ attr: value,
+ }
+ object_changes.append(change)
+
+ objects_df = _instantiate_dataframe(
+ list(object_records_by_id.values()), [object_id_column, object_type_column]
+ )
+ object_changes_df = _instantiate_dataframe(
+ object_changes,
+ [object_id_column, object_type_column, event_timestamp_column, changed_field_column],
+ )
+ objects_df, object_changes_df = _infer_object_attribute_types(
+ objects_df,
+ object_changes_df,
+ object_type_column,
+ {
+ object_id_column,
+ object_type_column,
+ event_timestamp_column,
+ changed_field_column,
+ },
+ )
+
+ if len(events_df) > 0:
+ events_df[internal_index_column] = events_df.index
+ events_df = events_df.sort_values([event_timestamp_column, internal_index_column])
+ del events_df[internal_index_column]
+
+ if len(relations_df) > 0:
+ relations_df[internal_index_column] = relations_df.index
+ relations_df = relations_df.sort_values([event_timestamp_column, internal_index_column])
+ del relations_df[internal_index_column]
+
+ if len(object_changes_df) > 0:
+ object_changes_df[internal_index_column] = object_changes_df.index
+ object_changes_df = object_changes_df.sort_values(
+ [event_timestamp_column, internal_index_column]
+ )
+ del object_changes_df[internal_index_column]
+
+ ocel = OCEL(
+ events=events_df,
+ objects=objects_df,
+ relations=relations_df,
+ o2o=o2o_df,
+ object_changes=object_changes_df,
+ parameters=parameters,
+ )
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/pandas.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/pandas.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecae144d60ade0974aa5b3a78f5e9f7acae50eb5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/csv/variants/pandas.py
@@ -0,0 +1,72 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import extended_table
+from pm4py.objects.ocel.util import ocel_consistency
+from enum import Enum
+from pm4py.util import exec_utils, constants as pm4_constants, pandas_utils
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def apply(
+ file_path: str,
+ objects_path: str = None,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Imports an object-centric event log from a CSV file, using Pandas as backend
+
+ Parameters
+ -----------------
+ file_path
+ Path to the object-centric event log
+ objects_path
+ Optional path to a CSV file containing the objects dataframe
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ------------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING)
+ table = pandas_utils.read_csv(file_path, index_col=False, encoding=encoding, dtype=str)
+
+ objects = None
+ if objects_path is not None:
+ objects = pandas_utils.read_csv(objects_path, index_col=False, encoding=encoding, dtype=str)
+
+ ocel = extended_table.get_ocel_from_extended_table(
+ table, objects, parameters=parameters
+ )
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8d74b205c1176e2b09b4132f23ae5311c8f8ed7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.jsonocel import importer, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..24830e645388ad798efea96b59666e746bd9245e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/importer.py
@@ -0,0 +1,63 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.importer.jsonocel.variants import (
+ classic,
+ ocel20_standard,
+ ocel20_rustxes,
+)
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ CLASSIC = classic
+ OCEL20_STANDARD = ocel20_standard
+ OCEL20_RUSTXES = ocel20_rustxes
+
+
+def apply(
+ file_path: str,
+ variant=Variants.CLASSIC,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Imports an object-centric event log from a JSON-OCEL file
+
+ Parameters
+ -----------------
+ file_path
+ Path to the JSON-OCEL file
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.CLASSIC
+ parameters
+ Variant-specific parameters
+
+ Returns
+ ------------------
+ ocel
+ Object-centric event log
+ """
+ return exec_utils.get_variant(variant).apply(file_path, parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0667d2304a87d200e7cc8760686f33b742389d86
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/__init__.py
@@ -0,0 +1,26 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.jsonocel.variants import (
+ classic,
+ ocel20_standard,
+ ocel20_rustxes
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed1e6a5299b950b3f4eec7c49a30fbd3d9798170
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/classic.py
@@ -0,0 +1,248 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import json
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import compression
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.util import (
+ exec_utils,
+ dt_parsing,
+ constants as pm4_constants,
+ pandas_utils,
+)
+from pm4py.objects.log.util import dataframe_utils
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+ ENCODING = "encoding"
+
+
+def get_base_ocel(json_obj: Any, parameters: Optional[Dict[Any, Any]] = None):
+ events = []
+ relations = []
+ objects = []
+ o2o = []
+ object_changes = []
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, constants.DEFAULT_EVENT_ACTIVITY
+ )
+ event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP,
+ parameters,
+ constants.DEFAULT_EVENT_TIMESTAMP,
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE
+ )
+ internal_index = exec_utils.get_param_value(
+ Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX
+ )
+
+ parser = dt_parsing.parser.get()
+
+ types_dict = {}
+ for obj_id in json_obj[constants.OCEL_OBJECTS_KEY]:
+ obj = json_obj[constants.OCEL_OBJECTS_KEY][obj_id]
+ obj_type = obj[object_type]
+ types_dict[obj_id] = obj_type
+ dct = {object_id: obj_id, object_type: obj_type}
+ for k, v in obj[constants.OCEL_OVMAP_KEY].items():
+ dct[k] = v
+ if constants.OCEL_O2O_KEY in obj:
+ this_rel_objs = obj[constants.OCEL_O2O_KEY]
+ for newel in this_rel_objs:
+ target_id = newel[object_id]
+ qualifier = newel[constants.DEFAULT_QUALIFIER]
+ o2o.append(
+ {
+ object_id: obj_id,
+ object_id + "_2": target_id,
+ constants.DEFAULT_QUALIFIER: qualifier,
+ }
+ )
+ objects.append(dct)
+
+ for ev_id in json_obj[constants.OCEL_EVENTS_KEY]:
+ ev = json_obj[constants.OCEL_EVENTS_KEY][ev_id]
+ dct = {
+ event_id: ev_id,
+ event_timestamp: parser.apply(ev[event_timestamp]),
+ event_activity: ev[event_activity],
+ }
+ for k, v in ev[constants.OCEL_VMAP_KEY].items():
+ dct[k] = v
+ this_rel = {}
+ for obj in ev[constants.OCEL_OMAP_KEY]:
+ if obj in types_dict:
+ this_rel[obj] = {
+ event_id: ev_id,
+ event_activity: ev[event_activity],
+ event_timestamp: parser.apply(ev[event_timestamp]),
+ object_id: obj,
+ object_type: types_dict[obj],
+ }
+ if constants.OCEL_TYPED_OMAP_KEY in ev:
+ for element in ev[constants.OCEL_TYPED_OMAP_KEY]:
+ if object_id in element:
+ key1 = element[object_id]
+ if key1 in this_rel:
+ this_rel[key1][constants.DEFAULT_QUALIFIER] = element[
+ constants.DEFAULT_QUALIFIER
+ ]
+ for obj in this_rel:
+ relations.append(this_rel[obj])
+ events.append(dct)
+
+ if constants.OCEL_OBJCHANGES_KEY in json_obj:
+ object_changes = json_obj[constants.OCEL_OBJCHANGES_KEY]
+
+ events = pandas_utils.instantiate_dataframe(events)
+ objects = pandas_utils.instantiate_dataframe(objects)
+ relations = pandas_utils.instantiate_dataframe(relations)
+ # If there are no relations, ensure the dataframe has the expected schema
+ # to avoid downstream crashes when accessing required columns.
+ if len(relations) == 0:
+ relations = pandas_utils.instantiate_dataframe(
+ {
+ event_id: [],
+ event_activity: [],
+ event_timestamp: [],
+ object_id: [],
+ object_type: [],
+ }
+ )
+
+ events = pandas_utils.insert_index(
+ events, internal_index, reset_index=False, copy_dataframe=False
+ )
+ # Only add temporary index and sort if there are relations rows
+ if len(relations) > 0:
+ relations = pandas_utils.insert_index(
+ relations, internal_index, reset_index=False, copy_dataframe=False
+ )
+
+ events = events.sort_values([event_timestamp, internal_index])
+ if len(relations) > 0:
+ relations = relations.sort_values([event_timestamp, internal_index])
+
+ del events[internal_index]
+ if internal_index in relations.columns:
+ del relations[internal_index]
+
+ globals = {}
+ globals[constants.OCEL_GLOBAL_LOG] = json_obj[constants.OCEL_GLOBAL_LOG]
+ globals[constants.OCEL_GLOBAL_EVENT] = json_obj[
+ constants.OCEL_GLOBAL_EVENT
+ ]
+ globals[constants.OCEL_GLOBAL_OBJECT] = json_obj[
+ constants.OCEL_GLOBAL_OBJECT
+ ]
+
+ o2o = pandas_utils.instantiate_dataframe(o2o) if o2o else None
+ object_changes = (
+ pandas_utils.instantiate_dataframe(object_changes)
+ if object_changes
+ else None
+ )
+ if object_changes is not None and len(object_changes) > 0:
+ object_changes = dataframe_utils.convert_timestamp_columns_in_df(
+ object_changes,
+ timest_format=pm4_constants.DEFAULT_XES_TIMESTAMP_PARSE_FORMAT,
+ timest_columns=[event_timestamp],
+ )
+ obj_id_map = objects[[object_id, object_type]].to_dict(orient="records")
+ obj_id_map = {x[object_id]: x[object_type] for x in obj_id_map}
+ object_changes[object_type] = object_changes[object_id].map(obj_id_map)
+
+ log = OCEL(
+ events=events,
+ objects=objects,
+ relations=relations,
+ o2o=o2o,
+ object_changes=object_changes,
+ globals=globals,
+ parameters=parameters,
+ )
+
+ return log
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Imports an object-centric event log from a JSON-OCEL file, using the default JSON backend of Python
+
+ Parameters
+ -----------------
+ file_path
+ Path to the JSON-OCEL file
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID
+ - Parameters.EVENT_ACTIVITY
+ - Parameters.EVENT_TIMESTAMP
+ - Parameters.OBJECT_ID
+ - Parameters.OBJECT_TYPE
+ - Parameters.INTERNAL_INDEX
+
+ Returns
+ ------------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+
+ with compression.open_text(file_path, "rt", encoding=encoding) as F:
+ json_obj = json.load(F)
+
+ log = get_base_ocel(json_obj, parameters=parameters)
+
+ log = ocel_consistency.apply(log, parameters=parameters)
+ log = filtering_utils.propagate_relations_filtering(
+ log, parameters=parameters
+ )
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/ocel20_rustxes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/ocel20_rustxes.py
new file mode 100644
index 0000000000000000000000000000000000000000..f40f4c287ea293fa5f3c9c2d09abdaf5ee99c28e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/ocel20_rustxes.py
@@ -0,0 +1,50 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import compression
+from pm4py.util.rustxes_utils import import_rustxes_backend
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Imports an OCEL 2.0 JSON using the r4pm/rustxes parser.
+
+ Parameters
+ ---------------
+ file_path
+ Path to the OCEL 2.0 JSON
+ parameters
+ Optional parameters.
+
+ Returns
+ ---------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ rustxes_backend, _ = import_rustxes_backend()
+
+ with compression.decompressed_path(file_path) as path:
+ return rustxes_backend.import_ocel_json_pm4py(path)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/ocel20_standard.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/ocel20_standard.py
new file mode 100644
index 0000000000000000000000000000000000000000..666acf540f61c90c5d783d8764ac6ada2a589b77
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/jsonocel/variants/ocel20_standard.py
@@ -0,0 +1,207 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import exec_utils, dt_parsing
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.importer.jsonocel.variants import classic
+from pm4py.objects.ocel.util import compression
+from pm4py.util import constants as pm4_constants
+from enum import Enum
+import json
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def _parse_attr_value(value, attr_type, parser):
+ if value is None:
+ return None
+ if isinstance(value, str) and value.strip().lower() == "null":
+ return None
+
+ attr_type = "" if attr_type is None else str(attr_type).lower()
+ if "date" in attr_type or "time" in attr_type:
+ try:
+ return parser.apply(value)
+ except BaseException:
+ from dateutil.parser import parse
+
+ try:
+ return parse(value)
+ except BaseException:
+ return value
+ if "float" in attr_type or "double" in attr_type:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return value
+ if "int" in attr_type:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return value
+ if "bool" in attr_type:
+ if isinstance(value, str):
+ lowered = value.strip().lower()
+ if lowered in ("true", "false"):
+ return lowered == "true"
+ return bool(value)
+ return value
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Imports an OCEL from a JSON-OCEL 2 standard file
+
+ Parameters
+ --------------
+ file_path
+ Path to the object-centric event log
+ parameters
+ Possible parameters of the method, including:
+ - Parameters.ENCODING
+
+ Returns
+ -------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, pm4_constants.DEFAULT_ENCODING
+ )
+
+ with compression.open_text(file_path, "rt", encoding=encoding) as F:
+ json_obj = json.load(F)
+
+ event_attr_types = {}
+ for et in json_obj.get("eventTypes", []):
+ event_attr_types[et["name"]] = {
+ x["name"]: x["type"] for x in et.get("attributes", [])
+ }
+
+ object_attr_types = {}
+ for ot in json_obj.get("objectTypes", []):
+ object_attr_types[ot["name"]] = {
+ x["name"]: x["type"] for x in ot.get("attributes", [])
+ }
+
+ parser = dt_parsing.parser.get()
+
+ legacy_obj = {}
+ legacy_obj["ocel:events"] = {}
+ legacy_obj["ocel:objects"] = {}
+ legacy_obj["ocel:objectChanges"] = []
+
+ for eve in json_obj["events"]:
+ dct = {}
+ dct["ocel:activity"] = eve["type"]
+ dct["ocel:timestamp"] = eve["time"]
+ dct["ocel:vmap"] = {}
+ if "attributes" in eve and eve["attributes"]:
+ type_map = event_attr_types.get(eve["type"], {})
+ dct["ocel:vmap"] = {
+ x["name"]: _parse_attr_value(
+ x["value"], type_map.get(x["name"]), parser
+ )
+ for x in eve["attributes"]
+ }
+ dct["ocel:typedOmap"] = []
+ if "relationships" in eve and eve["relationships"]:
+ dct["ocel:typedOmap"] = [
+ {"ocel:oid": x["objectId"], "ocel:qualifier": x["qualifier"]}
+ for x in eve["relationships"]
+ ]
+ dct["ocel:omap"] = list(
+ set(x["ocel:oid"] for x in dct["ocel:typedOmap"])
+ )
+ legacy_obj["ocel:events"][eve["id"]] = dct
+
+ for obj in json_obj["objects"]:
+ dct = {}
+ dct["ocel:type"] = obj["type"]
+ dct["ocel:ovmap"] = {}
+ if "attributes" in obj and obj["attributes"]:
+ type_map = object_attr_types.get(obj["type"], {})
+ attrs_by_name = {}
+ for x in obj["attributes"]:
+ value = _parse_attr_value(
+ x["value"], type_map.get(x["name"]), parser
+ )
+ time_raw = x.get("time")
+ if time_raw is None:
+ time_key = None
+ time_val = None
+ elif str(time_raw).startswith("1970-01-01T00:00:00") or str(
+ time_raw
+ ) == "0":
+ time_key = None
+ time_val = time_raw
+ else:
+ try:
+ time_val = parser.apply(time_raw)
+ time_key = time_val
+ except BaseException:
+ time_val = time_raw
+ time_key = time_raw
+ attrs_by_name.setdefault(x["name"], []).append(
+ (time_key, time_val, value)
+ )
+
+ for name, entries in attrs_by_name.items():
+ base_time_key, base_time_val, base_value = entries[0]
+ dct["ocel:ovmap"][name] = base_value
+ for time_key, time_val, value in entries[1:]:
+ legacy_obj["ocel:objectChanges"].append(
+ {
+ "ocel:oid": obj["id"],
+ "ocel:type": obj["type"],
+ "ocel:field": name,
+ name: value,
+ "ocel:timestamp": time_val,
+ }
+ )
+ dct["ocel:o2o"] = []
+ if "relationships" in obj and obj["relationships"]:
+ dct["ocel:o2o"] = [
+ {"ocel:oid": x["objectId"], "ocel:qualifier": x["qualifier"]}
+ for x in obj["relationships"]
+ ]
+ legacy_obj["ocel:objects"][obj["id"]] = dct
+
+ legacy_obj["ocel:global-log"] = {}
+ legacy_obj["ocel:global-event"] = {}
+ legacy_obj["ocel:global-object"] = {}
+
+ log = classic.get_base_ocel(legacy_obj, parameters=parameters)
+
+ log = ocel_consistency.apply(log, parameters=parameters)
+ log = filtering_utils.propagate_relations_filtering(
+ log, parameters=parameters
+ )
+
+ return log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b67d7f7bc933098d24c6d9268892b1987c191de
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/__init__.py
@@ -0,0 +1,23 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.importer.sqlite import variants, importer
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..58bac324fae84e507bf6391d5d020fcd968815e6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/importer.py
@@ -0,0 +1,64 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Dict, Any
+from enum import Enum
+from typing import Optional
+from pm4py.objects.ocel.importer.sqlite.variants import pandas_importer, ocel20
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ PANDAS_IMPORTER = pandas_importer
+ OCEL20 = ocel20
+
+
+def apply(
+ file_path: str,
+ variant=Variants.PANDAS_IMPORTER,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Imports an OCEL from a SQLite database
+
+ Parameters
+ --------------
+ file_path
+ Path to the SQLite database
+ variant
+ Variant of the importer to use:
+ - Variants.PANDAS_IMPORTER => Pandas
+ parameters
+ Variant-specific parameters
+
+ Returns
+ --------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ return exec_utils.get_variant(variant).apply(
+ file_path, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..92c7b106080e019b493f6986ea33c5cc33524d3d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.sqlite.variants import pandas_importer, ocel20
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..01e0d0932d73c55e330be2b685758a1011308b23
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/ocel20.py
@@ -0,0 +1,287 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils, pandas_utils
+import pandas as pd
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.objects.ocel.validation import ocel20_rel_validation
+from pm4py.util import constants as pm4_constants
+from pm4py.objects.log.util import dataframe_utils
+import warnings
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ CUMCOUNT = "cumcount"
+ VALIDATION = "validation"
+ EXCEPT_IF_INVALID = "except_if_invalid"
+
+
+def _normalize_id_series(series: pd.Series) -> pd.Series:
+ if series is None:
+ return series
+ if pd.api.types.is_float_dtype(series):
+ non_null = series.dropna()
+ if len(non_null) > 0 and ((non_null % 1) == 0).all():
+ series = series.astype("Int64")
+ return series.astype("string")
+ if pd.api.types.is_numeric_dtype(series):
+ return series.astype("string")
+ series = series.astype("string")
+ return series.str.replace(r"\\.0$", "", regex=True)
+
+
+def _quote_identifier(identifier: str) -> str:
+ if identifier is None:
+ return identifier
+ return '"' + identifier.replace('"', '""') + '"'
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None):
+ if parameters is None:
+ parameters = {}
+
+ import sqlite3
+
+ validation = exec_utils.get_param_value(
+ Parameters.VALIDATION, parameters, False
+ )
+ except_if_invalid = exec_utils.get_param_value(
+ Parameters.EXCEPT_IF_INVALID, parameters, False
+ )
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, constants.DEFAULT_EVENT_ACTIVITY
+ )
+ event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP,
+ parameters,
+ constants.DEFAULT_EVENT_TIMESTAMP,
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE
+ )
+ internal_index = exec_utils.get_param_value(
+ Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX
+ )
+ qualifier_field = exec_utils.get_param_value(
+ Parameters.QUALIFIER, parameters, constants.DEFAULT_QUALIFIER
+ )
+ changed_field = exec_utils.get_param_value(
+ Parameters.CHANGED_FIELD, parameters, constants.DEFAULT_CHNGD_FIELD
+ )
+ cumcount_field = exec_utils.get_param_value(
+ Parameters.CUMCOUNT, parameters, "@@cumcount"
+ )
+
+ if validation:
+ satisfied, unsatisfied = ocel20_rel_validation.apply(file_path)
+ if unsatisfied and except_if_invalid:
+ raise Exception("OCEL 2.0 validation failed.")
+
+ conn = sqlite3.connect(file_path)
+
+ EVENTS = pd.read_sql("SELECT * FROM event", conn)
+ OBJECTS = pd.read_sql("SELECT * FROM object", conn)
+ EVENTS["ocel_id"] = _normalize_id_series(EVENTS["ocel_id"])
+ OBJECTS["ocel_id"] = _normalize_id_series(OBJECTS["ocel_id"])
+
+ etypes = sorted(pandas_utils.format_unique(EVENTS["ocel_type"].unique()))
+ otypes = sorted(pandas_utils.format_unique(OBJECTS["ocel_type"].unique()))
+
+ EVENTS = EVENTS.to_dict(orient="records")
+ OBJECTS = OBJECTS.to_dict(orient="records")
+ events_id_type = {x["ocel_id"]: x["ocel_type"] for x in EVENTS}
+ objects_id_type = {x["ocel_id"]: x["ocel_type"] for x in OBJECTS}
+
+ EVENT_CORR_TYPE = pd.read_sql("SELECT * FROM event_map_type", conn)
+ OBJECT_CORR_TYPE = pd.read_sql("SELECT * FROM object_map_type", conn)
+ EVENT_CORR_TYPE = EVENT_CORR_TYPE.to_dict(orient="records")
+ OBJECT_CORR_TYPE = OBJECT_CORR_TYPE.to_dict(orient="records")
+
+ events_type_map = {
+ x["ocel_type"]: x["ocel_type_map"] for x in EVENT_CORR_TYPE
+ }
+ objects_type_map = {
+ x["ocel_type"]: x["ocel_type_map"] for x in OBJECT_CORR_TYPE
+ }
+
+ event_types_coll = []
+ object_types_coll = []
+
+ for act in etypes:
+ act_red = events_type_map[act]
+ table_name = _quote_identifier("event_" + act_red)
+ df = pd.read_sql(f"SELECT * FROM {table_name}", conn)
+ df = df.rename(
+ columns={"ocel_id": event_id, "ocel_time": event_timestamp}
+ )
+ df[event_id] = _normalize_id_series(df[event_id])
+ event_types_coll.append(df)
+
+ for ot in otypes:
+ ot_red = objects_type_map[ot]
+ table_name = _quote_identifier("object_" + ot_red)
+ df = pd.read_sql(f"SELECT * FROM {table_name}", conn)
+ df = df.rename(
+ columns={"ocel_id": object_id, "ocel_time": event_timestamp}
+ )
+ df[object_id] = _normalize_id_series(df[object_id])
+ object_types_coll.append(df)
+
+ event_types_coll = pandas_utils.concat(event_types_coll)
+ event_types_coll[event_activity] = event_types_coll[event_id].map(
+ events_id_type
+ )
+ event_types_coll = dataframe_utils.convert_timestamp_columns_in_df(
+ event_types_coll,
+ timest_format=pm4_constants.DEFAULT_TIMESTAMP_PARSE_FORMAT,
+ timest_columns=[event_timestamp],
+ )
+ object_types_coll = pandas_utils.concat(object_types_coll)
+ object_types_coll[object_type] = object_types_coll[object_id].map(
+ objects_id_type
+ )
+ object_types_coll = object_types_coll.rename(
+ columns={"ocel_changed_field": changed_field}
+ )
+
+ events_timestamp = event_types_coll[[event_id, event_timestamp]].to_dict(
+ orient="records"
+ )
+ events_timestamp = {
+ x[event_id]: x[event_timestamp] for x in events_timestamp
+ }
+ object_types_coll[cumcount_field] = object_types_coll.groupby(
+ object_id
+ ).cumcount()
+
+ if changed_field in object_types_coll:
+ objects = object_types_coll[object_types_coll[changed_field].isna()]
+ object_changes = object_types_coll[
+ ~object_types_coll[changed_field].isna()
+ ]
+ if len(objects) == 0:
+ objects = object_types_coll[object_types_coll[cumcount_field] == 0]
+ object_changes = object_types_coll[
+ object_types_coll[cumcount_field] > 0
+ ]
+ if len(object_changes) == 0:
+ object_changes = None
+ else:
+ object_changes = object_changes.copy()
+ objects = objects.copy()
+ del objects[changed_field]
+ else:
+ objects = object_types_coll.copy()
+ object_changes = None
+
+ if event_timestamp in objects:
+ del objects[event_timestamp]
+ del objects[cumcount_field]
+
+ E2O = pd.read_sql("SELECT * FROM event_object", conn)
+ E2O = E2O.rename(
+ columns={
+ "ocel_event_id": event_id,
+ "ocel_object_id": object_id,
+ "ocel_qualifier": qualifier_field,
+ }
+ )
+ E2O[event_id] = _normalize_id_series(E2O[event_id])
+ E2O[object_id] = _normalize_id_series(E2O[object_id])
+ E2O[event_activity] = E2O[event_id].map(events_id_type)
+ E2O[event_timestamp] = E2O[event_id].map(events_timestamp)
+ E2O[object_type] = E2O[object_id].map(objects_id_type)
+
+ O2O = pd.read_sql("SELECT * FROM object_object", conn)
+ O2O = O2O.rename(
+ columns={
+ "ocel_source_id": object_id,
+ "ocel_target_id": object_id + "_2",
+ "ocel_qualifier": qualifier_field,
+ }
+ )
+ if len(O2O) > 0:
+ O2O[object_id] = _normalize_id_series(O2O[object_id])
+ O2O[object_id + "_2"] = _normalize_id_series(
+ O2O[object_id + "_2"]
+ )
+ if len(O2O) == 0:
+ O2O = None
+
+ conn.close()
+
+ event_types_coll[internal_index] = event_types_coll.index
+ E2O[internal_index] = E2O.index
+
+ event_types_coll = event_types_coll.sort_values(
+ [event_timestamp, internal_index]
+ )
+ E2O = E2O.sort_values([event_timestamp, internal_index])
+
+ del event_types_coll[internal_index]
+ del E2O[internal_index]
+
+ if object_changes is not None:
+ object_changes = dataframe_utils.convert_timestamp_columns_in_df(
+ object_changes,
+ timest_format=pm4_constants.DEFAULT_TIMESTAMP_PARSE_FORMAT,
+ timest_columns=[event_timestamp],
+ )
+ object_changes[internal_index] = object_changes.index
+ object_changes = object_changes.sort_values(
+ [event_timestamp, internal_index]
+ )
+ del object_changes[internal_index]
+
+ ocel = OCEL(
+ events=event_types_coll,
+ objects=objects,
+ relations=E2O,
+ object_changes=object_changes,
+ o2o=O2O,
+ parameters=parameters,
+ )
+
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(ocel, parameters=parameters)
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/pandas_importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/pandas_importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2a35608758ad2495b7a795a78e0f4bf68094140
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/sqlite/variants/pandas_importer.py
@@ -0,0 +1,82 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Dict, Any, Optional
+import pandas as pd
+from pm4py.objects.ocel.util import ocel_consistency
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.objects.log.util import dataframe_utils
+from pm4py.util import pandas_utils, constants as pm4_constants
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Imports an OCEL from a SQLite database using Pandas
+
+ Parameters
+ --------------
+ file_path
+ Path to the SQLite database
+ parameters
+ Parameters of the import
+
+ Returns
+ --------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ import sqlite3
+
+ conn = sqlite3.connect(file_path)
+
+ events = pd.read_sql("SELECT * FROM EVENTS", conn)
+ objects = pd.read_sql("SELECT * FROM OBJECTS", conn)
+ relations = pd.read_sql("SELECT * FROM RELATIONS", conn)
+
+ events = dataframe_utils.convert_timestamp_columns_in_df(
+ events,
+ timest_format=pm4_constants.DEFAULT_TIMESTAMP_PARSE_FORMAT,
+ timest_columns=["ocel:timestamp"],
+ )
+
+ relations = dataframe_utils.convert_timestamp_columns_in_df(
+ relations,
+ timest_format=pm4_constants.DEFAULT_TIMESTAMP_PARSE_FORMAT,
+ timest_columns=["ocel:timestamp"],
+ )
+
+ ocel = OCEL(
+ events=events,
+ objects=objects,
+ relations=relations,
+ parameters=parameters,
+ )
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(
+ ocel, parameters=parameters
+ )
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ade95438ab4ae8a49141dd2b3972d22bc6fa1068
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.xmlocel import importer, variants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fcdd8152a93beeda695cef29c5e9ece1d84c32a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/importer.py
@@ -0,0 +1,63 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from pm4py.objects.ocel.importer.xmlocel.variants import (
+ classic,
+ ocel20,
+ ocel20_rustxes,
+)
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ CLASSIC = classic
+ OCEL20 = ocel20
+ OCEL20_RUSTXES = ocel20_rustxes
+
+
+def apply(
+ file_path: str,
+ variant=Variants.CLASSIC,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Imports an object-centric event log from a XML-OCEL file
+
+ Parameters
+ -----------------
+ file_path
+ Path to the XML-OCEL file
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.CLASSIC
+ parameters
+ Variant-specific parameters
+
+ Returns
+ ------------------
+ ocel
+ Object-centric event log
+ """
+ return exec_utils.get_variant(variant).apply(file_path, parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8739773410b264b1225a8f02c587043cfd43d9c2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.importer.xmlocel.variants import classic, ocel20, ocel20_rustxes
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..35a0234250e7bb18081a7e99ea43132828433db1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/classic.py
@@ -0,0 +1,275 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+from lxml import etree, objectify
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import compression
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.util import exec_utils, dt_parsing, pandas_utils
+from pm4py.objects.ocel.util import ocel_consistency
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ ENCODING = "encoding"
+
+
+def parse_xml(value, tag_str_lower, parser):
+ if "float" in tag_str_lower:
+ return float(value)
+ elif "date" in tag_str_lower:
+ return parser.apply(value)
+ return str(value)
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Imports an object-centric event log from a XNK-OCEL file, using LXML
+
+ Parameters
+ -----------------
+ file_path
+ Path to the XML-OCEL file
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID
+ - Parameters.EVENT_ACTIVITY
+ - Parameters.EVENT_TIMESTAMP
+ - Parameters.OBJECT_ID
+ - Parameters.OBJECT_TYPE
+ - Parameters.INTERNAL_INDEX
+
+ Returns
+ ------------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ events = []
+ relations = []
+ objects = []
+ object_changes = []
+ o2o = []
+ obj_type_dict = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, None
+ )
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, constants.DEFAULT_EVENT_ACTIVITY
+ )
+ event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP,
+ parameters,
+ constants.DEFAULT_EVENT_TIMESTAMP,
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE
+ )
+ internal_index = exec_utils.get_param_value(
+ Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX
+ )
+ qualifier_field = exec_utils.get_param_value(
+ Parameters.QUALIFIER, parameters, constants.DEFAULT_QUALIFIER
+ )
+ changed_field = exec_utils.get_param_value(
+ Parameters.CHANGED_FIELD, parameters, constants.DEFAULT_CHNGD_FIELD
+ )
+
+ date_parser = dt_parsing.parser.get()
+
+ parser = etree.XMLParser(remove_comments=True, encoding=encoding)
+
+ with compression.open_binary(file_path, "rb") as F:
+ tree = objectify.parse(F, parser=parser)
+
+ root = tree.getroot()
+
+ for child in root:
+ if child.tag.lower().endswith("events"):
+ for event in child:
+ eve_id = None
+ eve_activity = None
+ eve_timestamp = None
+ eve_omap = {}
+ eve_vmap = {}
+ for child2 in event:
+ if child2.get("key") == "id":
+ eve_id = child2.get("value")
+ elif child2.get("key") == "timestamp":
+ eve_timestamp = parse_xml(
+ child2.get("value"),
+ child2.tag.lower(),
+ date_parser,
+ )
+ elif child2.get("key") == "activity":
+ eve_activity = child2.get("value")
+ elif child2.get("key") == "omap":
+ for child3 in child2:
+ objref = child3.get("value")
+ qualifier = (
+ child3.get("qualifier")
+ if "qualifier" in child3.keys()
+ else None
+ )
+ eve_omap[objref] = qualifier
+ elif child2.get("key") == "vmap":
+ for child3 in child2:
+ key = child3.get("key")
+ value = parse_xml(
+ child3.get("value"),
+ child3.tag.lower(),
+ date_parser,
+ )
+ eve_vmap[key] = value
+
+ event_dict = {
+ event_id: eve_id,
+ event_activity: eve_activity,
+ event_timestamp: eve_timestamp,
+ }
+ for k, v in eve_vmap.items():
+ event_dict[k] = v
+ events.append(event_dict)
+
+ for obj in eve_omap:
+ rel_dict = {
+ event_id: eve_id,
+ event_activity: eve_activity,
+ event_timestamp: eve_timestamp,
+ object_id: obj,
+ qualifier_field: eve_omap[obj],
+ }
+ relations.append(rel_dict)
+ elif child.tag.lower().endswith("objects"):
+ for object in child:
+ obj_id = None
+ obj_type = None
+ obj_ovmap = []
+ for child2 in object:
+ if child2.get("key") == "id":
+ obj_id = child2.get("value")
+ elif child2.get("key") == "type":
+ obj_type = child2.get("value")
+ elif child2.get("key") == "ovmap":
+ for child3 in child2:
+ key = child3.get("key")
+ value = parse_xml(
+ child3.get("value"),
+ child3.tag.lower(),
+ date_parser,
+ )
+ timestamp = (
+ child3.get("timestamp")
+ if "timestamp" in child3.keys()
+ else None
+ )
+ obj_ovmap.append((key, value, timestamp))
+ dct = {object_id: obj_id, object_type: obj_type}
+ for el in obj_ovmap:
+ if el[0] not in dct:
+ dct[el[0]] = el[1]
+ else:
+ this_dct = {object_id: obj_id, object_type: obj_type}
+ this_dct[el[0]] = el[1]
+ this_dct[event_timestamp] = date_parser.apply(el[2])
+ this_dct[changed_field] = el[0]
+ object_changes.append(this_dct)
+ objects.append(dct)
+ obj_type_dict[obj_id] = obj_type
+ elif child.tag.lower().endswith("o2o"):
+ for rel in child:
+ source = rel.get("source")
+ target = rel.get("target")
+ qualifier = rel.get("qualifier")
+ o2o.append(
+ {
+ object_id: source,
+ object_id + "_2": target,
+ qualifier_field: qualifier,
+ }
+ )
+
+ for rel in relations:
+ rel[object_type] = obj_type_dict[rel[object_id]]
+
+ events = pandas_utils.instantiate_dataframe(events) if events else None
+ objects = pandas_utils.instantiate_dataframe(objects) if objects else None
+ relations = (
+ pandas_utils.instantiate_dataframe(relations) if relations else None
+ )
+ o2o = pandas_utils.instantiate_dataframe(o2o) if o2o else None
+ object_changes = (
+ pandas_utils.instantiate_dataframe(object_changes)
+ if object_changes
+ else None
+ )
+
+ events = pandas_utils.insert_index(
+ events, internal_index, reset_index=False, copy_dataframe=False
+ )
+ relations = pandas_utils.insert_index(
+ relations, internal_index, reset_index=False, copy_dataframe=False
+ )
+
+ events = events.sort_values([event_timestamp, internal_index])
+ relations = relations.sort_values([event_timestamp, internal_index])
+
+ del events[internal_index]
+ del relations[internal_index]
+
+ globals = {}
+
+ ocel = OCEL(
+ events=events,
+ objects=objects,
+ relations=relations,
+ globals=globals,
+ o2o=o2o,
+ object_changes=object_changes,
+ parameters=parameters,
+ )
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(ocel)
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/ocel20.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/ocel20.py
new file mode 100644
index 0000000000000000000000000000000000000000..03b084a6b363c90aa3514e496a36c4d9d5a8816d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/ocel20.py
@@ -0,0 +1,323 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+from lxml import etree, objectify
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import compression
+from pm4py.objects.ocel.util import filtering_utils
+from pm4py.util import exec_utils, dt_parsing, pandas_utils
+from pm4py.objects.ocel.util import ocel_consistency
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+ ENCODING = "encoding"
+
+
+def parse_xml(value, tag_str_lower, parser):
+ if "float" in tag_str_lower:
+ if value == "null":
+ return 0
+ return float(value)
+ elif "date" in tag_str_lower:
+ return embed_date_parser(parser.apply, value)
+ return str(value)
+
+
+def embed_date_parser(date_parser, x):
+ try:
+ return date_parser(x)
+ except BaseException:
+ from dateutil.parser import parse
+
+ try:
+ return parse(x)
+ except BaseException:
+ return parse(x, fuzzy=True)
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ if parameters is None:
+ parameters = {}
+
+ events_list = []
+ relations_list = []
+ objects_list = []
+ object_changes_list = []
+ o2o_list = []
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, None
+ )
+
+ event_id_column = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID
+ )
+ event_activity_column = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, constants.DEFAULT_EVENT_ACTIVITY
+ )
+ event_timestamp_column = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP,
+ parameters,
+ constants.DEFAULT_EVENT_TIMESTAMP,
+ )
+ object_id_column = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID
+ )
+ object_type_column = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE
+ )
+ internal_index_column = exec_utils.get_param_value(
+ Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX
+ )
+ qualifier_field = exec_utils.get_param_value(
+ Parameters.QUALIFIER, parameters, constants.DEFAULT_QUALIFIER
+ )
+ changed_field = exec_utils.get_param_value(
+ Parameters.CHANGED_FIELD, parameters, constants.DEFAULT_CHNGD_FIELD
+ )
+ obj_type_dict = {}
+
+ date_parser = dt_parsing.parser.get()
+
+ parser = etree.XMLParser(remove_comments=True, encoding=encoding)
+
+ with compression.open_binary(file_path, "rb") as F:
+ tree = objectify.parse(F, parser=parser)
+
+ root = tree.getroot()
+
+ object_type_attributes = {}
+ event_type_attributes = {}
+
+ for child in root:
+ if child.tag.endswith("object-types"):
+ for object_type in child:
+ object_type_name = object_type.get("name")
+ object_type_attributes[object_type_name] = {}
+ for attributes in object_type:
+ for attribute in attributes:
+ attribute_name = attribute.get("name")
+ attribute_type = attribute.get("type")
+ object_type_attributes[object_type_name][
+ attribute_name
+ ] = attribute_type
+ elif child.tag.endswith("event-types"):
+ for event_type in child:
+ event_type_name = event_type.get("name")
+ event_type_attributes[event_type_name] = {}
+ for attributes in event_type:
+ for attribute in attributes:
+ attribute_name = attribute.get("name")
+ attribute_type = attribute.get("type")
+ event_type_attributes[event_type_name][
+ attribute_name
+ ] = attribute_type
+ elif child.tag.endswith("objects"):
+ object_id = None
+ object_type = None
+
+ for object in child:
+ object_id = object.get("id")
+ object_type = object.get("type")
+
+ obj_dict = {
+ object_id_column: object_id,
+ object_type_column: object_type,
+ }
+ obj_type_dict[object_id] = object_type
+ obj_attrs = {}
+
+ for child2 in object:
+ if child2.tag.endswith("objects"):
+ for target_object in child2:
+ target_object_id = target_object.get("object-id")
+ qualifier = target_object.get("qualifier")
+
+ o2o_dict = {
+ object_id_column: object_id,
+ object_id_column + "_2": target_object_id,
+ qualifier_field: qualifier,
+ }
+ o2o_list.append(o2o_dict)
+
+ elif child2.tag.endswith("attributes"):
+ for attribute in child2:
+ attribute_name = attribute.get("name")
+ attribute_time = attribute.get("time")
+ try:
+ attribute_type = object_type_attributes[
+ object_type
+ ][attribute_name]
+ except BaseException:
+ attribute_type = "string"
+ attribute_text = parse_xml(
+ attribute.text, attribute_type, date_parser
+ )
+ if (
+ attribute_time == "0"
+ or attribute_time.startswith(
+ "1970-01-01T00:00:00"
+ )
+ ):
+ time_key = None
+ time_val = attribute_time
+ else:
+ time_val = embed_date_parser(
+ date_parser.apply, attribute_time
+ )
+ time_key = time_val
+
+ obj_attrs.setdefault(attribute_name, []).append(
+ (time_key, time_val, attribute_text)
+ )
+
+ for attr_name, entries in obj_attrs.items():
+ base_time_key, base_time_val, base_value = entries[0]
+ obj_dict[attr_name] = base_value
+ for time_key, time_val, value in entries[1:]:
+ obj_change_dict = {
+ object_id_column: object_id,
+ object_type_column: object_type,
+ attr_name: value,
+ changed_field: attr_name,
+ event_timestamp_column: time_val,
+ }
+ object_changes_list.append(obj_change_dict)
+
+ objects_list.append(obj_dict)
+
+ elif child.tag.endswith("events"):
+ event_id = None
+ event_type = None
+ event_time = None
+
+ for event in child:
+ event_id = event.get("id")
+ event_type = event.get("type")
+ event_time = embed_date_parser(
+ date_parser.apply, event.get("time")
+ )
+
+ ev_dict = {
+ event_id_column: event_id,
+ event_activity_column: event_type,
+ event_timestamp_column: event_time,
+ }
+
+ for child2 in event:
+ if child2.tag.endswith("objects"):
+ for target_object in child2:
+ target_object_id = target_object.get("object-id")
+ qualifier = target_object.get("qualifier")
+
+ if target_object_id in obj_type_dict:
+ rel_dict = {
+ event_id_column: event_id,
+ event_activity_column: event_type,
+ event_timestamp_column: event_time,
+ object_id_column: target_object_id,
+ object_type_column: obj_type_dict[
+ target_object_id
+ ],
+ qualifier_field: qualifier,
+ }
+ relations_list.append(rel_dict)
+ elif child2.tag.endswith("attributes"):
+ for attribute in child2:
+ attribute_name = attribute.get("name")
+ attribute_text = attribute.text
+ try:
+ attribute_type = event_type_attributes[
+ event_type
+ ][attribute_name]
+ except BaseException:
+ attribute_type = "string"
+ ev_dict[attribute_name] = parse_xml(
+ attribute_text, attribute_type, date_parser
+ )
+
+ events_list.append(ev_dict)
+
+ events_list = (
+ pandas_utils.instantiate_dataframe(events_list)
+ if events_list
+ else None
+ )
+ objects_list = (
+ pandas_utils.instantiate_dataframe(objects_list)
+ if objects_list
+ else None
+ )
+ relations_list = (
+ pandas_utils.instantiate_dataframe(relations_list)
+ if relations_list
+ else None
+ )
+ o2o_list = (
+ pandas_utils.instantiate_dataframe(o2o_list) if o2o_list else None
+ )
+ object_changes_list = (
+ pandas_utils.instantiate_dataframe(object_changes_list)
+ if object_changes_list
+ else None
+ )
+ globals = {}
+
+ events_list[internal_index_column] = events_list.index
+ relations_list[internal_index_column] = relations_list.index
+
+ events_list = events_list.sort_values(
+ [event_timestamp_column, internal_index_column]
+ )
+ relations_list = relations_list.sort_values(
+ [event_timestamp_column, internal_index_column]
+ )
+
+ del events_list[internal_index_column]
+ del relations_list[internal_index_column]
+
+ ocel = OCEL(
+ events=events_list,
+ objects=objects_list,
+ relations=relations_list,
+ globals=globals,
+ o2o=o2o_list,
+ object_changes=object_changes_list,
+ parameters=parameters,
+ )
+ ocel = ocel_consistency.apply(ocel, parameters=parameters)
+ ocel = filtering_utils.propagate_relations_filtering(ocel)
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/ocel20_rustxes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/ocel20_rustxes.py
new file mode 100644
index 0000000000000000000000000000000000000000..692e3a65a629707b5033bf94293ea8ffa89b92a6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/importer/xmlocel/variants/ocel20_rustxes.py
@@ -0,0 +1,50 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import compression
+from pm4py.util.rustxes_utils import import_rustxes_backend
+
+
+def apply(file_path: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Imports an OCEL 2.0 XML using the r4pm/rustxes parser.
+
+ Parameters
+ ---------------
+ file_path
+ Path to the OCEL 2.0 XML
+ parameters
+ Optional parameters.
+
+ Returns
+ ---------------
+ ocel
+ Object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ rustxes_backend, _ = import_rustxes_backend()
+
+ with compression.decompressed_path(file_path) as path:
+ return rustxes_backend.import_ocel_xml_pm4py(path)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..e75daff232a7f4db7d1ffd9364abd99d7649743c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/obj.py
@@ -0,0 +1,319 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.ocel import constants
+from pm4py.util import exec_utils, pandas_utils
+import pandas as pd
+import numpy as np
+from collections import Counter
+from copy import copy, deepcopy
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ QUALIFIER = constants.PARAM_QUALIFIER
+ CHANGED_FIELD = constants.PARAM_CHNGD_FIELD
+
+
+class OCEL(object):
+ def __init__(
+ self,
+ events=None,
+ objects=None,
+ relations=None,
+ globals=None,
+ parameters=None,
+ o2o=None,
+ e2e=None,
+ object_changes=None,
+ ):
+ if parameters is None:
+ parameters = {}
+
+ self.event_id_column = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID
+ )
+ self.object_id_column = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID
+ )
+ self.object_type_column = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE
+ )
+
+ self.event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY,
+ parameters,
+ constants.DEFAULT_EVENT_ACTIVITY,
+ )
+ self.event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP,
+ parameters,
+ constants.DEFAULT_EVENT_TIMESTAMP,
+ )
+ self.qualifier = exec_utils.get_param_value(
+ Parameters.QUALIFIER, parameters, constants.DEFAULT_QUALIFIER
+ )
+ self.changed_field = exec_utils.get_param_value(
+ Parameters.CHANGED_FIELD, parameters, constants.DEFAULT_CHNGD_FIELD
+ )
+
+ if events is None:
+ events = pandas_utils.instantiate_dataframe(
+ {
+ self.event_id_column: [],
+ self.event_activity: [],
+ self.event_timestamp: [],
+ }
+ )
+ if objects is None:
+ objects = pandas_utils.instantiate_dataframe(
+ {self.object_id_column: [], self.object_type_column: []}
+ )
+ if relations is None:
+ relations = pandas_utils.instantiate_dataframe(
+ {
+ self.event_id_column: [],
+ self.event_activity: [],
+ self.event_timestamp: [],
+ self.object_id_column: [],
+ self.object_type_column: [],
+ }
+ )
+ if globals is None:
+ globals = {}
+ if o2o is None:
+ o2o = pandas_utils.instantiate_dataframe(
+ {
+ self.object_id_column: [],
+ self.object_id_column + "_2": [],
+ self.qualifier: [],
+ }
+ )
+ if e2e is None:
+ e2e = pandas_utils.instantiate_dataframe(
+ {
+ self.event_id_column: [],
+ self.event_id_column + "_2": [],
+ self.qualifier: [],
+ }
+ )
+ if object_changes is None:
+ object_changes = pandas_utils.instantiate_dataframe(
+ {
+ self.object_id_column: [],
+ self.object_type_column: [],
+ self.event_timestamp: [],
+ self.changed_field: [],
+ }
+ )
+ if self.qualifier not in relations:
+ relations[self.qualifier] = [None] * len(relations)
+
+ self.events = events
+ self.objects = objects
+ self.relations = relations
+ self.globals = globals
+ self.o2o = o2o
+ self.e2e = e2e
+ self.object_changes = object_changes
+
+ self.parameters = parameters
+
+ def get_extended_table(
+ self, ot_prefix=constants.DEFAULT_OBJECT_TYPE_PREFIX_EXTENDED
+ ) -> pd.DataFrame:
+ """
+ Transforms the current OCEL data structure into a Pandas dataframe containing the events with their
+ attributes and the related objects per object type.
+ """
+ object_types = pandas_utils.format_unique(
+ self.relations[self.object_type_column].unique()
+ )
+ table = self.events.copy().set_index(self.event_id_column)
+ for ot in object_types:
+ table[ot_prefix + ot] = (
+ self.relations[self.relations[self.object_type_column] == ot]
+ .groupby(self.event_id_column)[self.object_id_column]
+ .agg(list)
+ )
+ table = table.reset_index()
+ return table
+
+ def get_summary(self) -> str:
+ """
+ Gets a string summary of the object-centric event log
+ """
+ ret = []
+ ret.append("Object-Centric Event Log (")
+ ret.append("number of events: %d" % (len(self.events)))
+ ret.append(", number of objects: %d" % (len(self.objects)))
+ ret.append(
+ ", number of activities: %d"
+ % (self.events[self.event_activity].nunique())
+ )
+ ret.append(
+ ", number of object types: %d"
+ % (self.objects[self.object_type_column].nunique())
+ )
+ ret.append(
+ ", events-objects relationships: %d)" % (len(self.relations))
+ )
+ ret.append("\n")
+ ret.append(
+ "Activities occurrences: "
+ + str(
+ Counter(
+ self.events[self.event_activity].value_counts().to_dict()
+ )
+ )
+ )
+ ret.append("\n")
+ ret.append(
+ "Object types occurrences (number of objects): "
+ + str(
+ Counter(
+ self.objects[self.object_type_column]
+ .value_counts()
+ .to_dict()
+ )
+ )
+ )
+ ret.append("\n")
+ ret.append(
+ "Unique activities per object type: "
+ + str(
+ Counter(
+ self.relations.groupby(self.object_type_column)[
+ self.event_activity
+ ]
+ .nunique()
+ .to_dict()
+ )
+ )
+ )
+ ret.append("\n")
+ ret.append(
+ "Please use .get_extended_table() to get a dataframe representation of the events related to the objects."
+ )
+ return "".join(ret)
+
+ def is_ocel20(self):
+ unique_qualifiers = []
+ if self.qualifier in self.relations.columns:
+ unique_qualifiers = [
+ x
+ for x in pandas_utils.format_unique(
+ self.relations[self.qualifier].unique()
+ )
+ if not self.__check_is_nan(x)
+ ]
+
+ return (
+ len(self.o2o) > 0
+ or len(self.object_changes) > 0
+ or len(unique_qualifiers) > 0
+ )
+
+ def __check_is_nan(self, x):
+ try:
+ if x is None:
+ return True
+ if np.isnan(x):
+ return True
+ except BaseException:
+ return False
+
+ def __str__(self):
+ return str(self.get_summary())
+
+ def __repr__(self):
+ return str(self.get_summary())
+
+ def __copy__(self):
+ return OCEL(
+ self.events,
+ self.objects,
+ self.relations,
+ copy(self.globals),
+ copy(self.parameters),
+ copy(self.o2o),
+ copy(self.e2e),
+ copy(self.object_changes),
+ )
+
+ def __deepcopy__(self, memo):
+ return OCEL(
+ self.events.copy(),
+ self.objects.copy(),
+ self.relations.copy(),
+ deepcopy(self.globals),
+ deepcopy(self.parameters),
+ deepcopy(self.o2o),
+ deepcopy(self.e2e),
+ deepcopy(self.object_changes),
+ )
+
+ def __eq__(self, other):
+ if not isinstance(other, OCEL):
+ return False
+
+ return (
+ self.event_id_column == other.event_id_column
+ and self.object_id_column == other.object_id_column
+ and self.object_type_column == other.object_type_column
+ and self.event_activity == other.event_activity
+ and self.event_timestamp == other.event_timestamp
+ and self.qualifier == other.qualifier
+ and self.changed_field == other.changed_field
+ and self.events.equals(other.events)
+ and self.objects.equals(other.objects)
+ and self.relations.equals(other.relations)
+ and self.globals == other.globals
+ and self.o2o.equals(other.o2o)
+ and self.e2e.equals(other.e2e)
+ and self.object_changes.equals(other.object_changes)
+ and self.parameters == other.parameters
+ )
+
+ def __hash__(self):
+ return hash(
+ (
+ self.event_id_column,
+ self.object_id_column,
+ self.object_type_column,
+ self.event_activity,
+ self.event_timestamp,
+ self.qualifier,
+ self.changed_field,
+ self.events.to_string(),
+ self.objects.to_string(),
+ self.relations.to_string(),
+ self.o2o.to_string(),
+ self.e2e.to_string(),
+ self.object_changes.to_string(),
+ )
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c10aee68facf106388585f9c8d3dc2e81f58d08
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/__init__.py
@@ -0,0 +1,48 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.util import (
+ attributes_names,
+ attributes_per_type,
+ compression,
+ convergence_divergence_diagnostics,
+ e2o_qualification,
+ ev_att_to_obj_type,
+ event_prefix_suffix_per_obj,
+ events_per_object_type,
+ events_per_type_per_activity,
+ explode,
+ extended_table,
+ filtering_utils,
+ flattening,
+ log_ocel,
+ names_stripping,
+ objects_per_type_per_activity,
+ ocel_consistency,
+ ocel_iterator,
+ ocel_to_dict_types_rel,
+ ocel_type_renaming,
+ parent_children_ref,
+ related_events,
+ related_objects,
+ rename_objs_ot_tim_lex,
+ sampling
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/attributes_names.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/attributes_names.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea6962eb1c8d1fc12d28786adc638e405c2cde3e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/attributes_names.py
@@ -0,0 +1,62 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Optional, Dict, Any, List
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+
+
+def get_attribute_names(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> List[str]:
+ """
+ Gets the list of attributes at the event and the object level of an object-centric event log
+ (e.g. ["cost", "amount", "name"])
+
+ Parameters
+ -------------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------------
+ attributes_list
+ List of attributes at the event and object level (e.g. ["cost", "amount", "name"])
+ """
+ if parameters is None:
+ parameters = {}
+
+ attributes = sorted(
+ set(
+ x
+ for x in ocel.events.columns
+ if not x.startswith(constants.OCEL_PREFIX)
+ ).union(
+ x
+ for x in ocel.objects.columns
+ if not x.startswith(constants.OCEL_PREFIX)
+ )
+ )
+
+ return attributes
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/attributes_per_type.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/attributes_per_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fb7fecce657a2c19aa012a0870b5965657f6d5b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/attributes_per_type.py
@@ -0,0 +1,117 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel import constants
+from enum import Enum
+from pm4py.util import exec_utils
+import datetime as dt
+import numpy as np
+import pandas as pd
+
+
+class Parameters(Enum):
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+
+
+def _infer_type_from_series(series):
+ dtype_str = str(series.dtype)
+ if "date" in dtype_str or "time" in dtype_str:
+ return "date"
+ if "float" in dtype_str or "double" in dtype_str:
+ return "float"
+ if "int" in dtype_str:
+ return "int"
+ if "bool" in dtype_str:
+ return "boolean"
+
+ if dtype_str != "object":
+ return "string"
+
+ values = series.dropna()
+ if values.empty:
+ return "string"
+
+ def _isinstance_all(values_iter, types):
+ return all(isinstance(v, types) for v in values_iter)
+
+ values_list = values.tolist()
+ if _isinstance_all(values_list, (bool,)):
+ return "boolean"
+ if _isinstance_all(values_list, (int,)):
+ return "int"
+ if _isinstance_all(values_list, (float, int)):
+ return "float"
+ if _isinstance_all(values_list, (pd.Timestamp, np.datetime64, dt.datetime, dt.date)):
+ return "date"
+
+ return "string"
+
+
+def get(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None):
+ if parameters is None:
+ parameters = {}
+
+ event_activity_column = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ object_type_column = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+
+ ets = {}
+ for k, v in ocel.events.groupby(event_activity_column):
+ cols = v.dropna(axis="columns", how="all").columns
+ ets[k] = {
+ x: _infer_type_from_series(v[x])
+ for x in cols
+ if not x.startswith("ocel:")
+ }
+
+ ots = {}
+ for k, v in ocel.objects.groupby(object_type_column):
+ cols = v.dropna(axis="columns", how="all").columns
+ ots[k] = {
+ x: _infer_type_from_series(v[x])
+ for x in cols
+ if not x.startswith("ocel:")
+ }
+
+ ots2 = {}
+ for k, v in ocel.object_changes.groupby(object_type_column):
+ cols = v.dropna(axis="columns", how="all").columns
+ ots2[k] = {
+ x: _infer_type_from_series(v[x])
+ for x in cols
+ if not x.startswith("ocel:")
+ }
+
+ for k in ots2:
+ if k not in ots:
+ ots[k] = ots2[k]
+ else:
+ for x in ots2[k]:
+ if x not in ots[k]:
+ ots[k][x] = ots2[k][x]
+
+ return ets, ots
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/compression.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/compression.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc945712a342c93c94e47659afbd13b5a8a857d3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/compression.py
@@ -0,0 +1,70 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import gzip
+import os
+import shutil
+import tempfile
+from contextlib import contextmanager
+
+
+def is_gzip_path(file_path: str) -> bool:
+ return str(file_path).lower().endswith(".gz")
+
+
+def open_text(file_path: str, mode: str, encoding: str):
+ if is_gzip_path(file_path):
+ return gzip.open(file_path, mode=mode, encoding=encoding)
+ return open(file_path, mode=mode, encoding=encoding)
+
+
+def open_binary(file_path: str, mode: str):
+ if is_gzip_path(file_path):
+ return gzip.open(file_path, mode=mode)
+ return open(file_path, mode=mode)
+
+
+def get_uncompressed_suffix(file_path: str) -> str:
+ path = str(file_path)
+ if is_gzip_path(path):
+ path = path[:-3]
+ _, suffix = os.path.splitext(path)
+ return suffix or ".tmp"
+
+
+@contextmanager
+def decompressed_path(file_path: str):
+ if not is_gzip_path(file_path):
+ yield file_path
+ return
+
+ tmp = tempfile.NamedTemporaryFile(
+ delete=False, suffix=get_uncompressed_suffix(file_path)
+ )
+ tmp.close()
+
+ try:
+ with gzip.open(file_path, "rb") as source:
+ with open(tmp.name, "wb") as target:
+ shutil.copyfileobj(source, target)
+ yield tmp.name
+ finally:
+ os.remove(tmp.name)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/convergence_divergence_diagnostics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/convergence_divergence_diagnostics.py
new file mode 100644
index 0000000000000000000000000000000000000000..834df95a6991942cecb4ec3171d60fcc00c5b9ff
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/convergence_divergence_diagnostics.py
@@ -0,0 +1,73 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.util import (
+ events_per_type_per_activity,
+ objects_per_type_per_activity,
+)
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel.obj import OCEL
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Reports the activities and the object types for which the convergence / divergence problems occur.
+
+ Parameters
+ ----------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ----------------
+ ret
+ Dictionary with two keys ("convergence" and "divergence"). Each key is associated to a set
+ of (activity, object_type) for which the specific problem occurs. An activity/object type
+ which does not appear neither in the "convergence" and "divergence" section does not suffer
+ of convergence and divergence problems.
+ """
+ if parameters is None:
+ parameters = {}
+
+ ev_per_type_per_act = events_per_type_per_activity.apply(
+ ocel, parameters=parameters
+ )
+ obj_per_type_per_act = objects_per_type_per_activity.apply(
+ ocel, parameters=parameters
+ )
+
+ ret = {"divergence": set(), "convergence": set()}
+
+ # analyze the divergence problems
+ for act in ev_per_type_per_act:
+ for ot in ev_per_type_per_act[act]:
+ if ev_per_type_per_act[act][ot]["median"] > 1:
+ ret["divergence"].add((act, ot))
+
+ # analyze the convergence problems
+ for act in obj_per_type_per_act:
+ for ot in obj_per_type_per_act[act]:
+ if obj_per_type_per_act[act][ot]["median"] > 1:
+ ret["convergence"].add((act, ot))
+
+ return ret
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/e2o_qualification.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/e2o_qualification.py
new file mode 100644
index 0000000000000000000000000000000000000000..615486c340fab57efadbb8e77a104286e7eedddb
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/e2o_qualification.py
@@ -0,0 +1,90 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from enum import Enum
+from pm4py.util import exec_utils
+from copy import copy
+
+
+class Parameters(Enum):
+ CONCATENER = "concatener"
+ CONCAT_COLUMN = "concat_column"
+
+
+def apply(
+ ocel: OCEL,
+ qualifier_type: str,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ if parameters is None:
+ parameters = {}
+
+ concatener = exec_utils.get_param_value(
+ Parameters.CONCATENER, parameters, "@@"
+ )
+ concat_column = exec_utils.get_param_value(
+ Parameters.CONCAT_COLUMN, parameters, "@@concat"
+ )
+
+ ocel = copy(ocel)
+ ocel.relations[concat_column] = (
+ ocel.relations[ocel.event_id_column]
+ + concatener
+ + ocel.relations[ocel.object_id_column]
+ )
+ relations = ocel.relations.groupby(ocel.object_id_column)[
+ ocel.event_id_column
+ ]
+
+ if qualifier_type == "creation":
+ relations = relations.first().to_dict()
+ relations = {
+ y + concatener + x: qualifier_type for x, y in relations.items()
+ }
+ elif qualifier_type == "termination":
+ relations = relations.last().to_dict()
+ relations = {
+ y + concatener + x: qualifier_type for x, y in relations.items()
+ }
+ elif qualifier_type == "other":
+ relations0 = relations.agg(list).to_dict()
+ relations0 = {x: y[1:-1] for x, y in relations0.items()}
+ relations0 = {x: y for x, y in relations0.items() if y}
+ relations = {}
+ for x, y in relations0.items():
+ for y1 in y:
+ relations[y1 + concatener + x] = qualifier_type
+
+ ocel.relations[ocel.qualifier + "_2"] = ocel.relations[concat_column].map(
+ relations
+ )
+ ocel.relations[ocel.qualifier + "_2"] = ocel.relations[
+ ocel.qualifier + "_2"
+ ].fillna(ocel.relations[ocel.qualifier])
+ ocel.relations[ocel.qualifier] = ocel.relations[ocel.qualifier + "_2"]
+
+ del ocel.relations[ocel.qualifier + "_2"]
+ del ocel.relations[concat_column]
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ev_att_to_obj_type.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ev_att_to_obj_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3f1fcbaa8c1821e2cf7c3ffc1045340eec931ee
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ev_att_to_obj_type.py
@@ -0,0 +1,116 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from enum import Enum
+from pm4py.objects.ocel import constants
+from pm4py.util import exec_utils, pandas_utils
+from copy import deepcopy
+import pandas as pd
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+
+
+def apply(ocel: OCEL, param: str, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Transforms an event attribute to an object type.
+
+ Parameters
+ ---------------
+ ocel
+ Object-centric event log
+ param
+ Event attribute that should be moved at the event level
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the event identifier column
+ - Parameters.EVENT_ACTIVITY => the event activity column
+ - Parameters.EVENT_TIMESTAMP => the event timestamp column
+ - Parameters.OBJECT_ID => the object identifier column
+ - Parameters.OBJECT_TYPE => the object type column
+ - Parameters.INTERNAL_INDEX => the internal index
+
+ Returns
+ --------------
+ new_ocel
+ OCEL in which the attribute has been moved to the object type level.
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP, parameters, ocel.event_timestamp
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+ internal_index = exec_utils.get_param_value(
+ Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX
+ )
+
+ new_ocel = deepcopy(ocel)
+ new_ocel.events[param] = new_ocel.events[param].astype(str)
+ ev_param = new_ocel.events.dropna(subset=[param])[
+ [event_id, event_activity, event_timestamp, param]
+ ]
+ vals = pandas_utils.format_unique(ev_param[param].unique())
+ ev_param = ev_param.rename(columns={param: object_id})
+ ev_param[object_type] = param
+
+ new_objects_df = pandas_utils.instantiate_dataframe(
+ [{object_id: v, object_type: param} for v in vals]
+ )
+
+ new_ocel.objects = pandas_utils.concat([new_ocel.objects, new_objects_df])
+ new_ocel.relations = pandas_utils.concat([new_ocel.relations, ev_param])
+
+ new_ocel.relations = pandas_utils.insert_index(
+ new_ocel.relations,
+ internal_index,
+ reset_index=False,
+ copy_dataframe=False,
+ )
+
+ new_ocel.relations = new_ocel.relations.sort_values(
+ [event_timestamp, internal_index]
+ )
+
+ del new_ocel.events[param]
+
+ return new_ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/event_prefix_suffix_per_obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/event_prefix_suffix_per_obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7b5ff6d50eb751ec480edb16f7cb3a759878499
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/event_prefix_suffix_per_obj.py
@@ -0,0 +1,132 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from enum import Enum
+from pm4py.util import exec_utils, pandas_utils
+
+
+class Parameters(Enum):
+ PREFIX_OR_SUFFIX = "prefix_or_suffix"
+ INDEX_ATTRIBUTE = "index_attribute"
+ LEFT_SUFFIX = "left_suffix"
+ RIGHT_SUFFIX = "right_suffix"
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Gets for each event and each one of the related objects,
+ the prefix or the suffix.
+ E.g. if there is an object "o1" with lifecycle "e1", "e2", "e3",
+ then:
+
+ The prefix of "e1" for "o1" is empty.
+ The prefix of "e2" for "o1" is ["e1"].
+ The prefix of "e3" for "o1" is ["e1", "e2"].
+
+ The suffix of "e1" for "o1" is ["e2", "e3"].
+ The suffix of "e2" for "o1" is ["o3"].
+ The suffix of "e3" for "o1" is empty.
+
+ Parameters
+ --------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.PREFIX_OR_SUFFIX => establishes if the prefix or the suffix of the event per object is
+ needed. Possible values:
+ - "prefix"
+ - "suffix"
+ - Parameters.INDEX_ATTRIBUTE => the index attribute which is artificially inserted in the relations df.
+ - Parameters.LEFT_SUFFIX => the suffix for the left-part of the merge.
+ - Parameters.RIGHT_SUFFIX => the suffix for the right-part of the merge
+
+ Returns
+ --------------
+ ret
+ A dictionary where the first key is the event, the second key is the object, and the value is a list
+ of events which are the object-specific prefix or suffix of the event.
+ """
+ if parameters is None:
+ parameters = {}
+
+ prefix_or_suffix = exec_utils.get_param_value(
+ Parameters.PREFIX_OR_SUFFIX, parameters, "prefix"
+ )
+ index_attribute = exec_utils.get_param_value(
+ Parameters.INDEX_ATTRIBUTE, parameters, "@@index"
+ )
+ left_suffix = exec_utils.get_param_value(
+ Parameters.LEFT_SUFFIX, parameters, "_LEFT"
+ )
+ right_suffix = exec_utils.get_param_value(
+ Parameters.RIGHT_SUFFIX, parameters, "_RIGHT"
+ )
+
+ relations = ocel.relations.copy()
+ relations = pandas_utils.insert_index(
+ relations, index_attribute, reset_index=False, copy_dataframe=False
+ )
+ relations_merged = relations.merge(
+ relations,
+ left_on=ocel.object_id_column,
+ right_on=ocel.object_id_column,
+ suffixes=(left_suffix, right_suffix),
+ )
+ if prefix_or_suffix == "prefix":
+ relations_merged = relations_merged[
+ relations_merged[index_attribute + left_suffix]
+ > relations_merged[index_attribute + right_suffix]
+ ]
+ else:
+ relations_merged = relations_merged[
+ relations_merged[index_attribute + left_suffix]
+ < relations_merged[index_attribute + right_suffix]
+ ]
+ relations_merged = relations_merged[
+ [
+ ocel.event_id_column + left_suffix,
+ ocel.event_id_column + right_suffix,
+ ocel.object_id_column,
+ ]
+ ]
+ relations_merged = relations_merged[
+ relations_merged[ocel.event_id_column + left_suffix]
+ != relations_merged[ocel.event_id_column + right_suffix]
+ ]
+ relations_merged = relations_merged.to_dict(orient="records")
+
+ ret = {}
+ for el in relations_merged:
+ e1 = el[ocel.event_id_column + left_suffix]
+ e2 = el[ocel.event_id_column + right_suffix]
+ obj = el[ocel.object_id_column]
+ if e1 not in ret:
+ ret[e1] = {}
+ if obj not in ret[e1]:
+ ret[e1][obj] = []
+ if e2 not in ret[e1][obj]:
+ ret[e1][obj].append(e2)
+
+ return ret
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/events_per_object_type.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/events_per_object_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf1f2a0f564202d368a0551e9e319e20442d7bfb
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/events_per_object_type.py
@@ -0,0 +1,74 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from pm4py.util import exec_utils, pandas_utils
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel import constants as ocel_constants
+from typing import Optional, Dict, Any
+
+
+class Parameters(Enum):
+ EVENT_ID = ocel_constants.PARAM_EVENT_ID
+ OBJECT_TYPE = ocel_constants.PARAM_OBJECT_TYPE
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Returns for each object type the number of events related to at least one object of the given type.
+
+ Parameters
+ ----------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the event identifier
+ - Parameters.OBJECT_TYPE => the object type column
+
+ Returns
+ -----------------
+ dictio
+ Dictionary associating to each object type the number of events related to at least one object of the given
+ type.
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+
+ object_types = pandas_utils.format_unique(
+ ocel.objects[object_type].unique()
+ )
+
+ ret = {}
+
+ for ot in object_types:
+ ret[ot] = ocel.relations[ocel.relations[object_type] == ot][
+ event_id
+ ].nunique()
+
+ return ret
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/events_per_type_per_activity.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/events_per_type_per_activity.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3631b47366a91dea2a0adf07bcfc2073ebf4672
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/events_per_type_per_activity.py
@@ -0,0 +1,107 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import exec_utils, pandas_utils
+from enum import Enum
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel import constants as ocel_constants
+
+
+class Parameters(Enum):
+ EVENT_ID = ocel_constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = ocel_constants.PARAM_EVENT_ACTIVITY
+ OBJECT_ID = ocel_constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = ocel_constants.PARAM_OBJECT_TYPE
+
+
+def apply(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> Dict[str, Dict[str, float]]:
+ """
+ Provided statistics (mean, median, min, max) on the number of events of a given activity that are associated
+ to objects of a given type.
+
+ Parameters
+ ---------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the event identifier
+ - Parameters.EVENT_ACTIVITY => the activity
+ - Parameters.OBJECT_ID => the object identifier
+ - Parameters.OBJECT_TYPE => the object type
+
+ Returns
+ ---------------
+ dictio
+ Dictionary in which the first key is the activity, the second key is the object type,
+ and the value is a dictionary containing the statistic for the given activity and object type.
+ """
+ if parameters is None:
+ parameters = {}
+
+ from statistics import mean, median
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+
+ activities = pandas_utils.format_unique(
+ ocel.events[event_activity].unique()
+ )
+ object_types = pandas_utils.format_unique(
+ ocel.objects[object_type].unique()
+ )
+
+ ret = {}
+
+ for act in activities:
+ if act not in ret:
+ ret[act] = {}
+ df = ocel.relations[ocel.relations[event_activity] == act]
+ for ot in object_types:
+ all_counts = list(
+ df[df[object_type] == ot]
+ .groupby(object_id)[event_id]
+ .agg("count")
+ .to_dict()
+ .values()
+ )
+ if all_counts:
+ ret[act][ot] = {
+ "min": min(all_counts),
+ "max": max(all_counts),
+ "mean": mean(all_counts),
+ "median": median(all_counts),
+ }
+
+ return ret
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/explode.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/explode.py
new file mode 100644
index 0000000000000000000000000000000000000000..97ed6492cacf732ea922ed6519afb76e88d6e112
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/explode.py
@@ -0,0 +1,57 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from copy import deepcopy
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Explode an OCEL: an event associated to N objects is "split" to N events, each one associated to one object.
+
+ Parameters
+ -----------------
+ ocel
+ Object-centric event log
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ -----------------
+ ocel
+ Exploded object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ ocel = deepcopy(ocel)
+ ocel.relations[ocel.event_id_column] = (
+ ocel.relations[ocel.event_id_column]
+ + "_"
+ + ocel.relations[ocel.object_id_column]
+ )
+ ocel.events = ocel.relations.copy()
+ del ocel.events[ocel.object_id_column]
+ del ocel.events[ocel.object_type_column]
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/extended_table.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/extended_table.py
new file mode 100644
index 0000000000000000000000000000000000000000..de7faed729a061c9335096a119888df0b3e13ff7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/extended_table.py
@@ -0,0 +1,356 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import ast
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+import importlib.util
+
+from pm4py.objects.ocel import constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils, pandas_utils, constants as pm4_constants
+
+
+class Parameters(Enum):
+ OBJECT_TYPE_PREFIX = constants.PARAM_OBJECT_TYPE_PREFIX_EXTENDED
+ EVENT_ID = constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = constants.PARAM_EVENT_TIMESTAMP
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+ INTERNAL_INDEX = constants.PARAM_INTERNAL_INDEX
+
+
+def _construct_progress_bar(progress_length):
+ if importlib.util.find_spec("tqdm") and pm4_constants.SHOW_PROGRESS_BAR:
+ if progress_length > 1:
+ from tqdm.auto import tqdm
+
+ return tqdm(
+ total=progress_length,
+ desc="importing OCEL, parsed rows :: ",
+ )
+ return None
+
+
+def _destroy_progress_bar(progress):
+ if progress is not None:
+ progress.close()
+ del progress
+
+
+def safe_parse_list(value):
+ """
+ Safely parse a string into a list using ast.literal_eval.
+
+ Args:
+ value: The value to parse
+
+ Returns:
+ A list if the parsing was successful, otherwise an empty list
+ """
+ if isinstance(value, str) and value.startswith('['):
+ try:
+ return ast.literal_eval(value)
+ except (SyntaxError, ValueError):
+ return []
+ return []
+
+
+def get_ocel_from_extended_table(
+ df: pd.DataFrame,
+ objects_df: Optional[pd.DataFrame] = None,
+ parameters: Optional[Dict[Any, Any]] = None,
+ chunk_size: int = 50000, # Default chunk size
+) -> OCEL:
+ """
+ Get an OCEL object from an extended table format.
+
+ Args:
+ df: The DataFrame in extended table format
+ objects_df: Optional DataFrame of objects
+ parameters: Optional parameters dictionary
+ chunk_size: Size of chunks to process
+
+ Returns:
+ An OCEL object
+ """
+ if parameters is None:
+ parameters = {}
+
+ # Extract parameters
+ object_type_prefix = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE_PREFIX,
+ parameters,
+ constants.DEFAULT_OBJECT_TYPE_PREFIX_EXTENDED,
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, constants.DEFAULT_EVENT_ACTIVITY
+ )
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, constants.DEFAULT_EVENT_ID
+ )
+ event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP,
+ parameters,
+ constants.DEFAULT_EVENT_TIMESTAMP,
+ )
+ object_id_column = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, constants.DEFAULT_OBJECT_ID
+ )
+ object_type_column = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, constants.DEFAULT_OBJECT_TYPE
+ )
+ internal_index = exec_utils.get_param_value(
+ Parameters.INTERNAL_INDEX, parameters, constants.DEFAULT_INTERNAL_INDEX
+ )
+
+ # Parse timestamp column upfront in the original DataFrame
+ df[event_timestamp] = pandas_utils.dataframe_column_string_to_datetime(df[event_timestamp], format=pm4_constants.DEFAULT_TIMESTAMP_PARSE_FORMAT)
+
+ # Identify columns efficiently
+ object_type_columns = [col for col in df.columns if col.startswith(object_type_prefix)]
+ non_object_type_columns = [col for col in df.columns if not col.startswith(object_type_prefix)]
+
+ # Pre-compute object type mappings
+ object_type_mapping = {ot: ot.split(object_type_prefix)[1] for ot in object_type_columns}
+
+ # Create events DataFrame (only non-object columns)
+ events_df = df[non_object_type_columns].copy()
+
+ # Add internal index for sorting events
+ events_df.loc[:, internal_index] = events_df.index
+
+ # Sort by timestamp and index
+ events_df = events_df.sort_values([event_timestamp, internal_index])
+
+ # Track unique objects if needed
+ unique_objects = {ot: set() for ot in object_type_columns} if objects_df is None else None
+
+ # Initialize progress bar
+ progress = _construct_progress_bar(len(events_df))
+
+ # Create a filtered DataFrame with only needed columns
+ needed_columns = [event_id, event_activity, event_timestamp] + object_type_columns
+ filtered_df = df[needed_columns]
+ del df
+
+ pa = None
+ use_pyarrow = False
+ if importlib.util.find_spec("pyarrow") is not None:
+ try:
+ import pyarrow as pa # type: ignore
+
+ use_pyarrow = True
+ except ModuleNotFoundError:
+ pa = None
+ use_pyarrow = False
+
+ class RelationAccumulator:
+ """
+ Accumulate relation data either through PyArrow arrays or plain Python lists,
+ depending on the availability of PyArrow.
+ """
+
+ _order = ("event_id", "event_activity", "event_timestamp", "object_id", "object_type")
+
+ def __init__(self, use_pyarrow: bool, pa_module):
+ self.use_pyarrow = use_pyarrow
+ self.pa = pa_module
+ if use_pyarrow and pa_module is not None:
+ self._types = {
+ "event_id": pa_module.large_string(),
+ "event_activity": pa_module.large_string(),
+ "event_timestamp": pa_module.timestamp("ns"),
+ "object_id": pa_module.large_string(),
+ "object_type": pa_module.large_string(),
+ }
+ self._chunks = {key: [] for key in self._order}
+ else:
+ self._chunks = {key: [] for key in self._order}
+ self.use_pyarrow = False
+ self.pa = None
+
+ def append_chunk(self, event_ids, event_activities, event_timestamps, object_ids, object_types):
+ if not event_ids:
+ return
+ if self.use_pyarrow:
+ pa_module = self.pa
+ self._chunks["event_id"].append(pa_module.array(event_ids, type=self._types["event_id"]))
+ self._chunks["event_activity"].append(pa_module.array(event_activities, type=self._types["event_activity"]))
+ self._chunks["event_timestamp"].append(pa_module.array(event_timestamps, type=self._types["event_timestamp"]))
+ self._chunks["object_id"].append(pa_module.array(object_ids, type=self._types["object_id"]))
+ self._chunks["object_type"].append(pa_module.array(object_types, type=self._types["object_type"]))
+ else:
+ self._chunks["event_id"].extend(event_ids)
+ self._chunks["event_activity"].extend(event_activities)
+ self._chunks["event_timestamp"].extend(event_timestamps)
+ self._chunks["object_id"].extend(object_ids)
+ self._chunks["object_type"].extend(object_types)
+
+ def has_data(self) -> bool:
+ values = self._chunks["event_id"]
+ if self.use_pyarrow:
+ return bool(values) and any(len(arr) > 0 for arr in values)
+ return bool(values)
+
+ def to_columns(self):
+ if not self.use_pyarrow:
+ return {key: self._chunks[key] for key in self._order}
+
+ pa_module = self.pa
+ result = {}
+ for key in self._order:
+ arrays = self._chunks[key]
+ if arrays:
+ concatenated = pa_module.concat_arrays(arrays) if len(arrays) > 1 else arrays[0]
+ else:
+ concatenated = pa_module.array([], type=self._types[key])
+ result[key] = concatenated.to_pandas()
+ return result
+
+ relations_accumulator = RelationAccumulator(use_pyarrow, pa)
+
+ # Process DataFrame in chunks to avoid memory issues
+ total_rows = len(filtered_df)
+
+ for chunk_start in range(0, total_rows, chunk_size):
+ chunk_end = min(chunk_start + chunk_size, total_rows)
+
+ # Extract a chunk
+ chunk = filtered_df.iloc[chunk_start:chunk_end]
+
+ # Convert small chunk to records for faster processing
+ chunk_records = chunk.to_dict(orient='records')
+
+ # Create chunk-specific temporary lists
+ chunk_ev_ids = []
+ chunk_ev_activities = []
+ chunk_ev_timestamps = []
+ chunk_obj_ids = []
+ chunk_obj_types = []
+ chunk_unique_objects = {ot: list() for ot in object_type_columns} if objects_df is None else None
+
+ # Process records in the current chunk
+ for record in chunk_records:
+ for ot in object_type_columns:
+ obj_list = safe_parse_list(record[ot])
+ if obj_list:
+ ot_striped = object_type_mapping[ot]
+
+ # Update unique objects for this chunk if tracking
+ if chunk_unique_objects is not None:
+ chunk_unique_objects[ot].extend(obj_list)
+
+ # Extend chunk-specific data efficiently
+ n_objs = len(obj_list)
+ chunk_ev_ids.extend([record[event_id]] * n_objs)
+ chunk_ev_activities.extend([record[event_activity]] * n_objs)
+ chunk_ev_timestamps.extend([record[event_timestamp]] * n_objs)
+ chunk_obj_ids.extend(obj_list)
+ chunk_obj_types.extend([ot_striped] * n_objs)
+
+ # Update progress (1 item at a time)
+ if progress is not None:
+ progress.update(1)
+
+ del chunk_records
+
+ relations_accumulator.append_chunk(
+ chunk_ev_ids,
+ chunk_ev_activities,
+ chunk_ev_timestamps,
+ chunk_obj_ids,
+ chunk_obj_types,
+ )
+ del chunk_ev_ids, chunk_ev_activities, chunk_ev_timestamps, chunk_obj_ids, chunk_obj_types
+
+ # Merge unique objects if tracking
+ if unique_objects is not None:
+ for ot in object_type_columns:
+ unique_objects[ot].update(set(chunk_unique_objects[ot]))
+
+ # Free memory
+ if chunk_unique_objects is not None:
+ del chunk_unique_objects
+
+ # Clean up progress bar
+ _destroy_progress_bar(progress)
+
+ del filtered_df
+
+ # Create the relations DataFrame only once at the end
+ relations = pandas_utils.DATAFRAME.DataFrame()
+ if relations_accumulator.has_data():
+ relation_columns = relations_accumulator.to_columns()
+ relations = pandas_utils.DATAFRAME.DataFrame({
+ event_id: relation_columns["event_id"],
+ event_activity: relation_columns["event_activity"],
+ event_timestamp: relation_columns["event_timestamp"],
+ object_id_column: relation_columns["object_id"],
+ object_type_column: relation_columns["object_type"]
+ })
+
+ # Add internal index for sorting the relations
+ relations[internal_index] = relations.index
+
+ # Sort by timestamp and index
+ if type(relations) is pd.DataFrame:
+ relations.sort_values([event_timestamp, internal_index], inplace=True)
+ else:
+ relations = relations.sort_values([event_timestamp, internal_index])
+
+ # Remove temporary index column
+ del relations[internal_index]
+
+ # Remove temporary index column from events
+ del events_df[internal_index]
+
+ # Create objects DataFrame if not provided
+ if objects_df is None:
+ obj_types_list = []
+ obj_ids_list = []
+
+ for ot in object_type_columns:
+ ot_striped = object_type_mapping[ot]
+ obj_ids = list(unique_objects[ot])
+
+ if obj_ids:
+ obj_types_list.extend([ot_striped] * len(obj_ids))
+ obj_ids_list.extend(obj_ids)
+
+ objects_df = pandas_utils.DATAFRAME.DataFrame({
+ object_type_column: obj_types_list,
+ object_id_column: obj_ids_list
+ })
+
+ # Free memory
+ del obj_types_list, obj_ids_list, unique_objects
+
+ # Create and return OCEL object
+ return OCEL(
+ events=events_df,
+ objects=objects_df,
+ relations=relations,
+ parameters=parameters,
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/filtering_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/filtering_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7632e581e6ce340168a0d0f36e102c1e1e105854
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/filtering_utils.py
@@ -0,0 +1,262 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel import constants
+from enum import Enum
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any, Set
+from pm4py.util import exec_utils, pandas_utils
+import pandas as pd
+
+
+class Parameters(Enum):
+ EVENT_ID = constants.PARAM_EVENT_ID
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = constants.PARAM_OBJECT_TYPE
+
+
+def _get_unique_ids(df: pd.DataFrame, column: str) -> Set:
+ """Helper function to get unique IDs from a DataFrame column."""
+ if df.empty:
+ return set()
+ return set(pandas_utils.format_unique(df[column].unique()))
+
+
+def propagate_event_filtering(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> OCEL:
+ """
+ Propagates the filtering at the event level to the remaining parts of the OCEL structure
+ (objects, relations)
+
+ Parameters
+ ----------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the column to be used as case identifier
+ - Parameters.OBJECT_ID => the column to be used as object identifier
+ - Parameters.OBJECT_TYPE => the column to be used as object type
+
+ Returns
+ ----------------
+ ocel
+ Object-centric event log with propagated filter
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ event_id_2 = event_id + "_2"
+ object_id_2 = object_id + "_2"
+
+ # Get unique event IDs efficiently
+ selected_event_ids = _get_unique_ids(ocel.events, event_id)
+ if not selected_event_ids:
+ # If no events are selected, clear all components
+ for df_attr in ['events', 'objects', 'relations', 'e2e', 'o2o', 'object_changes']:
+ setattr(ocel, df_attr, getattr(ocel, df_attr).iloc[0:0])
+ return ocel
+
+ # Filter relations and get unique object IDs in one pass
+ ocel.relations = ocel.relations[ocel.relations[event_id].isin(selected_event_ids)]
+ selected_object_ids = _get_unique_ids(ocel.relations, object_id)
+
+ # Filter remaining components efficiently
+ if selected_object_ids:
+ # Apply filters to object-related components
+ ocel.objects = ocel.objects[ocel.objects[object_id].isin(selected_object_ids)]
+ ocel.object_changes = ocel.object_changes[ocel.object_changes[object_id].isin(selected_object_ids)]
+
+ # Combined filtering for o2o with single mask
+ o2o_mask = (ocel.o2o[object_id].isin(selected_object_ids) &
+ ocel.o2o[object_id_2].isin(selected_object_ids))
+ ocel.o2o = ocel.o2o[o2o_mask]
+ else:
+ # If no objects are selected, clear objects-related components
+ for df_attr in ['objects', 'o2o', 'object_changes']:
+ setattr(ocel, df_attr, getattr(ocel, df_attr).iloc[0:0])
+
+ # Filter e2e with single mask
+ e2e_mask = (ocel.e2e[event_id].isin(selected_event_ids) &
+ ocel.e2e[event_id_2].isin(selected_event_ids))
+ ocel.e2e = ocel.e2e[e2e_mask]
+
+ return ocel
+
+
+def propagate_object_filtering(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> OCEL:
+ """
+ Propagates the filtering at the object level to the remaining parts of the OCEL structure
+ (events, relations)
+
+ Parameters
+ ----------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the column to be used as case identifier
+ - Parameters.OBJECT_ID => the column to be used as object identifier
+ - Parameters.OBJECT_TYPE => the column to be used as object type
+
+ Returns
+ ----------------
+ ocel
+ Object-centric event log with propagated filter
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ event_id_2 = event_id + "_2"
+ object_id_2 = object_id + "_2"
+
+ # Get unique object IDs efficiently
+ selected_object_ids = _get_unique_ids(ocel.objects, object_id)
+ if not selected_object_ids:
+ # If no objects are selected, clear all components
+ for df_attr in ['events', 'objects', 'relations', 'e2e', 'o2o', 'object_changes']:
+ setattr(ocel, df_attr, getattr(ocel, df_attr).iloc[0:0])
+ return ocel
+
+ # Filter relations and get unique event IDs in one pass
+ ocel.relations = ocel.relations[ocel.relations[object_id].isin(selected_object_ids)]
+ selected_event_ids = _get_unique_ids(ocel.relations, event_id)
+
+ # Filter event-related components
+ if selected_event_ids:
+ ocel.events = ocel.events[ocel.events[event_id].isin(selected_event_ids)]
+
+ # Combined filtering for e2e with single mask
+ e2e_mask = (ocel.e2e[event_id].isin(selected_event_ids) &
+ ocel.e2e[event_id_2].isin(selected_event_ids))
+ ocel.e2e = ocel.e2e[e2e_mask]
+ else:
+ # If no events are selected, clear events-related components
+ for df_attr in ['events', 'e2e']:
+ setattr(ocel, df_attr, getattr(ocel, df_attr).iloc[0:0])
+
+ # Filter object-related components
+ o2o_mask = (ocel.o2o[object_id].isin(selected_object_ids) &
+ ocel.o2o[object_id_2].isin(selected_object_ids))
+ ocel.o2o = ocel.o2o[o2o_mask]
+
+ ocel.object_changes = ocel.object_changes[
+ ocel.object_changes[object_id].isin(selected_object_ids)
+ ]
+
+ return ocel
+
+
+def propagate_relations_filtering(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> OCEL:
+ """
+ Propagates the filtering at the relations level to the remaining parts of the OCEL structure
+ (events, objects)
+
+ Parameters
+ ----------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the column to be used as case identifier
+ - Parameters.OBJECT_ID => the column to be used as object identifier
+ - Parameters.OBJECT_TYPE => the column to be used as object type
+
+ Returns
+ ----------------
+ ocel
+ Object-centric event log with propagated filter
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ event_id_2 = event_id + "_2"
+ object_id_2 = object_id + "_2"
+
+ # Efficiently get unique IDs from relations
+ relation_event_ids = _get_unique_ids(ocel.relations, event_id)
+ relation_object_ids = _get_unique_ids(ocel.relations, object_id)
+
+ if not relation_event_ids or not relation_object_ids:
+ # If no relations are selected, clear all components
+ for df_attr in ['events', 'objects', 'relations', 'e2e', 'o2o', 'object_changes']:
+ setattr(ocel, df_attr, getattr(ocel, df_attr).iloc[0:0])
+ return ocel
+
+ # Compute intersections with existing components
+ existing_event_ids = _get_unique_ids(ocel.events, event_id)
+ existing_object_ids = _get_unique_ids(ocel.objects, object_id)
+
+ selected_event_ids = relation_event_ids.intersection(existing_event_ids)
+ selected_object_ids = relation_object_ids.intersection(existing_object_ids)
+
+ if not selected_event_ids or not selected_object_ids:
+ # If no valid intersections, clear all components
+ for df_attr in ['events', 'objects', 'relations', 'e2e', 'o2o', 'object_changes']:
+ setattr(ocel, df_attr, getattr(ocel, df_attr).iloc[0:0])
+ return ocel
+
+ # Filter all components in a single operation each
+ ocel.events = ocel.events[ocel.events[event_id].isin(selected_event_ids)]
+ ocel.objects = ocel.objects[ocel.objects[object_id].isin(selected_object_ids)]
+
+ # Filter relations with combined condition
+ relations_mask = (ocel.relations[event_id].isin(selected_event_ids) &
+ ocel.relations[object_id].isin(selected_object_ids))
+ ocel.relations = ocel.relations[relations_mask]
+
+ # Filter e2e and o2o with combined conditions
+ e2e_mask = (ocel.e2e[event_id].isin(selected_event_ids) &
+ ocel.e2e[event_id_2].isin(selected_event_ids))
+ ocel.e2e = ocel.e2e[e2e_mask]
+
+ o2o_mask = (ocel.o2o[object_id].isin(selected_object_ids) &
+ ocel.o2o[object_id_2].isin(selected_object_ids))
+ ocel.o2o = ocel.o2o[o2o_mask]
+
+ ocel.object_changes = ocel.object_changes[
+ ocel.object_changes[object_id].isin(selected_object_ids)
+ ]
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/flattening.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/flattening.py
new file mode 100644
index 0000000000000000000000000000000000000000..24af83cbccbbf151b4db9ad8b47dac024d898aae
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/flattening.py
@@ -0,0 +1,98 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+import pandas as pd
+
+from pm4py.objects.ocel import constants as ocel_constants
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import constants, xes_constants
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ EVENT_ACTIVITY = ocel_constants.PARAM_EVENT_ACTIVITY
+ EVENT_TIMESTAMP = ocel_constants.PARAM_EVENT_TIMESTAMP
+
+
+def flatten(
+ ocel: OCEL, ot: str, parameters: Optional[Dict[Any, Any]] = None
+) -> pd.DataFrame:
+ """
+ Flattens the object-centric event log to a traditional event log with the choice of an object type.
+ In the flattened log, the objects of a given object type are the cases, and each case
+ contains the set of events related to the object.
+
+ Parameters
+ -------------------
+ ocel
+ Object-centric event log
+ ot
+ Object type
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ACTIVITY
+ - Parameters.EVENT_TIMESTAMP
+
+ Returns
+ ------------------
+ dataframe
+ Flattened log in the form of a Pandas dataframe
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ event_timestamp = exec_utils.get_param_value(
+ Parameters.EVENT_TIMESTAMP, parameters, ocel.event_timestamp
+ )
+
+ objects = ocel.objects[ocel.objects[ocel.object_type_column] == ot]
+ objects = objects.rename(
+ columns={ocel.object_id_column: xes_constants.DEFAULT_TRACEID_KEY}
+ )
+ objects = objects.rename(
+ columns={
+ x: constants.CASE_ATTRIBUTE_PREFIX + x for x in objects.columns
+ }
+ )
+
+ relations = ocel.relations[ocel.relations[ocel.object_type_column] == ot][
+ [ocel.object_id_column, ocel.event_id_column]
+ ].drop_duplicates()
+ relations = relations.rename(
+ columns={ocel.object_id_column: constants.CASE_CONCEPT_NAME}
+ )
+
+ objects = objects.merge(relations, on=constants.CASE_CONCEPT_NAME)
+
+ events = ocel.events.merge(objects, on=ocel.event_id_column).rename(
+ columns={
+ event_activity: xes_constants.DEFAULT_NAME_KEY,
+ event_timestamp: xes_constants.DEFAULT_TIMESTAMP_KEY,
+ }
+ )
+
+ return events
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/log_ocel.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/log_ocel.py
new file mode 100644
index 0000000000000000000000000000000000000000..983c98e416eaaae75a99574b4a715c8cb958c1c5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/log_ocel.py
@@ -0,0 +1,595 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from pm4py.objects.log.obj import EventLog, EventStream
+import pandas as pd
+from typing import Optional, Dict, Any, Collection, Union
+from pm4py.util import exec_utils, constants, xes_constants, pandas_utils
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel import constants as ocel_constants
+from pm4py.objects.conversion.log import converter as log_converter
+from pm4py.objects.ocel.util import ocel_consistency
+from copy import copy
+import math
+
+
+class Parameters(Enum):
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
+ CASE_ATTRIBUTE_PREFIX = constants.PARAMETER_KEY_CASE_ATTRIBUTE_PRFIX
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
+ TARGET_OBJECT_TYPE = "target_object_type"
+ TARGET_OBJECT_TYPE_2 = "target_object_type_2"
+ LEFT_INDEX = "left_index"
+ RIGHT_INDEX = "right_index"
+ DIRECTION = "direction"
+
+
+def __postprocess_stream(list_events):
+ """
+ Postprocess the list of events of the stream in order to make sure
+ that there are no NaN/NaT values
+
+ Parameters
+ -------------
+ list_events
+ List of events
+
+ Returns
+ -------------
+ list_events
+ Postprocessed stream
+ """
+ for event in list_events:
+ event_keys = list(event.keys())
+ for k in event_keys:
+ typ_k = type(event[k])
+ if typ_k is pd._libs.tslibs.nattype.NaTType:
+ del event[k]
+ continue
+ elif (typ_k is float or typ_k is int) and math.isnan(event[k]):
+ del event[k]
+ continue
+ elif event[k] is None:
+ del event[k]
+ continue
+ return list_events
+
+
+def from_traditional_log(
+ log: EventLog, parameters: Optional[Dict[Any, Any]] = None
+) -> OCEL:
+ """
+ Transforms an EventLog to an OCEL
+
+ Parameters
+ -----------------
+ log
+ Event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.TARGET_OBJECT_TYPE => the name of the object type to which the cases should be mapped
+ - Parameters.ACTIVITY_KEY => the attribute to use as activity
+ - Parameters.TIMESTAMP_KEY => the attribute to use as timestamp
+ - Parameters.CASE_ID_KEY => the attribute to use as case identifier
+
+ Returns
+ -----------------
+ ocel
+ OCEL (equivalent to the provided event log)
+ """
+ if parameters is None:
+ parameters = {}
+
+ log = log_converter.apply(
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+
+ target_object_type = exec_utils.get_param_value(
+ Parameters.TARGET_OBJECT_TYPE, parameters, "OTYPE"
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, xes_constants.DEFAULT_TRACEID_KEY
+ )
+
+ events = []
+ objects = []
+ relations = []
+
+ ev_count = 0
+ for trace in log:
+ case_id = trace.attributes[case_id_key]
+ obj = {
+ ocel_constants.DEFAULT_OBJECT_ID: case_id,
+ ocel_constants.DEFAULT_OBJECT_TYPE: target_object_type,
+ }
+ for attr in trace.attributes:
+ if attr != case_id_key:
+ obj[attr] = trace.attributes[attr]
+ objects.append(obj)
+ for ev in trace:
+ ev_count = ev_count + 1
+ activity = ev[activity_key]
+ timestamp = ev[timestamp_key]
+ eve = {
+ ocel_constants.DEFAULT_EVENT_ID: str(ev_count),
+ ocel_constants.DEFAULT_EVENT_ACTIVITY: activity,
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP: timestamp,
+ }
+ for attr in ev:
+ if attr not in [activity, timestamp]:
+ eve[attr] = ev[attr]
+ events.append(eve)
+ relations.append(
+ {
+ ocel_constants.DEFAULT_EVENT_ID: str(ev_count),
+ ocel_constants.DEFAULT_EVENT_ACTIVITY: activity,
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP: timestamp,
+ ocel_constants.DEFAULT_OBJECT_ID: case_id,
+ ocel_constants.DEFAULT_OBJECT_TYPE: target_object_type,
+ }
+ )
+
+ events = pandas_utils.instantiate_dataframe(events)
+ objects = pandas_utils.instantiate_dataframe(objects)
+ relations = pandas_utils.instantiate_dataframe(relations)
+
+ return OCEL(events=events, objects=objects, relations=relations)
+
+
+def __get_events_dataframe(
+ df: pd.DataFrame,
+ activity_key: str,
+ timestamp_key: str,
+ case_id_key: str,
+ case_attribute_prefix: str,
+ events_prefix="E",
+) -> pd.DataFrame:
+ """
+ Internal method to get the events dataframe out of a traditional log stored as Pandas dataframe
+ """
+ columns = {case_id_key}.union(
+ set(x for x in df.columns if not x.startswith(case_attribute_prefix))
+ )
+ columns = list(columns)
+ df = df[columns]
+ df = df.rename(
+ columns={
+ activity_key: ocel_constants.DEFAULT_EVENT_ACTIVITY,
+ timestamp_key: ocel_constants.DEFAULT_EVENT_TIMESTAMP,
+ case_id_key: ocel_constants.DEFAULT_OBJECT_ID,
+ }
+ )
+ df[ocel_constants.DEFAULT_EVENT_ID] = events_prefix + df.index.astype(str)
+ return df
+
+
+def __get_objects_dataframe(
+ df: pd.DataFrame,
+ case_id_key: str,
+ case_attribute_prefix: str,
+ target_object_type: str,
+) -> pd.DataFrame:
+ """
+ Internal method to get the objects dataframe out of a traditional log stored as Pandas dataframe
+ """
+ columns = {x for x in df.columns if x.startswith(case_attribute_prefix)}
+ columns = list(columns)
+ df = df[columns]
+ df = df.rename(columns={case_id_key: ocel_constants.DEFAULT_OBJECT_ID})
+ df = df.groupby(ocel_constants.DEFAULT_OBJECT_ID).first().reset_index()
+ df[ocel_constants.DEFAULT_OBJECT_TYPE] = target_object_type
+ return df
+
+
+def __get_relations_from_events(
+ events: pd.DataFrame, target_object_type: str
+) -> pd.DataFrame:
+ """
+ Internal method to get the relations dataframe out of a traditional log stored as Pandas dataframe
+ """
+ relations = events[
+ [
+ ocel_constants.DEFAULT_EVENT_ACTIVITY,
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP,
+ ocel_constants.DEFAULT_OBJECT_ID,
+ ocel_constants.DEFAULT_EVENT_ID,
+ ]
+ ]
+ relations[ocel_constants.DEFAULT_OBJECT_TYPE] = target_object_type
+ return relations
+
+
+def from_traditional_pandas(
+ df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None
+) -> OCEL:
+ """
+ Transforms a dataframe to an OCEL
+
+ Parameters
+ -----------------
+ df
+ Pandas dataframe
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.TARGET_OBJECT_TYPE => the name of the object type to which the cases should be mapped
+ - Parameters.ACTIVITY_KEY => the attribute to use as activity
+ - Parameters.TIMESTAMP_KEY => the attribute to use as timestamp
+ - Parameters.CASE_ID_KEY => the attribute to use as case identifier
+ - Parameters.CASE_ATTRIBUTE_PREFIX => the prefix identifying the attributes at the case level
+
+ Returns
+ -----------------
+ ocel
+ OCEL (equivalent to the provided event log)
+ """
+ if parameters is None:
+ parameters = {}
+
+ target_object_type = exec_utils.get_param_value(
+ Parameters.TARGET_OBJECT_TYPE, parameters, "OTYPE"
+ )
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ case_attribute_prefix = exec_utils.get_param_value(
+ Parameters.CASE_ATTRIBUTE_PREFIX,
+ parameters,
+ constants.CASE_ATTRIBUTE_PREFIX,
+ )
+
+ events = __get_events_dataframe(
+ df, activity_key, timestamp_key, case_id_key, case_attribute_prefix
+ )
+ objects = __get_objects_dataframe(
+ df, case_id_key, case_attribute_prefix, target_object_type
+ )
+ relations = __get_relations_from_events(events, target_object_type)
+ del events[ocel_constants.DEFAULT_OBJECT_ID]
+
+ events = events.sort_values(
+ [
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP,
+ ocel_constants.DEFAULT_EVENT_ID,
+ ]
+ )
+ relations = relations.sort_values(
+ [
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP,
+ ocel_constants.DEFAULT_EVENT_ID,
+ ]
+ )
+
+ return OCEL(events=events, objects=objects, relations=relations)
+
+
+def from_interleavings(
+ df1: pd.DataFrame,
+ df2: pd.DataFrame,
+ interleavings: pd.DataFrame,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Transforms a couple of dataframes, along with the interleavings between
+ them, to an OCEL.
+
+ Parameters
+ ----------
+ df1
+ First of the two dataframes
+ df2
+ Second of the two dataframes
+ interleavings
+ Interleavings dataframe
+ parameters
+ Parameters of the algorithm, including:
+
+ - Parameters.ACTIVITY_KEY => the attribute to use as activity
+ - Parameters.TIMESTAMP_KEY => the attribute to use as timestamp
+ - Parameters.CASE_ID_KEY => the attribute to use as case identifier
+ - Parameters.CASE_ATTRIBUTE_PREFIX => the prefix identifying the attributes at the case level
+ - Parameters.TARGET_OBJECT_TYPE => the name of the object type to which the cases of the first log should be mapped
+ - Parameters.TARGET_OBJECT_TYPE_2 => the name of the object type to which the cases of the second log should be mapped
+ - Parameters.LEFT_INDEX => the index column of the events of the first dataframe, in the interleavings dataframe
+ - Parameters.RIGHT_INDEX => the index column of the events of the second dataframe, in the interleavings dataframe.
+ - Parameters.DIRECTION => the direction of the interleavings (LR or RL)
+
+ Returns
+ -----------------
+ ocel
+ OCEL (equivalent to the provided event log)
+
+ """
+ if parameters is None:
+ parameters = {}
+
+ activity_key = exec_utils.get_param_value(
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
+ )
+ timestamp_key = exec_utils.get_param_value(
+ Parameters.TIMESTAMP_KEY,
+ parameters,
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
+ )
+ case_id_key = exec_utils.get_param_value(
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
+ )
+ case_attribute_prefix = exec_utils.get_param_value(
+ Parameters.CASE_ATTRIBUTE_PREFIX,
+ parameters,
+ constants.CASE_ATTRIBUTE_PREFIX,
+ )
+ target_object_type = exec_utils.get_param_value(
+ Parameters.TARGET_OBJECT_TYPE, parameters, "OTYPE"
+ )
+ target_object_type_2 = exec_utils.get_param_value(
+ Parameters.TARGET_OBJECT_TYPE_2, parameters, "OTYPE2"
+ )
+ left_index = exec_utils.get_param_value(
+ Parameters.LEFT_INDEX, parameters, "@@left_index"
+ )
+ right_index = exec_utils.get_param_value(
+ Parameters.RIGHT_INDEX, parameters, "@@right_index"
+ )
+ direction = exec_utils.get_param_value(
+ Parameters.DIRECTION, parameters, "@@direction"
+ )
+
+ events1 = __get_events_dataframe(
+ df1,
+ activity_key,
+ timestamp_key,
+ case_id_key,
+ case_attribute_prefix,
+ events_prefix="E1_",
+ )
+ objects1 = __get_objects_dataframe(
+ df1, case_id_key, case_attribute_prefix, target_object_type
+ )
+ relations1 = __get_relations_from_events(events1, target_object_type)
+
+ relations1_minimal = relations1[
+ {
+ ocel_constants.DEFAULT_EVENT_ID,
+ ocel_constants.DEFAULT_OBJECT_ID,
+ ocel_constants.DEFAULT_OBJECT_TYPE,
+ }
+ ]
+
+ events2 = __get_events_dataframe(
+ df2,
+ activity_key,
+ timestamp_key,
+ case_id_key,
+ case_attribute_prefix,
+ events_prefix="E2_",
+ )
+ objects2 = __get_objects_dataframe(
+ df2, case_id_key, case_attribute_prefix, target_object_type_2
+ )
+ relations2 = __get_relations_from_events(events2, target_object_type_2)
+ relations2_minimal = relations2[
+ {
+ ocel_constants.DEFAULT_EVENT_ID,
+ ocel_constants.DEFAULT_OBJECT_ID,
+ ocel_constants.DEFAULT_OBJECT_TYPE,
+ }
+ ]
+
+ interleavings[left_index] = "E1_" + interleavings[left_index].astype(
+ int
+ ).astype(str)
+ interleavings[right_index] = "E2_" + interleavings[right_index].astype(
+ int
+ ).astype(str)
+ interleavings_lr = interleavings[interleavings[direction] == "LR"][
+ [left_index, right_index]
+ ]
+ interleavings_rl = interleavings[interleavings[direction] == "RL"][
+ [left_index, right_index]
+ ]
+
+ relations3 = events1.merge(
+ interleavings_lr,
+ left_on=ocel_constants.DEFAULT_EVENT_ID,
+ right_on=left_index,
+ )
+ relations3 = relations3.merge(
+ relations2_minimal,
+ left_on=right_index,
+ right_on=ocel_constants.DEFAULT_EVENT_ID,
+ suffixes=("", "_@#@#RIGHT"),
+ )
+ relations3[ocel_constants.DEFAULT_OBJECT_ID] = relations3[
+ ocel_constants.DEFAULT_OBJECT_ID + "_@#@#RIGHT"
+ ]
+ relations3[ocel_constants.DEFAULT_OBJECT_TYPE] = target_object_type_2
+
+ relations4 = events2.merge(
+ interleavings_rl,
+ left_on=ocel_constants.DEFAULT_EVENT_ID,
+ right_on=right_index,
+ )
+ relations4 = relations4.merge(
+ relations1_minimal,
+ left_on=left_index,
+ right_on=ocel_constants.DEFAULT_EVENT_ID,
+ suffixes=("", "_@#@#LEFT"),
+ )
+ relations4[ocel_constants.DEFAULT_OBJECT_ID] = relations4[
+ ocel_constants.DEFAULT_OBJECT_ID + "_@#@#LEFT"
+ ]
+ relations4[ocel_constants.DEFAULT_OBJECT_TYPE] = target_object_type
+
+ del events1[ocel_constants.DEFAULT_OBJECT_ID]
+ del events2[ocel_constants.DEFAULT_OBJECT_ID]
+
+ events = pandas_utils.concat([events1, events2])
+ objects = pandas_utils.concat([objects1, objects2])
+ relations = pandas_utils.concat(
+ [relations1, relations2, relations3, relations4]
+ )
+
+ events = events.sort_values(
+ [
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP,
+ ocel_constants.DEFAULT_EVENT_ID,
+ ]
+ )
+ relations = relations.sort_values(
+ [
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP,
+ ocel_constants.DEFAULT_EVENT_ID,
+ ]
+ )
+
+ return OCEL(events=events, objects=objects, relations=relations)
+
+
+def log_to_ocel_multiple_obj_types(
+ log_obj: Union[EventLog, EventStream, pd.DataFrame],
+ activity_column: str,
+ timestamp_column: str,
+ obj_types: Collection[str],
+ obj_separator: str = " AND ",
+ additional_event_attributes: Optional[Collection[str]] = None,
+ additional_object_attributes: Optional[Dict[str, Collection[str]]] = None,
+) -> OCEL:
+ """
+ Converts an event log to an object-centric event log with one or more than one
+ object types.
+
+ Parameters
+ ---------------
+ log_obj
+ Log object
+ activity_column
+ Activity column
+ timestamp_column
+ Timestamp column
+ object_types
+ List of columns to consider as object types
+ obj_separator
+ Separator between different objects in the same column
+ additional_event_attributes
+ Additional attributes to be considered as event attributes in the OCEL
+ additional_object_attributes
+ Additional attributes per object type to be considered as object attributes in the OCEL
+ (dictionary in which object types are associated to their attributes, i.e.,
+ {"order": ["quantity", "cost"], "invoice": ["date", "due date"]})
+
+ Returns
+ ----------------
+ ocel
+ Object-centric event log
+ """
+ log_obj = log_converter.apply(
+ log_obj, variant=log_converter.Variants.TO_DATA_FRAME
+ )
+
+ if additional_event_attributes is None:
+ additional_event_attributes = {}
+
+ if additional_object_attributes is None:
+ additional_object_attributes = {}
+
+ events = []
+ objects = []
+ relations = []
+
+ obj_ids = set()
+
+ stream = log_obj.to_dict(orient="records")
+ stream = __postprocess_stream(stream)
+
+ for index, eve in enumerate(stream):
+ ocel_eve = {
+ ocel_constants.DEFAULT_EVENT_ID: str(index),
+ ocel_constants.DEFAULT_EVENT_ACTIVITY: eve[activity_column],
+ ocel_constants.DEFAULT_EVENT_TIMESTAMP: eve[timestamp_column],
+ }
+ for attr in additional_event_attributes:
+ if attr in eve:
+ ocel_eve[attr] = eve[attr]
+ events.append(ocel_eve)
+
+ for ot in obj_types:
+ try:
+ objs = eve[ot].split(obj_separator)
+
+ for obj in objs:
+ if len(obj.strip()) > 0:
+ if obj not in obj_ids:
+ obj_ids.add(obj)
+ obj_instance = {
+ ocel_constants.DEFAULT_OBJECT_ID: obj,
+ ocel_constants.DEFAULT_OBJECT_TYPE: ot,
+ }
+
+ if ot in additional_object_attributes:
+ for objattname in additional_object_attributes[
+ ot
+ ]:
+ if objattname in eve:
+ objattvalue = eve[objattname]
+ obj_instance[objattname] = objattvalue
+
+ objects.append(obj_instance)
+
+ rel = copy(ocel_eve)
+ rel[ocel_constants.DEFAULT_OBJECT_ID] = obj
+ rel[ocel_constants.DEFAULT_OBJECT_TYPE] = ot
+
+ relations.append(rel)
+ except BaseException:
+ pass
+
+ events = pandas_utils.instantiate_dataframe(events)
+ objects = pandas_utils.instantiate_dataframe(objects)
+ relations = pandas_utils.instantiate_dataframe(relations)
+ relations = relations.drop_duplicates(
+ subset=[
+ ocel_constants.DEFAULT_EVENT_ID,
+ ocel_constants.DEFAULT_OBJECT_ID,
+ ]
+ )
+
+ ocel = OCEL(events=events, objects=objects, relations=relations)
+ ocel = ocel_consistency.apply(ocel)
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/names_stripping.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/names_stripping.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b590e6656f4a8172e60667e053ce6cfda76d07c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/names_stripping.py
@@ -0,0 +1,39 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import re
+
+
+match = re.compile(r"[^0-9a-zA-Z]+")
+
+
+def apply(X: str, max_len: int = 100) -> str:
+ X = X.split(" ")
+ i = 0
+ while i < len(X):
+ X[i] = X[i].capitalize()
+ i = i + 1
+ X = "".join(X)
+ stru = match.sub("", X).strip()
+ if len(stru) > max_len:
+ stru = stru[:100]
+ return stru
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/objects_per_type_per_activity.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/objects_per_type_per_activity.py
new file mode 100644
index 0000000000000000000000000000000000000000..385387858786d94322f8e242b45d9a25a2f46c5b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/objects_per_type_per_activity.py
@@ -0,0 +1,107 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import exec_utils, pandas_utils
+from enum import Enum
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from pm4py.objects.ocel import constants as ocel_constants
+
+
+class Parameters(Enum):
+ EVENT_ID = ocel_constants.PARAM_EVENT_ID
+ EVENT_ACTIVITY = ocel_constants.PARAM_EVENT_ACTIVITY
+ OBJECT_ID = ocel_constants.PARAM_OBJECT_ID
+ OBJECT_TYPE = ocel_constants.PARAM_OBJECT_TYPE
+
+
+def apply(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> Dict[str, Dict[str, float]]:
+ """
+ Provided statistics (mean, median, min, max) on the number of objects of a given type that are associated to events
+ of a given activity.
+
+ Parameters
+ ---------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => the event identifier
+ - Parameters.EVENT_ACTIVITY => the activity
+ - Parameters.OBJECT_ID => the object identifier
+ - Parameters.OBJECT_TYPE => the object type
+
+ Returns
+ ---------------
+ dictio
+ Dictionary in which the first key is the activity, the second key is the object type,
+ and the value is a dictionary containing the statistic for the given activity and object type.
+ """
+ if parameters is None:
+ parameters = {}
+
+ from statistics import mean, median
+
+ event_id = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ event_activity = exec_utils.get_param_value(
+ Parameters.EVENT_ACTIVITY, parameters, ocel.event_activity
+ )
+ object_id = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ object_type = exec_utils.get_param_value(
+ Parameters.OBJECT_TYPE, parameters, ocel.object_type_column
+ )
+
+ activities = pandas_utils.format_unique(
+ ocel.events[event_activity].unique()
+ )
+ object_types = pandas_utils.format_unique(
+ ocel.objects[object_type].unique()
+ )
+
+ ret = {}
+
+ for act in activities:
+ if act not in ret:
+ ret[act] = {}
+ df = ocel.relations[ocel.relations[event_activity] == act]
+ for ot in object_types:
+ all_counts = list(
+ df[df[object_type] == ot]
+ .groupby(event_id)[object_id]
+ .agg("count")
+ .to_dict()
+ .values()
+ )
+ if all_counts:
+ ret[act][ot] = {
+ "min": min(all_counts),
+ "max": max(all_counts),
+ "mean": mean(all_counts),
+ "median": median(all_counts),
+ }
+
+ return ret
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_consistency.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_consistency.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a94f4270d8a9daeb4a337f847d1357470da75d3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_consistency.py
@@ -0,0 +1,128 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+import warnings
+from pm4py.util import pandas_utils
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Forces the consistency of the OCEL, ensuring that the event/object identifier,
+ event/object type are of type string and non-empty.
+
+ Parameters
+ --------------
+ ocel
+ OCEL
+ parameters
+ Possible parameters of the method
+
+ Returns
+ --------------
+ ocel
+ Consistent OCEL
+ """
+ if parameters is None:
+ parameters = {}
+
+ # Store frequently accessed column names locally to reduce attribute lookups
+ event_id_col = ocel.event_id_column
+ object_id_col = ocel.object_id_column
+ event_activity = ocel.event_activity
+ object_type_col = ocel.object_type_column
+ qualifier_col = ocel.qualifier
+
+ # Define fields to process for each dataframe
+ fields = {
+ "events": [event_id_col, event_activity],
+ "objects": [object_id_col, object_type_col],
+ "relations": [event_id_col, object_id_col, event_activity, object_type_col],
+ "o2o": [object_id_col, object_id_col + "_2"],
+ "e2e": [event_id_col, event_id_col + "_2"],
+ "object_changes": [object_id_col],
+ }
+
+ # Process each dataframe
+ for tab, columns in fields.items():
+ # Skip processing if attribute doesn't exist
+ if not hasattr(ocel, tab):
+ continue
+
+ # Get dataframe
+ df = getattr(ocel, tab)
+
+ # Skip empty dataframes
+ if df.empty:
+ continue
+
+ # Filter to only columns that exist in this dataframe
+ valid_columns = [col for col in columns if col in df.columns]
+ if not valid_columns:
+ continue
+
+ # Check for NA values - only create mask if needed
+ has_na = df[valid_columns].isna().any().any()
+ if has_na:
+ # Create mask for rows without NA values
+ valid_rows = ~df[valid_columns].isna().any(axis=1)
+ df = df.loc[valid_rows]
+
+ df = df.copy()
+
+ # Convert columns to string type
+ for col in valid_columns:
+ df[col] = df[col].astype(str)
+
+ # Efficiently filter out empty strings
+ # Create a single mask for all columns and apply once
+ valid_rows = pandas_utils.DATAFRAME.Series(True, index=df.index)
+ for col in valid_columns:
+ valid_rows &= (df[col].str.len() > 0)
+
+ # Only filter if we found empty strings
+ if not valid_rows.all():
+ df = df.loc[valid_rows]
+
+ # Update OCEL attribute
+ setattr(ocel, tab, df)
+
+ # Check uniqueness efficiently
+ events_df = ocel.events
+ objects_df = ocel.objects
+
+ # Only check if there are rows to check
+ if len(events_df) > 0:
+ num_ev_ids = events_df[event_id_col].nunique()
+ if num_ev_ids < len(events_df):
+ warnings.warn("The event identifiers in the OCEL are not unique!")
+
+ if len(objects_df) > 0:
+ num_obj_ids = objects_df[object_id_col].nunique()
+ if num_obj_ids < len(objects_df):
+ warnings.warn("The object identifiers in the OCEL are not unique!")
+
+ ocel.relations[qualifier_col] = ocel.relations[qualifier_col].fillna("")
+ ocel.o2o[qualifier_col] = ocel.o2o[qualifier_col].fillna("")
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_iterator.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_iterator.py
new file mode 100644
index 0000000000000000000000000000000000000000..0957789e798373e65bd284f0e36c27d8e1da5b2f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_iterator.py
@@ -0,0 +1,67 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+from enum import Enum
+from pm4py.util import exec_utils
+from pm4py.objects.ocel import constants as ocel_constants
+import pandas as pd
+
+
+class Parameters(Enum):
+ OCEL_TYPE_PREFIX = ocel_constants.PARAM_OBJECT_TYPE_PREFIX_EXTENDED
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None):
+ """
+ Creates an iterator over the events of an object-centric event log
+
+ Parameters
+ ----------------
+ ocel
+ OCEL
+ parameters
+ Parameters of the method, including:
+ - Parameters.OCEL_TYPE_PREFIX => the prefix of the object types in the OCEL (default: ocel:type)
+
+ Returns
+ ----------------
+ yielded event
+ The events of the OCEL, one by one.
+ """
+ if parameters is None:
+ parameters = {}
+
+ ot_prefix = exec_utils.get_param_value(
+ Parameters.OCEL_TYPE_PREFIX,
+ parameters,
+ ocel_constants.DEFAULT_OBJECT_TYPE_PREFIX_EXTENDED,
+ )
+
+ ext_table = ocel.get_extended_table(ot_prefix)
+
+ for k, ev in ext_table.iterrows():
+ yield {
+ x: y
+ for x, y in dict(ev).items()
+ if isinstance(y, list) or not pd.isna(y)
+ }
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_to_dict_types_rel.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_to_dict_types_rel.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f0254e1000681d4a5706096ffd6420bd4c8fb6a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_to_dict_types_rel.py
@@ -0,0 +1,157 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Dict, Union, Tuple
+import pandas as pd
+from pm4py.util import pandas_utils
+
+
+def apply(
+ ocel: OCEL,
+) -> Dict[str, Dict[Union[str, Tuple[str, str]], pd.DataFrame]]:
+ r"""Gets from an object-centric event log (OCEL) a dictionary associating to
+ every event/object/e2o/o2o/change type a dataframe containing the
+ associated information. This effectively splits the information of
+ different event/object types in dense dataframes.
+
+ Running example::
+
+ import pm4py
+ from pm4py.objects.ocel.util import ocel_to_dict_types_rel
+
+
+ ocel = pm4py.read_ocel("tests/input_data/ocel/example_log.jsonocel")
+ dct_types_rel = ocel_to_dict_types_rel.apply(ocel)
+
+ # prints the dense dataframes for every event type of the log
+ for evt, table in dct_types_rel["ev_types"].items():
+ print("\n")
+ print(evt)
+ print(table)
+
+ Parameters
+ ----------
+ ocel : OCEL
+ Object-centric event log.
+
+ Returns
+ -------
+ dct_types_rel : dict
+ Dictionary associating to every type the corresponding dense table.
+
+ Keys at the first level:
+
+ - ev_types: pointing to the different event types of the object-centric event log
+ - obj_types: pointing to the different object types of the object-centric event log
+ - e2o: pointing to the different event-object relationships of the object-centric event log
+ - o2o: pointing to the different object-object relationships of the object-centric event log
+ - object_changes: pointing to temporal changes in the attributes of the different object types of an OCEL
+
+ Keys at the second level:
+
+ - for "ev_types", "obj_types" and "object_changes": the name of the event/object type related to the dense table.
+ - for "e2o": a tuple in which the first element is an event type, and the second element is an object type.
+ - for "o2o": a tuple in which the two elements are interconnected object types.
+
+ Value: a Pandas dataframe (dense table).
+ """
+ ev_types_list = pandas_utils.format_unique(
+ ocel.events[ocel.event_activity].unique()
+ )
+ obj_types_list = pandas_utils.format_unique(
+ ocel.objects[ocel.object_type_column].unique()
+ )
+ e2o_list = list(
+ ocel.relations.groupby([ocel.event_activity, ocel.object_type_column])
+ .size()
+ .to_dict()
+ )
+
+ obj_type_map = ocel.objects[
+ [ocel.object_id_column, ocel.object_type_column]
+ ].to_dict(orient="records")
+ obj_type_map = {
+ x[ocel.object_id_column]: x[ocel.object_type_column]
+ for x in obj_type_map
+ }
+ overall_o2o = ocel.o2o.copy()
+ overall_o2o[ocel.object_type_column] = overall_o2o[
+ ocel.object_id_column
+ ].map(obj_type_map)
+ overall_o2o[ocel.object_type_column + "_2"] = overall_o2o[
+ ocel.object_id_column + "_2"
+ ].map(obj_type_map)
+
+ o2o_list = list(
+ overall_o2o.groupby(
+ [ocel.object_type_column, ocel.object_type_column + "_2"]
+ )
+ .size()
+ .to_dict()
+ )
+ changes_list = pandas_utils.format_unique(
+ ocel.object_changes[ocel.object_type_column].unique()
+ )
+
+ dct_types_rel = {
+ "ev_types": {},
+ "obj_types": {},
+ "e2o": {},
+ "o2o": {},
+ "changes": {},
+ }
+
+ for evt in ev_types_list:
+ events = ocel.events[ocel.events[ocel.event_activity] == evt]
+ events = events.dropna(axis="columns", how="all")
+ dct_types_rel["ev_types"][evt] = events
+
+ for objt in obj_types_list:
+ objects = ocel.objects[ocel.objects[ocel.object_type_column] == objt]
+ objects = objects.dropna(axis="columns", how="all")
+ dct_types_rel["obj_types"][objt] = objects
+
+ for e2ot in e2o_list:
+ e2o = ocel.relations[
+ (ocel.relations[ocel.event_activity] == e2ot[0])
+ & (ocel.relations[ocel.object_type_column] == e2ot[1])
+ ]
+ e2o = e2o.dropna(axis="columns", how="all")
+ dct_types_rel["e2o"][e2ot] = e2o
+
+ for o2ot in o2o_list:
+ o2o = overall_o2o[
+ (overall_o2o[ocel.object_type_column] == o2ot[0])
+ & (overall_o2o[ocel.object_type_column + "_2"] == o2ot[1])
+ ]
+ o2o = o2o.dropna(axis="columns", how="all")
+ dct_types_rel["o2o"][o2ot] = o2o
+
+ for objt in changes_list:
+ objects = ocel.object_changes[
+ ocel.object_changes[ocel.object_type_column] == objt
+ ]
+ objects = objects.dropna(axis="columns", how="all")
+ dct_types_rel["changes"][objt] = objects
+
+ return dct_types_rel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_type_renaming.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_type_renaming.py
new file mode 100644
index 0000000000000000000000000000000000000000..873d2c4d13732588dc78d5b1ed45839d415bb988
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/ocel_type_renaming.py
@@ -0,0 +1,113 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel.util import names_stripping
+from copy import deepcopy
+from typing import Dict, Optional
+
+
+def __rename_types_from_maps(
+ ocel: OCEL,
+ event_types_map: Optional[Dict[str, str]],
+ object_types_map: Optional[Dict[str, str]],
+) -> OCEL:
+ ret_ocel = deepcopy(ocel)
+
+ if event_types_map is not None:
+ ret_ocel.events[ocel.event_activity] = ret_ocel.events[
+ ocel.event_activity
+ ].map(event_types_map)
+ ret_ocel.relations[ocel.event_activity] = ret_ocel.relations[
+ ocel.event_activity
+ ].map(event_types_map)
+
+ if object_types_map is not None:
+ ret_ocel.objects[ocel.object_type_column] = ret_ocel.objects[
+ ocel.object_type_column
+ ].map(object_types_map)
+ ret_ocel.relations[ocel.object_type_column] = ret_ocel.relations[
+ ocel.object_type_column
+ ].map(object_types_map)
+ ret_ocel.object_changes[ocel.object_type_column] = (
+ ret_ocel.object_changes[ocel.object_type_column].map(
+ object_types_map
+ )
+ )
+
+ return ret_ocel
+
+
+def remove_spaces_non_alphanumeric_characters_from_types(ocel: OCEL) -> OCEL:
+ """
+ Creates a copy of the object-centric event log in which
+ spaces and non-alphanumeric characters inside the event/object types are stripped
+
+ Parameters
+ ----------------
+ ocel
+ Object-centric event log
+
+ Returns
+ ----------------
+ ocel
+ Object-centric event log with stripped types
+ """
+ object_types = (
+ ocel.objects[ocel.object_type_column].value_counts().to_dict()
+ )
+ event_types = ocel.events[ocel.event_activity].value_counts().to_dict()
+
+ object_types_map = {x: names_stripping.apply(x) for x in object_types}
+ event_types_map = {x: names_stripping.apply(x) for x in event_types}
+
+ return __rename_types_from_maps(ocel, event_types_map, object_types_map)
+
+
+def abbreviate_event_types(ocel: OCEL) -> OCEL:
+ """
+ Creates a copy of the object-centric event log in which
+ the event types are replaced by the letters of the alphabet (A being the most frequent event type, ...).
+ This is particularly useful to textually abstract the object-centric event log.
+
+ Parameters
+ ----------------
+ ocel
+ Object-centric event log
+
+ Returns
+ ----------------
+ ocel
+ Object-centric event log with alphabetical event types
+ """
+ event_types = list(
+ ocel.events[ocel.event_activity].value_counts().to_dict()
+ )
+
+ event_types_map = {}
+ for index, act in enumerate(event_types):
+ result = ""
+ while index >= 0:
+ result = chr((index % 26) + ord("A")) + result
+ index = index // 26 - 1
+ event_types_map[act] = result
+
+ return __rename_types_from_maps(ocel, event_types_map, None)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/parent_children_ref.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/parent_children_ref.py
new file mode 100644
index 0000000000000000000000000000000000000000..b51b5457ded41aacdc414881447bb0e6dc07f704
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/parent_children_ref.py
@@ -0,0 +1,85 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+
+
+def apply(
+ ocel: OCEL,
+ child_obj_type: str,
+ parent_obj_type: str,
+ parameters: Optional[Dict[Any, Any]] = None,
+) -> OCEL:
+ """
+ Inserts an object attribute pointing to the parent of a child object,
+ by looking at the related objects of the events of the log.
+ This requires only the provision of the child object type and of the parent object type.
+
+ Parameters
+ --------------
+ ocel
+ Object-centric event log
+ child_obj_type
+ Child object type (e.g. item)
+ parent_obj_type
+ Parent object type (e.g. parent)
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ -------------
+ ocel
+ Enriched object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ ev_lf = (
+ ocel.relations.groupby(ocel.event_id_column)[ocel.object_id_column]
+ .agg(list)
+ .to_dict()
+ )
+ obj_types = ocel.objects[
+ [ocel.object_id_column, ocel.object_type_column]
+ ].to_dict(orient="records")
+ obj_types = {
+ x[ocel.object_id_column]: x[ocel.object_type_column] for x in obj_types
+ }
+ parents = {}
+
+ for ev_id, lif in ev_lf.items():
+ for obj_id in lif:
+ if obj_types[obj_id] == child_obj_type:
+ for obj_id_2 in lif:
+ if obj_types[obj_id_2] == parent_obj_type:
+ parents[obj_id] = obj_id_2
+
+ col = ocel.objects[ocel.object_id_column].map(parents)
+ if parent_obj_type + "ID" not in ocel.objects.columns:
+ ocel.objects[parent_obj_type + "ID"] = col
+ else:
+ ocel.objects[parent_obj_type + "ID"] = ocel.objects[
+ parent_obj_type + "ID"
+ ].fillna(col)
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/related_events.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/related_events.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8a6156a6fd7448d0b1912153b1656cd21f4ff21
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/related_events.py
@@ -0,0 +1,45 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Dict, Any, Optional, List
+
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import pandas_utils
+
+
+def related_events_dct(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> Dict[str, Dict[str, List[str]]]:
+ if parameters is None:
+ parameters = {}
+
+ object_types = pandas_utils.format_unique(
+ ocel.relations[ocel.object_type_column].unique()
+ )
+ dct = {}
+ for ot in object_types:
+ dct[ot] = (
+ ocel.relations[ocel.relations[ocel.object_type_column] == ot]
+ .groupby(ocel.object_id_column)[ocel.event_id_column]
+ .apply(list)
+ .to_dict()
+ )
+ return dct
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/related_objects.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/related_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..77ac14330cd78e2861304809d80717dcf80659ed
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/related_objects.py
@@ -0,0 +1,67 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Dict, Any, Optional, List
+
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import pandas_utils
+
+
+def related_objects_dct_per_type(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> Dict[str, Dict[str, List[str]]]:
+ if parameters is None:
+ parameters = {}
+
+ object_types = pandas_utils.format_unique(
+ ocel.relations[ocel.object_type_column].unique()
+ )
+ dct = {}
+ for ot in object_types:
+ dct[ot] = (
+ ocel.relations[ocel.relations[ocel.object_type_column] == ot]
+ .groupby(ocel.event_id_column)[ocel.object_id_column]
+ .apply(list)
+ .to_dict()
+ )
+ return dct
+
+
+def related_objects_dct_overall(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> Dict[str, List[str]]:
+ if parameters is None:
+ parameters = {}
+
+ evids = pandas_utils.format_unique(
+ ocel.events[ocel.event_id_column].unique()
+ )
+ dct = (
+ ocel.relations.groupby(ocel.event_id_column)[ocel.object_id_column]
+ .agg(list)
+ .to_dict()
+ )
+
+ for evid in evids:
+ if evid not in dct:
+ dct[evid] = []
+
+ return dct
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/rename_objs_ot_tim_lex.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/rename_objs_ot_tim_lex.py
new file mode 100644
index 0000000000000000000000000000000000000000..90962c9503624976fed889b5c1f0221d8be270ac
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/rename_objs_ot_tim_lex.py
@@ -0,0 +1,119 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from typing import Optional, Dict, Any
+
+from copy import deepcopy
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.util import exec_utils
+
+
+class Parameters(Enum):
+ EXCLUDE_OBJECT_TYPES = "exclude_object_types"
+
+
+def apply(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
+ """
+ Rename objects given their object type, lifecycle start/end timestamps, and lexicographic order,
+
+ Parameters
+ -----------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EXCLUDE_OBJECT_TYPES => set/list of object types to exclude from renaming
+
+ Returns
+ ----------------
+ renamed_ocel
+ Object-centric event log with renaming
+ """
+ if parameters is None:
+ parameters = {}
+
+ exclude_object_types = exec_utils.get_param_value(
+ Parameters.EXCLUDE_OBJECT_TYPES, parameters, set()
+ )
+ # normalize to a Python set for fast membership checks
+ try:
+ exclude_object_types = set(exclude_object_types)
+ except Exception:
+ exclude_object_types = set()
+
+ objects_start = (
+ ocel.relations.groupby(ocel.object_id_column)[ocel.event_timestamp]
+ .first()
+ .to_dict()
+ )
+ objects_end = (
+ ocel.relations.groupby(ocel.object_id_column)[ocel.event_timestamp]
+ .last()
+ .to_dict()
+ )
+ objects_ot0 = ocel.objects[
+ [ocel.object_id_column, ocel.object_type_column]
+ ].to_dict(orient="records")
+ objects_ot0 = [
+ (x[ocel.object_id_column], x[ocel.object_type_column])
+ for x in objects_ot0
+ ]
+ objects_ot1 = {}
+
+ for el in objects_ot0:
+ if el[1] not in objects_ot1:
+ objects_ot1[el[1]] = []
+ objects_ot1[el[1]].append(el[0])
+
+ overall_objects = {}
+ keys = sorted(list(objects_ot1))
+ for ot in keys:
+ objects = objects_ot1[ot]
+ objects.sort(key=lambda x: (objects_start[x], objects_end[x], x))
+ if ot in exclude_object_types:
+ # skip renaming for this object type
+ continue
+ mapped = {objects[i]: ot + "_" + str(i + 1) for i in range(len(objects))}
+ overall_objects.update(mapped)
+
+ ocel = deepcopy(ocel)
+ # map and keep original IDs for excluded object types
+ oid_col = ocel.object_id_column
+ ocel.objects[oid_col] = ocel.objects[oid_col].map(overall_objects).fillna(
+ ocel.objects[oid_col]
+ )
+ ocel.relations[oid_col] = ocel.relations[oid_col].map(overall_objects).fillna(
+ ocel.relations[oid_col]
+ )
+ if ocel.o2o is not None:
+ ocel.o2o[oid_col] = ocel.o2o[oid_col].map(overall_objects).fillna(
+ ocel.o2o[oid_col]
+ )
+ ocel.o2o[oid_col + "_2"] = ocel.o2o[oid_col + "_2"].map(overall_objects).fillna(
+ ocel.o2o[oid_col + "_2"]
+ )
+ if ocel.object_changes is not None:
+ ocel.object_changes[oid_col] = ocel.object_changes[oid_col].map(
+ overall_objects
+ ).fillna(ocel.object_changes[oid_col])
+
+ return ocel
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/sampling.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f2a9a1268aa11a5ec9d3091498ad8ef49d8b4c7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/util/sampling.py
@@ -0,0 +1,130 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from pm4py.util import exec_utils, pandas_utils
+from pm4py.objects.ocel import constants
+import random
+from pm4py.objects.ocel.util import filtering_utils
+from copy import copy
+from pm4py.objects.ocel.obj import OCEL
+from typing import Optional, Dict, Any
+
+
+class Parameters(Enum):
+ OBJECT_ID = constants.PARAM_OBJECT_ID
+ EVENT_ID = constants.PARAM_EVENT_ID
+ NUM_ENTITIES = "num_entities"
+
+
+def sample_ocel_events(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> OCEL:
+ """
+ Keeps a sample of the events of an object-centric event log
+
+ Parameters
+ ------------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.EVENT_ID => event identifier
+ - Parameters.NUM_ENTITIES => number of events
+
+ Returns
+ ------------------
+ sampled_ocel
+ Sampled object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ event_id_column = exec_utils.get_param_value(
+ Parameters.EVENT_ID, parameters, ocel.event_id_column
+ )
+ num_entities = exec_utils.get_param_value(
+ Parameters.NUM_ENTITIES, parameters, 100
+ )
+
+ events = pandas_utils.format_unique(ocel.events[event_id_column].unique())
+ num_events = min(len(events), num_entities)
+
+ random.shuffle(events)
+ picked_events = events[:num_events]
+
+ ocel = copy(ocel)
+ ocel.events = ocel.events[ocel.events[event_id_column].isin(picked_events)]
+
+ return filtering_utils.propagate_event_filtering(
+ ocel, parameters=parameters
+ )
+
+
+def sample_ocel_objects(
+ ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None
+) -> OCEL:
+ """
+ Random samples the objects of the object-centric event log.
+ Then, only the events related to at least one of these objects are filtered from the event log.
+ As a note, the relationships between the different objects are probably going to be ruined by
+ this sampling.
+
+ Parameters
+ -----------------
+ ocel
+ Object-centric event log
+ parameters
+ Parameters of the algorithm, including:
+ - Parameters.OBJECT_ID => object identifier
+ - Parameters.NUM_ENTITIES => number of objects to retain
+
+ Returns
+ ----------------
+ sampled_ocel
+ Sampled object-centric event log
+ """
+ if parameters is None:
+ parameters = {}
+
+ object_id_column = exec_utils.get_param_value(
+ Parameters.OBJECT_ID, parameters, ocel.object_id_column
+ )
+ num_entities = exec_utils.get_param_value(
+ Parameters.NUM_ENTITIES, parameters, 100
+ )
+
+ objects = pandas_utils.format_unique(
+ ocel.objects[object_id_column].unique()
+ )
+ num_objects = min(len(objects), num_entities)
+
+ random.shuffle(objects)
+ picked_objects = objects[:num_objects]
+
+ ocel = copy(ocel)
+ ocel.objects = ocel.objects[
+ ocel.objects[object_id_column].isin(picked_objects)
+ ]
+
+ return filtering_utils.propagate_object_filtering(
+ ocel, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b54ea5abd3c858e8c14441e624c7abb307fd342e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocel.validation import jsonocel, xmlocel, ocel20_rel_validation
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/jsonocel.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/jsonocel.py
new file mode 100644
index 0000000000000000000000000000000000000000..538039f3dfa4f20c7249209dc691e5b97c6a74a4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/jsonocel.py
@@ -0,0 +1,47 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import importlib.util
+from pm4py.objects.ocel.util import compression
+
+
+def apply(input_path, validation_path, parameters=None):
+ if not importlib.util.find_spec("jsonschema"):
+ raise Exception(
+ "please install jsonschema in order to validate a JSONOCEL file."
+ )
+
+ import json
+ import jsonschema
+ from jsonschema import validate
+
+ if parameters is None:
+ parameters = {}
+
+ with compression.open_text(input_path, "rt", encoding="utf-8") as F:
+ file_content = json.load(F)
+ with open(validation_path, "rb") as F:
+ schema_content = json.load(F)
+ try:
+ validate(instance=file_content, schema=schema_content)
+ return True
+ except jsonschema.exceptions.ValidationError as err:
+ return False
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/ocel20_rel_validation.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/ocel20_rel_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a51955ce77328dde0bd3339efc232fb3bb4f914
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/ocel20_rel_validation.py
@@ -0,0 +1,349 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Tuple, Collection
+
+
+def const_1_existence_type_independent_tables(curs):
+ query = """SELECT Count(*) FROM sqlite_master WHERE type = "table" AND tbl_name IN ("event_map_type", "object_map_type", "event", "object", "event_object", "object_object");"""
+ curs.execute(query)
+ res = curs.fetchone()
+ return res[0] == 6
+
+
+def const_2_existence_object_type_tables_map_obj_types(curs):
+ query = """SELECT Count(*) FROM (SELECT a.ocel_type_map, b.tbl_name FROM (SELECT ocel_type_map FROM object_map_type) a LEFT OUTER JOIN (SELECT tbl_name FROM sqlite_master WHERE type = "table" AND tbl_name LIKE "object_%") b ON b.tbl_name = "object_" || a.ocel_type_map WHERE b.tbl_name IS NULL);"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ query = """SELECT Count(*) FROM (SELECT a.ocel_type_map, b.tbl_name FROM (SELECT tbl_name FROM sqlite_master WHERE type = "table" AND tbl_name LIKE "object_%") b LEFT OUTER JOIN (SELECT ocel_type_map FROM object_map_type) a ON b.tbl_name = "object_" || a.ocel_type_map WHERE a.ocel_type_map IS NULL);"""
+ curs.execute(query)
+ res1 = curs.fetchone()
+
+ return res0[0] == 0 and res1[0] == 2
+
+
+def const_3_existence_event_type_tables_map_ev_types(curs):
+ query = """SELECT Count(*) FROM (SELECT a.ocel_type_map, b.tbl_name FROM (SELECT ocel_type_map FROM event_map_type) a LEFT OUTER JOIN (SELECT tbl_name FROM sqlite_master WHERE type = "table" AND tbl_name LIKE "event_%") b ON b.tbl_name = "event_" || a.ocel_type_map WHERE b.tbl_name IS NULL);"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ query = """SELECT Count(*) FROM (SELECT a.ocel_type_map, b.tbl_name FROM (SELECT tbl_name FROM sqlite_master WHERE type = "table" AND tbl_name LIKE "event_%") b LEFT OUTER JOIN (SELECT ocel_type_map FROM event_map_type) a ON b.tbl_name = "event_" || a.ocel_type_map WHERE a.ocel_type_map IS NULL);"""
+ curs.execute(query)
+ res1 = curs.fetchone()
+
+ return res0[0] == 0 and res1[0] == 2
+
+
+def const_4_ocel_type_column(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.tbl_name IN ("object_map_type", "event_map_type", "event", "object") AND m.type = "table" AND p.name = "ocel_type");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 4
+
+
+def const_5_ocel_type_map(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.tbl_name IN ("object_map_type", "event_map_type") AND m.type = "table" AND p.name = "ocel_type_map");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 2
+
+
+def const_6_ocel_id(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.tbl_name IN ("event", "object") AND m.type = "table" AND p.name = "ocel_id");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 2
+
+
+def const_7_ocel_qualifier(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.tbl_name IN ("event_object", "object_object") AND m.type = "table" AND p.name = "ocel_qualifier");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 2
+
+
+def const_8_event_object_fields(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.tbl_name = "event_object" AND m.type = "table" AND p.name IN ("ocel_event_id", "ocel_object_id"));"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 2
+
+
+def const_9_object_object_fields(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.tbl_name = "object_object" AND m.type = "table" AND p.name IN ("ocel_source_id", "ocel_target_id"));"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 2
+
+
+def const_10_existence_ocel_id_obj_type_spec_tables(curs):
+ query = """SELECT m.tbl_name, Count(*) FROM sqlite_master m JOIN object_map_type ty on m.tbl_name = "object_" || ty.ocel_type_map JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND p.name = "ocel_id" GROUP BY m.tbl_name;"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[1] != 1:
+ ret = False
+ break
+
+ return ret
+
+
+def const_11_existence_ocel_id_ev_type_spec_tables(curs):
+ query = """SELECT m.tbl_name, Count(*) FROM sqlite_master m JOIN event_map_type ty on m.tbl_name = "event_" || ty.ocel_type_map JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND p.name = "ocel_id" GROUP BY m.tbl_name;"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[1] != 1:
+ ret = False
+ break
+
+ return ret
+
+
+def const_12_existence_type_ocel_time_obj_type_spec_tables(curs):
+ query = """SELECT m.tbl_name, Count(*) FROM sqlite_master m JOIN object_map_type ty on m.tbl_name = "object_" || ty.ocel_type_map JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND p.name = "ocel_time" AND p.type = "TIMESTAMP" GROUP BY m.tbl_name;"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[1] != 1:
+ ret = False
+ break
+
+ return ret
+
+
+def const_13_existence_type_ocel_time_ev_type_spec_tables(curs):
+ query = """SELECT m.tbl_name, Count(*) FROM sqlite_master m JOIN event_map_type ty on m.tbl_name = "event_" || ty.ocel_type_map JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND p.name = "ocel_time" AND p.type = "TIMESTAMP" GROUP BY m.tbl_name;"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[1] != 1:
+ ret = False
+ break
+
+ return ret
+
+
+def const_14_primary_key_object_event_map_type_tables(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND m.tbl_name IN ("object_map_type", "event_map_type") AND p.name = "ocel_type" AND p.pk > 0);"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[0] != 2:
+ ret = False
+ break
+
+ return ret
+
+
+def const_15_primary_key_object_event_tables(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND m.tbl_name IN ("object", "event") AND p.name = "ocel_id" AND p.pk > 0);"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[0] != 2:
+ ret = False
+ break
+
+ return ret
+
+
+def const_16_primary_key_event_object_table(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND m.tbl_name = "event_object" AND p.name IN ("ocel_event_id", "ocel_object_id", "ocel_qualifier") AND p.pk > 0);"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[0] != 3:
+ ret = False
+ break
+
+ return ret
+
+
+def const_17_primary_key_object_object_table(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM sqlite_master m JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND m.tbl_name = "object_object" AND p.name IN ("ocel_source_id", "ocel_target_id", "ocel_qualifier") AND p.pk > 0);"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[0] != 3:
+ ret = False
+ break
+
+ return ret
+
+
+def const_18_primary_key_event_type_spec_tables(curs):
+ query = """SELECT m.tbl_name, sum(p.pk) FROM sqlite_master m JOIN event_map_type ty on m.tbl_name = "event_" || ty.ocel_type_map JOIN pragma_table_info(m.tbl_name) p WHERE m.type = "table" AND p.name = "ocel_id" GROUP BY m.tbl_name;"""
+ curs.execute(query)
+ res = curs.fetchall()
+
+ ret = True
+ for el in res:
+ if el[1] != 1:
+ ret = False
+ break
+
+ return ret
+
+
+def const_19_foreign_key_event(curs):
+ query = """SELECT Count(*) FROM (SELECT * from pragma_foreign_key_list("event") p WHERE p."table" = "event_map_type" AND p."from" = "ocel_type" AND p."to" = "ocel_type");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 1
+
+
+def const_20_foreign_key_object(curs):
+ query = """SELECT Count(*) FROM (SELECT * from pragma_foreign_key_list("object") p WHERE p."table" = "object_map_type" AND p."from" = "ocel_type" AND p."to" = "ocel_type");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 1
+
+
+def const_21_foreign_key_event_object(curs):
+ query = """SELECT Count(*) FROM (SELECT * from pragma_foreign_key_list("event_object") p WHERE p."table" = "event" AND p."from" = "ocel_event_id" AND p."to" = "ocel_id");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ query = """SELECT Count(*) FROM (SELECT * from pragma_foreign_key_list("event_object") p WHERE p."table" = "object" AND p."from" = "ocel_object_id" AND p."to" = "ocel_id");"""
+ curs.execute(query)
+ res1 = curs.fetchone()
+
+ return res0[0] == 1 and res1[0] == 1
+
+
+def const_22_foreign_key_object_object(curs):
+ query = """SELECT Count(*) FROM (SELECT * from pragma_foreign_key_list("object_object") p WHERE p."table" = "object" AND p."from" = "ocel_source_id" AND p."to" = "ocel_id");"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ query = """SELECT Count(*) FROM (SELECT * from pragma_foreign_key_list("object_object") p WHERE p."table" = "object" AND p."from" = "ocel_target_id" AND p."to" = "ocel_id");"""
+ curs.execute(query)
+ res1 = curs.fetchone()
+
+ return res0[0] == 1 and res1[0] == 1
+
+
+def const_23_foreign_key_event_type_specific(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM (SELECT tbl_name FROM sqlite_master WHERE type = "table") m JOIN event_map_type ty on m.tbl_name = "event_" || ty.ocel_type_map LEFT OUTER JOIN pragma_foreign_key_list(m.tbl_name) p ON p."table" = "event" AND p."from" = "ocel_id" AND p."to" = "ocel_id" WHERE p."table" IS NULL)"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 0
+
+
+def const_24_foreign_key_object_type_specific(curs):
+ query = """SELECT Count(*) FROM (SELECT m.tbl_name, p.* FROM (SELECT tbl_name FROM sqlite_master WHERE type = "table") m JOIN object_map_type ty on m.tbl_name = "object_" || ty.ocel_type_map LEFT OUTER JOIN pragma_foreign_key_list(m.tbl_name) p ON p."table" = "object" AND p."from" = "ocel_id" AND p."to" = "ocel_id" WHERE p."table" IS NULL)"""
+ curs.execute(query)
+ res0 = curs.fetchone()
+
+ return res0[0] == 0
+
+
+constraints = {
+ "const_1_existence_type_independent_tables": const_1_existence_type_independent_tables,
+ "const_2_existence_object_type_tables_map_obj_types": const_2_existence_object_type_tables_map_obj_types,
+ "const_3_existence_event_type_tables_map_ev_types": const_3_existence_event_type_tables_map_ev_types,
+ "const_4_ocel_type_column": const_4_ocel_type_column,
+ "const_5_ocel_type_map": const_5_ocel_type_map,
+ "const_6_ocel_id": const_6_ocel_id,
+ "const_7_ocel_qualifier": const_7_ocel_qualifier,
+ "const_8_event_object_fields": const_8_event_object_fields,
+ "const_9_object_object_fields": const_9_object_object_fields,
+ "const_10_existence_ocel_id_obj_type_spec_tables": const_10_existence_ocel_id_obj_type_spec_tables,
+ "const_11_existence_ocel_id_ev_type_spec_tables": const_11_existence_ocel_id_ev_type_spec_tables,
+ "const_12_existence_type_ocel_time_obj_type_spec_tables": const_12_existence_type_ocel_time_obj_type_spec_tables,
+ "const_13_existence_type_ocel_time_ev_type_spec_tables": const_13_existence_type_ocel_time_ev_type_spec_tables,
+ "const_14_primary_key_object_event_map_type_tables": const_14_primary_key_object_event_map_type_tables,
+ "const_15_primary_key_object_event_tables": const_15_primary_key_object_event_tables,
+ "const_16_primary_key_event_object_table": const_16_primary_key_event_object_table,
+ "const_17_primary_key_object_object_table": const_17_primary_key_object_object_table,
+ "const_18_primary_key_event_type_spec_tables": const_18_primary_key_event_type_spec_tables,
+ "const_19_foreign_key_event": const_19_foreign_key_event,
+ "const_20_foreign_key_object": const_20_foreign_key_object,
+ "const_21_foreign_key_event_object": const_21_foreign_key_event_object,
+ "const_22_foreign_key_object_object": const_22_foreign_key_object_object,
+ "const_23_foreign_key_event_type_specific": const_23_foreign_key_event_type_specific,
+ "const_24_foreign_key_object_type_specific": const_24_foreign_key_object_type_specific,
+}
+
+
+def apply(file_path: str) -> Tuple[Collection[str], Collection[str]]:
+ """
+ Validates the relational schema of an OCEL 2.0 SQLite database
+
+ Parameters
+ ----------------
+ file_path
+ Path to the OCEL 2.0 SQLite database
+
+ Returns
+ ----------------
+ satisfied
+ List of satisfied constraints
+ unsatisfied
+ List of unsatisfied constraints
+ """
+ import sqlite3
+
+ conn = sqlite3.connect(file_path)
+ curs = conn.cursor()
+
+ satisfied = []
+ unsatisfied = []
+
+ for c in constraints:
+ res = constraints[c](curs)
+ if res:
+ satisfied.append(c)
+ else:
+ unsatisfied.append(c)
+
+ curs.close()
+ conn.close()
+
+ return satisfied, unsatisfied
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/xmlocel.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/xmlocel.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b79ba181b6de23c061d2a2a6f1aeda0d313c9f6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocel/validation/xmlocel.py
@@ -0,0 +1,41 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import importlib.util
+from pm4py.objects.ocel.util import compression
+
+
+def apply(input_path, validation_path, parameters=None):
+ if not importlib.util.find_spec("lxml"):
+ raise Exception(
+ "please install lxml in order to validate an XMLOCEL file."
+ )
+
+ import lxml.etree
+
+ if parameters is None:
+ parameters = {}
+
+ with compression.open_binary(input_path, "rb") as F:
+ xml_file = lxml.etree.parse(F)
+ xml_validator = lxml.etree.XMLSchema(file=validation_path)
+ is_valid = xml_validator.validate(xml_file)
+ return is_valid
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ff116bb21894a552e8e2a51910ae8205cf9011e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.ocpn import obj, converter, factory, semantics, utils
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/converter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..d87ffe8ca78ae96ce672c10516645d20ede87dcb
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/converter.py
@@ -0,0 +1,47 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocpn.variants import to_oc_causal_net, to_alternative_format
+from pm4py.util import exec_utils
+from enum import Enum
+
+class Variants(Enum):
+ TO_OC_CAUSAL_NET = to_oc_causal_net
+ TO_ALTERNATIVE_FORMAT = to_alternative_format
+
+def apply(ocpn, parameters=None, variant=Variants.TO_OC_CAUSAL_NET):
+ """
+ Method for converting an Object-centric Petri Net to Object-centric Causal Net
+
+ Parameters
+ -----------
+ ocpn: OCPetriNet
+ Object-centric Petri net
+ parameters: dict, optional
+ Parameters of the algorithm
+ variant
+ Chosen variant of the algorithm
+
+ Returns
+ -----------
+ Conversion result
+ """
+ return exec_utils.get_variant(variant).apply(ocpn, parameters=parameters)
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/factory.py
new file mode 100644
index 0000000000000000000000000000000000000000..405ae35e0a0582ce18d15b5e75a810476fa79f87
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/factory.py
@@ -0,0 +1,129 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections import Counter
+import uuid
+from pm4py.objects.ocpn.obj import OCMarking, OCPetriNet
+from typing import Dict, Any, Union
+
+from pm4py.objects.petri_net.obj import PetriNet
+
+
+def create(ocpn: Union[Dict[str, Any], OCPetriNet]) -> OCPetriNet:
+ """
+ Creates an Object-centric Petri net object from its dictionary representation
+ specified in pm4py.algo.discovery.ocel.ocpn.variants.classic.
+ Considers the properties `activities`, `petri_nets`, `double_arcs_on_activity`,
+ and, when available, `object_ids`.
+ All other information is ignored.
+
+ Parameters
+ -----------------
+ ocpn
+ Dictionary containing the properties of the Object-centric Petri net
+
+ Returns
+ ----------------
+ OCPetriNet
+ Object-centric Petri net object
+ """
+ if isinstance(ocpn, OCPetriNet):
+ return ocpn
+
+ activities = ocpn["activities"]
+ petri_nets = ocpn["petri_nets"]
+ double_arcs_on_activity = ocpn["double_arcs_on_activity"]
+ object_ids = ocpn.get("object_ids")
+
+ places = dict()
+ unlabeled_transitions = dict()
+ arcs = []
+ initial_marking = OCMarking()
+ final_marking = OCMarking()
+
+ def _get_marking_counter(ot, multiplicity):
+ if multiplicity <= 0:
+ return Counter()
+ if object_ids is None or ot not in object_ids:
+ return Counter([f"{ot}_{i}" for i in range(multiplicity)])
+ return Counter({obj: multiplicity for obj in object_ids[ot]})
+
+ # Labeled transitions
+ labeled_transitions = {label: OCPetriNet.Transition(label=label, name=str(uuid.uuid4())) for label in activities}
+
+ for ot, net in petri_nets.items():
+ pn, im, fm = net
+
+ # transitions
+ for t in pn.transitions:
+ if not t.label:
+ # labeled transitions are already in labeled_transitions
+ name = f"{ot}_{t.name}" # make name unique
+ unlabeled_transitions[name] = OCPetriNet.Transition(name=name)
+
+ # places
+ for p in pn.places:
+ name = f"{ot}_{p.name}" # make name unique
+ places[name] = OCPetriNet.Place(name=name, object_type=ot)
+
+ # arcs
+ for arc in pn.arcs:
+ is_double = False
+ if isinstance(arc.source, PetriNet.Transition):
+ if arc.source.label:
+ source = labeled_transitions[arc.source.label]
+ is_double = double_arcs_on_activity[ot][arc.source.label]
+ else:
+ source = unlabeled_transitions[f"{ot}_{arc.source.name}"]
+ target = places[f"{ot}_{arc.target.name}"]
+ elif isinstance(arc.source, PetriNet.Place):
+ source = places[f"{ot}_{arc.source.name}"]
+ if arc.target.label:
+ target = labeled_transitions[arc.target.label]
+ is_double = double_arcs_on_activity[ot][arc.target.label]
+ else:
+ target = unlabeled_transitions[f"{ot}_{arc.target.name}"]
+ else:
+ raise ValueError("Unknown arc source type")
+
+ # check for double arc
+
+ a = OCPetriNet.Arc(source=source, target=target, object_type=ot, is_variable=is_double)
+ arcs.append(a)
+ source.add_out_arc(a)
+ target.add_in_arc(a)
+
+ # markings
+ for p in im:
+ initial_marking += OCMarking({places[f"{ot}_{p.name}"]: _get_marking_counter(ot, im[p])})
+ for p in fm:
+ final_marking += OCMarking({places[f"{ot}_{p.name}"]: _get_marking_counter(ot, fm[p])})
+
+ # create the OCPetriNet object
+ ocpn_obj = OCPetriNet(
+ places = set(places.values()),
+ transitions = set(labeled_transitions.values()) | set(unlabeled_transitions.values()),
+ arcs = set(arcs),
+ initial_marking=initial_marking,
+ final_marking=final_marking,
+ )
+ ocpn_obj.set_legacy_dict(ocpn)
+ return ocpn_obj
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..85341f7697e78a7537c70afb23400aec30af9c1d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/obj.py
@@ -0,0 +1,476 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections.abc import Mapping
+from collections import Counter, defaultdict
+from copy import deepcopy
+from typing import Collection, Dict, Any, Set
+from pm4py.objects.petri_net.obj import PetriNet
+
+
+class OCMarking(defaultdict):
+ """
+ An object-centric marking represented as a mapping from places to multisets of object IDs.
+
+ ```
+ marking = OCMarking({p: Counter(["object1", "object2"])})
+ ```
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """Initializes the OCMarking, querying unspecified places defaults to an empty multiset."""
+ super().__init__(Counter)
+ data_args = args
+ if args and args[0] is Counter:
+ data_args = args[1:]
+ initial_data = dict(*data_args, **kwargs)
+ for place, objects in initial_data.items():
+ self[place] = Counter(objects)
+
+ def __hash__(self):
+ return frozenset(
+ (place, frozenset(counter.items()))
+ for place, counter in self.items()
+ if counter
+ ).__hash__()
+
+ def __eq__(self, other):
+ if not isinstance(other, OCMarking):
+ return False
+ return all(
+ self.get(p, Counter()) == other.get(p, Counter())
+ for p in set(self.keys()) | set(other.keys())
+ )
+
+ def __le__(self, other):
+ for place, self_counter in self.items():
+ other_counter = other.get(place, Counter())
+ # Every object count in self must be less than or equal to the count in other.
+ if not all(
+ other_counter.get(obj_id, 0) >= count
+ for obj_id, count in self_counter.items()
+ ):
+ return False
+ return True
+
+ def __add__(self, other):
+ result = OCMarking()
+ for place, self_counter in self.items():
+ result[place] += self_counter
+ for place, other_counter in other.items():
+ result[place] += other_counter
+ return result
+
+ def __sub__(self, other):
+ result = OCMarking()
+ for place, self_counter in self.items():
+ diff = self_counter - other.get(place, Counter())
+ if diff != Counter():
+ result[place] = diff
+ return result
+
+ def __repr__(self):
+ # e.g. ["p1:{o1, o2}", "p2: {o2, o3}", …]
+ sorted_entries = sorted(self.items(), key=lambda item: item[0].name)
+ return (
+ ", ".join(f"{place.name}: {objects}" for (place, objects) in sorted_entries)
+ if sorted_entries
+ else "[]"
+ )
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __deepcopy__(self, memodict={}):
+ new_marking = OCMarking()
+ memodict[id(self)] = new_marking
+ for place, objects in self.items():
+ place_copy = (
+ memodict[id(place)]
+ if id(place) in memodict
+ else deepcopy(place, memodict)
+ )
+ counter_copy = (
+ memodict[id(objects)]
+ if id(objects) in memodict
+ else deepcopy(objects, memodict)
+ )
+ new_marking[place_copy] = counter_copy
+ return new_marking
+
+ @property
+ def places(self) -> Set:
+ """
+ Returns the set of all places in the marking that contain tokens.
+
+ Returns
+ ------------
+ Set[str]
+ Set of place names in the marking.
+ """
+ return set([p for p in self.keys() if self[p]])
+
+
+class OCPetriNet(PetriNet, Mapping):
+ class Place(PetriNet.Place):
+ def __init__(
+ self, name, object_type, in_arcs=None, out_arcs=None, properties=None
+ ):
+ """
+ Constructor
+
+ Parameters
+ ------------
+ name
+ human-readable identifier
+ object_type
+ the type/color of objects this place holds
+ in_arcs
+ set of incoming arcs
+ out_arcs
+ set of outgoing arcs
+ properties
+ dict of additional properties
+ """
+ super().__init__(
+ name, in_arcs=in_arcs, out_arcs=out_arcs, properties=properties
+ )
+ self.__object_type = object_type
+
+ def add_in_arc(self, arc):
+ """
+ Adds an incoming arc to the place.
+
+ Parameters
+ ------------
+ arc: OCPetriNet.Arc
+ the arc to add
+ """
+ self.__in_arcs.add(arc)
+ assert arc.target == self
+ assert arc.object_type == self.object_type
+
+ def add_out_arc(self, arc):
+ """
+ Adds an outgoing arc to the place.
+
+ Parameters
+ ------------
+ arc: OCPetriNet.Arc
+ the arc to add
+ """
+ self.__out_arcs.add(arc)
+ assert arc.source == self
+ assert arc.object_type == self.object_type
+
+ def __get_object_type(self):
+ return self.__object_type
+
+ def __repr__(self):
+ return f"{self.name}[{self.object_type}]"
+
+ def __deepcopy__(self, memodict={}):
+ if id(self) in memodict:
+ return memodict[id(self)]
+ new_place = OCPetriNet.Place(
+ self.name, self.object_type, properties=self.properties
+ )
+ memodict[id(self)] = new_place
+ # attached arcs
+ for arc in self.in_arcs:
+ arc_copy = deepcopy(arc, memodict)
+ new_place.in_arcs.add(arc_copy)
+ for arc in self.out_arcs:
+ arc_copy = deepcopy(arc, memodict)
+ new_place.out_arcs.add(arc_copy)
+
+ return new_place
+
+ object_type = property(__get_object_type)
+
+ class Transition(PetriNet.Transition):
+ def add_in_arc(self, arc):
+ """
+ Adds an incoming arc to the place.
+
+ Parameters
+ ------------
+ arc: OCPetriNet.Arc
+ the arc to add
+ """
+ self.__in_arcs.add(arc)
+ assert arc.target == self
+
+ def add_out_arc(self, arc):
+ """
+ Adds an outgoing arc to the place.
+
+ Parameters
+ ------------
+ arc: OCPetriNet.Arc
+ the arc to add
+ """
+ self.__out_arcs.add(arc)
+ assert arc.source == self
+
+
+ class Arc(PetriNet.Arc):
+ def __init__(
+ self,
+ source,
+ target,
+ object_type,
+ is_variable=False,
+ properties=None,
+ ):
+ """
+ Constructor
+
+ Parameters
+ ------------
+ source
+ source place / transition
+ target
+ target place / transition
+ is_variable
+ whether the arc is a variable arc
+ properties
+ dict of additional properties
+ """
+ super().__init__(source, target, weight=1, properties=properties)
+ self.__object_type = object_type
+ self.__is_variable = is_variable
+
+ def __get_object_type(self):
+ return self.__object_type
+
+ def __get_is_variable(self):
+ return self.__is_variable
+
+ def __repr__(self):
+ base = super().__repr__()
+ var = "variable" if self.is_variable else "non-variable"
+ return f"{base}:{self.object_type}:{var}"
+
+ def __deepcopy__(self, memodict={}):
+ if id(self) in memodict:
+ return memodict[id(self)]
+ new_source = memodict.get(id(self.source), deepcopy(self.source, memodict))
+ new_target = memodict.get(id(self.target), deepcopy(self.target, memodict))
+ new_arc = OCPetriNet.Arc(
+ new_source,
+ new_target,
+ self.object_type,
+ is_variable=self.is_variable,
+ properties=self.properties,
+ )
+ memodict[id(self)] = new_arc
+ # reattach
+ new_source.out_arcs.add(new_arc)
+ new_target.in_arcs.add(new_arc)
+ return new_arc
+
+ object_type = property(__get_object_type)
+ is_variable = property(__get_is_variable)
+
+ def __init__(
+ self,
+ name: str = None,
+ places: Collection[Place] = None,
+ transitions: Collection[Transition] = None,
+ arcs: Collection[Arc] = None,
+ initial_marking: OCMarking = None,
+ final_marking: OCMarking = None,
+ properties: Dict[str, Any] = None,
+ ):
+ """
+ Constructor
+
+ Parameters
+ ------------
+ name
+ human-readable identifier
+ places
+ collection of places
+ transitions
+ collection of transitions
+ arcs
+ collection of arcs
+ initial_marking
+ initial marking of the net
+ final_marking
+ final marking of the net
+ properties
+ dict of additional properties
+ """
+ super().__init__(
+ name=name,
+ places=places,
+ transitions=transitions,
+ arcs=arcs,
+ properties=properties,
+ )
+ self.__initial_marking = initial_marking
+ self.__final_marking = final_marking
+ self.__legacy_dict = None
+ self.__assert_well_formed()
+
+ def __get_initial_marking(self):
+ return self.__initial_marking
+
+ def __get_final_marking(self):
+ return self.__final_marking
+
+ def __deepcopy__(self, memodict={}):
+ new_net = OCPetriNet(self.name)
+ memodict[id(self)] = new_net
+ for p in self.places:
+ p_copy = OCPetriNet.Place(p.name, p.object_type, properties=p.properties)
+ new_net.places.add(p_copy)
+ memodict[id(p)] = p_copy
+ for t in self.transitions:
+ t_copy = OCPetriNet.Transition(t.name, t.label, properties=t.properties)
+ new_net.transitions.add(t_copy)
+ memodict[id(t)] = t_copy
+ for a in self.arcs:
+ src = memodict[id(a.source)]
+ tgt = memodict[id(a.target)]
+ a_copy = OCPetriNet.Arc(
+ src,
+ tgt,
+ a.object_type,
+ is_variable=a.is_variable,
+ properties=a.properties,
+ )
+ src.out_arcs.add(a_copy)
+ tgt.in_arcs.add(a_copy)
+ new_net.arcs.add(a_copy)
+ memodict[id(a)] = a_copy
+
+ def copy_marking(marking):
+ if marking is None:
+ return None
+ copied_marking = OCMarking()
+ for place, objects in marking.items():
+ place_copy = memodict.get(id(place))
+ if place_copy is None:
+ place_copy = OCPetriNet.Place(
+ place.name, place.object_type, properties=place.properties
+ )
+ memodict[id(place)] = place_copy
+ new_net.places.add(place_copy)
+ copied_marking[place_copy] = objects.copy()
+ return copied_marking
+
+ new_net._OCPetriNet__initial_marking = copy_marking(self.initial_marking)
+ new_net._OCPetriNet__final_marking = copy_marking(self.final_marking)
+ if self.__legacy_dict is not None:
+ new_net._OCPetriNet__legacy_dict = deepcopy(
+ self.__legacy_dict, memodict
+ )
+ return new_net
+
+ def __repr__(self):
+ ret = [f"OCPN {self.name}:\nobject_types: ["]
+ object_types_rep = []
+ for ot in self.object_types:
+ object_types_rep.append(ot)
+ object_types_rep.sort()
+ ret.append(" " + ", ".join(object_types_rep) + " ")
+ ret.append("]\nplaces: [")
+ places_rep = []
+ for place in self.places:
+ places_rep.append(repr(place))
+ places_rep.sort()
+ ret.append(" " + ", ".join(places_rep) + " ")
+ ret.append("]\ntransitions: [")
+ trans_rep = []
+ for trans in self.transitions:
+ trans_rep.append(repr(trans))
+ trans_rep.sort()
+ ret.append(" " + ", ".join(trans_rep) + " ")
+ ret.append("]\narcs: [")
+ arcs_rep = []
+ for arc in self.arcs:
+ arcs_rep.append(repr(arc))
+ arcs_rep.sort()
+ ret.append(" " + ", ".join(arcs_rep) + " ")
+ ret.append("]\ninitial_marking: [")
+ initial_marking_rep = [repr(self.initial_marking)]
+ ret.append(" " + ", ".join(initial_marking_rep) + " ")
+ ret.append("]\nfinal_marking: [")
+ final_marking_rep = [repr(self.final_marking)]
+ ret.append(" " + ", ".join(final_marking_rep) + " ")
+ ret.append("]")
+ return "".join(ret)
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __assert_well_formed(self):
+ """
+ Asserts that the OCPN is well-formed, i.e., all transitions have,
+ for each object type, only either variable or non-variable arcs, but not both.
+ """
+ for t in self.transitions:
+ for ot in self.object_types:
+ var_arcs = {
+ a for a in t.in_arcs if a.is_variable and a.object_type == ot
+ }
+ non_var_arcs = {
+ a for a in t.in_arcs if not a.is_variable and a.object_type == ot
+ }
+ if var_arcs and non_var_arcs:
+ raise ValueError(f"Transition {t} is not well-formed.")
+
+ initial_marking = property(__get_initial_marking)
+ final_marking = property(__get_final_marking)
+
+ def set_legacy_dict(self, legacy_dict: Dict[str, Any]) -> None:
+ self.__legacy_dict = legacy_dict
+
+ def to_dict(self) -> Dict[str, Any]:
+ if self.__legacy_dict is None:
+ from pm4py.objects.ocpn.variants import to_alternative_format
+
+ self.__legacy_dict = to_alternative_format.apply(self)
+ return self.__legacy_dict
+
+ def __getitem__(self, key):
+ return self.to_dict()[key]
+
+ def __iter__(self):
+ return iter(self.to_dict())
+
+ def __len__(self):
+ return len(self.to_dict())
+
+ @property
+ def object_types(self) -> Set[str]:
+ """
+ Returns the set of all object types (colors) used in this net.
+
+ Returns
+ ------------
+ Set[str]
+ Set of object types (colors) used in this net.
+ """
+ return {p.object_type for p in self.places}
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d1613155dd9ab8e84dddcc13aff3804663b9607
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/semantics.py
@@ -0,0 +1,453 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from collections import defaultdict
+from itertools import chain, combinations
+from typing import Counter, Generic, TypeVar, Dict, Set, FrozenSet, Tuple, Iterator
+from pm4py.objects.ocpn.obj import OCPetriNet, OCMarking
+from pm4py.objects.ocpn.utils.ocpn_utils import pre_set
+
+N = TypeVar("N", bound=OCPetriNet)
+T = TypeVar("T", bound=OCPetriNet.Transition)
+P = TypeVar("P", bound=OCPetriNet.Place)
+
+
+class OCPetriNetSemantics(Generic[N]):
+
+ @classmethod
+ def is_enabled(cls, pn: N, transition: T, marking: OCMarking) -> bool:
+ """
+ Checks whether a given transition is enabled in a given object-centric Petri net and marking.
+ A transition is enabled if every non-variable arc has at least one object in the corresponding place,
+ and at least one arc can consume a token.
+
+ Parameters
+ ----------
+ net
+ object-centric Petri net
+ transition
+ transition to check
+ marking
+ marking to check
+
+ Returns
+ -------
+ bool
+ true if enabled, false otherwise
+ """
+ if transition not in pn.transitions:
+ return False
+
+ any_enabled = False
+ for a in transition.in_arcs:
+ if marking[a.source] == Counter():
+ if not a.is_variable:
+ return False
+ else:
+ any_enabled = True
+ return any_enabled
+
+ @classmethod
+ def is_binding_enabled(cls, pn: N, transition: T, marking: OCMarking, objects: Dict[str, Set]) -> bool:
+ """
+ Checks whether a given binding is enabled for a transition in a given object-centric Petri net and marking.
+
+ Parameters
+ ----------
+ pn
+ object-centric Petri net
+ transition
+ transition to check
+ marking
+ marking to check
+ objects
+ dict of objects per object type, e.g., {"order": {"order1", "order2"}}
+
+ Returns
+ -------
+ bool
+ true if binding is enabled, false otherwise
+ """
+ # We need to consume at least one token
+ at_least_one_object = False
+
+ # Check for every in-arc if:
+ # - the binding respects the variability of the in-arc
+ # - the state contains the necessary tokens
+ for a in transition.in_arcs:
+ ot = a.object_type
+
+ obj_set = objects.get(ot, set())
+
+ # Check if variability of arc is respected
+ if (not a.is_variable) and (not len(obj_set) == 1):
+ # nv-arc must be bound to exactly one object
+ return False
+
+ if not obj_set:
+ # We assign not objects to this variable arc
+ continue
+
+ at_least_one_object = True
+
+ # Check if state contains all tokens
+ place_tokens = marking[a.source].keys()
+ if not obj_set <= place_tokens:
+ # tokens not present
+ return False
+
+ return at_least_one_object
+
+ @classmethod
+ def check_and_fire(
+ cls, pn: N, transition: T, marking: OCMarking, objects: Dict[str, Set]
+ ) -> OCMarking:
+ """
+ Checks if a transition is enabled and fires it with the given set of objects.
+ If the transition is not enabled, it returns None.
+
+ Parameters
+ ----------
+ pn
+ object-centric Petri net
+ transition
+ transition to fire
+ marking
+ marking to use
+ objects
+ dict of objects per object type, e.g., {"order": {"order1", "order2"}}
+
+ Returns
+ -------
+ OCMarking or None
+ New marking after firing the transition or None if the transition was not enabled.
+ """
+ if cls.is_binding_enabled(pn, transition, marking, objects):
+ return cls.fire(pn, transition, marking, objects)
+ return None
+
+ @classmethod
+ def fire(
+ cls, pn: N, transition: T, marking: OCMarking, objects: Dict[str, Set]
+ ) -> OCMarking:
+ """
+ Execute a transition for a given set of objects per object type
+ For performance reasons, this function does not check if the transition is enabled or binding passed set of objects is valid, i.e.,
+ this should be performed by the invoking algorithm (if needed). Hence, markings can become negative.
+
+ Parameters
+ ----------
+ pn
+ object-centric Petri net
+ transition
+ transition to execute
+ marking
+ marking to use
+ objects
+ dict of objects per object type, e.g., {"order": {"order1", "order2"}}
+
+ Returns
+ -------
+ OCMarking
+ newly reached marking
+ """
+ # Copy counters place-wise so firing does not mutate the input marking.
+ m_out = OCMarking({place: counter.copy() for place, counter in marking.items()})
+ for a in transition.in_arcs:
+ obj_set = objects.get(a.object_type, set())
+ m_out[a.source] -= Counter(obj_set)
+ for a in transition.out_arcs:
+ obj_set = objects.get(a.object_type, set())
+ m_out[a.target] += Counter(obj_set)
+ return m_out
+
+ @classmethod
+ def replay(cls, ocpn: N, trace, initial_marking=None, final_marking=None):
+ """
+ Replays a trace on the object-centric Petri net.
+ Starts with the initial marking and check if the trace reaches the final marking.
+
+ Parameters
+ ----------
+ ocpn : N
+ The object-centric Petri net to replay on.
+ trace : tuple
+ A trace from the object-centric Petri net,
+ represented as a tuple of (transition_name, {object_type: set(object_ids)}) tuples.
+ initial_marking : OCMarking, optional
+ The initial marking to start the replay from. If None, the initial marking of the ocpn is used.
+ final_marking : OCMarking, optional
+ The final marking to check after the replay. If None, the final marking of the ocpn is used.
+ """
+ if not initial_marking:
+ initial_marking = ocpn.initial_marking
+ if not final_marking:
+ final_marking = ocpn.final_marking
+
+ transitions = {t.name: t for t in ocpn.transitions}
+
+ # start in the initial marking
+ marking = initial_marking
+
+ # replay each binding
+ for transition_name, objects in trace:
+ t = transitions[transition_name]
+
+ # Check if the binding is enabled
+ if not cls.is_binding_enabled(ocpn, t, marking, objects):
+ return False
+
+ # Fire
+ marking = cls.fire(ocpn, t, marking, objects)
+
+ # Check if we are in the final marking
+ return cls._is_final(marking, final_marking)
+
+ @classmethod
+ def _is_final(cls, marking: OCMarking, final_marking: OCMarking) -> bool:
+ """
+ Checks if the given marking is a valid final marking.
+ May be overriden by subclasses.
+
+ Parameters
+ ----------
+ marking
+ marking to check
+ final_marking
+ final marking to check against
+
+ Returns
+ -------
+ bool
+ true if marking is a final marking, false otherwise
+ """
+ return marking == final_marking
+
+ @classmethod
+ def enabled_transitions(
+ cls, pn: N, marking: OCMarking
+ ) -> Set[T]:
+ """
+ Returns the enabled transitions in a given object-centric Petri net and marking
+
+ Parameters
+ ----------
+ net
+ object-centric Petri net
+ marking
+ marking to check
+
+ Returns
+ -------
+ Set[T]
+ Set of enabled transitions
+ """
+ return {t for t in pn.transitions if cls.is_enabled(pn, t, marking)}
+
+ @classmethod
+ def get_possible_bindings(
+ cls, pn: N, transition: T, marking: OCMarking
+ ) -> Iterator[Dict[str, Set]]:
+ """
+ Returns an Iterator on the possible bindings for a given transition
+ in a given object-centric Petri net and marking.
+
+ Parameters
+ ----------
+ net
+ object-centric Petri net
+ transition
+ transition to check
+ marking
+ marking to check
+
+ Returns
+ -------
+ Iterator[Dict[str, Set]]
+ Iterator on all possible bindings (key is object type, value is a set of objects)
+ """
+
+ def get_common_objects(places: Set[P], marking: OCMarking) -> Set:
+ """
+ Get the intersection of objects in a set of places for the given marking.
+
+ The resulting set contains objects present in ALL specified places.
+
+ Parameters
+ ----------
+ places
+ Set of places to consider
+ marking
+ Marking to consider
+
+ Returns
+ -------
+ Set
+ Set containing the common objects
+ """
+ if not places:
+ return set()
+
+ # iter to avoid treating the first place as a special case
+ places_iter = iter(places)
+
+ result_counter = marking[next(places_iter)].copy()
+
+ for place in places_iter:
+ if not result_counter:
+ break
+ # intersect with the current place's objects
+ result_counter &= marking[place]
+
+ return set(result_counter)
+
+ def get_powerset(object_type: str, objects: Set) -> Set[FrozenSet[Tuple]]:
+ """
+ Generate the powerset of a set of objects in the form (object_type, object_id).
+
+ Parameters
+ ----------
+ object_type
+ The type of the objects
+ objects
+ Set of objects to generate the powerset for
+
+ Returns
+ -------
+ Set[FrozenSet[Tuple]]
+ Set of frozen sets representing the powerset of the input set
+ """
+ items = [(object_type, obj_id) for obj_id in objects]
+ powerset_iterator = chain.from_iterable(
+ combinations(items, r) for r in range(len(items) + 1)
+ )
+ return {frozenset(subset) for subset in powerset_iterator}
+
+ def recursive_bindings(
+ variable_object_types: Set[str],
+ non_variable_object_types: Set[str],
+ available_objects: Dict[str, Set],
+ ) -> Set[FrozenSet[Tuple]]:
+ """
+ Recursively generate all possible bindings given the remaining object types and available objects.
+
+ Parameters
+ ----------
+ variable_object_types
+ Set of variable object types to consider
+ non_variable_object_types
+ Set of non-variable object types to consider
+ available_objects
+ Dictionary where keys are object types and values are sets of available objects for that type
+
+ Returns
+ -------
+ Set[FrozenSet[Tuple]]
+ Set of possible bindings (as frozen sets of tuples (object_type, object_id))
+ """
+ # Base case
+ if not non_variable_object_types and not variable_object_types:
+ # empty binding
+ return {frozenset()}
+
+ # Recursive case
+ # Pick next object type to process. Non-variable object types are processed first.
+ is_variable = not non_variable_object_types
+ types_to_process = variable_object_types if is_variable else non_variable_object_types
+ ot = types_to_process.pop()
+
+ try:
+ ot_objects = available_objects.get(ot, set())
+
+ # Get all possible object combinations for this object type
+ if is_variable:
+ # For variable object types, we can pick 0-all objects (powerset)
+ current_options = get_powerset(ot, ot_objects)
+ else:
+ # For non-variable object types, we must pick exactly one object
+ current_options = {frozenset({(ot, obj)}) for obj in ot_objects}
+ # No options -> no bindings possible
+ if not current_options:
+ return set()
+
+ # Recursively get bindings for the remaining object types
+ sub_bindings = recursive_bindings(
+ variable_object_types,
+ non_variable_object_types,
+ available_objects,
+ )
+
+ # cross product current options with sub-bindings
+ bindings = {
+ sub_binding.union(option)
+ for option in current_options
+ for sub_binding in sub_bindings
+ }
+
+ return bindings
+
+ finally:
+ # restore the set of object types
+ types_to_process.add(ot)
+
+
+ if transition not in pn.transitions:
+ # no binding to yield
+ return
+
+ # get object types involved in t and whether they are variable
+ non_variable_object_types = set()
+ variable_object_types = set()
+ for a in transition.in_arcs:
+ if a.is_variable:
+ variable_object_types.add(a.object_type)
+ else:
+ non_variable_object_types.add(a.object_type)
+
+ # get predecessor places per object type
+ predecessors = {
+ ot: pre_set(transition, ot)
+ for ot in non_variable_object_types | variable_object_types
+ }
+
+ # per ot, get objects present in all predecessor places
+ common_objects = {
+ ot: get_common_objects(predecessors[ot], marking)
+ for ot in non_variable_object_types | variable_object_types
+ }
+
+ # get bindings
+ frozenset_bindings = recursive_bindings(
+ variable_object_types, non_variable_object_types, common_objects
+ )
+
+ # Loop through immutable bindings and yield dictionary one by one
+ for fs_binding in frozenset_bindings:
+ # do not yield the empty binding
+ if not fs_binding:
+ continue
+
+ binding_dict = defaultdict(set)
+ for ot, obj in fs_binding:
+ binding_dict[ot].add(obj)
+
+ yield binding_dict
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ccca4b8b3a5ca377efb5454abf3988b56886367
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/utils/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocpn.utils import ocpn_utils
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/utils/ocpn_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/utils/ocpn_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..82fbddbcd9ddbebe9d5a0c89a5aebbb261a12894
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/utils/ocpn_utils.py
@@ -0,0 +1,70 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Set
+
+
+def pre_set(elem, object_type: str = None) -> Set:
+ """
+ Returns the set of predecessors of an element (place or transition) in an object-centric Petri net.
+ Restricted to predecessors connected using arcs of the object type, if specified.
+
+ Parameters
+ ----------
+ elem
+ Element (place or transition) for which to get the predecessors
+ object_type
+ Object type to restrict the predecessors to (optional)
+
+ Returns
+ -------
+ Set
+ Set of predecessor elements (places or transitions) of the specified object type.
+ """
+ pre = set()
+ for a in elem.in_arcs:
+ if object_type is None or a.object_type == object_type:
+ pre.add(a.source)
+ return pre
+
+def post_set(elem, object_type: str = None) -> Set:
+ """
+ Returns the set of successors of an element (place or transition) in an object-centric Petri net.
+ Restricted to successors connected using arcs of the object type, if specified.
+
+ Parameters
+ ----------
+ elem
+ Element (place or transition) for which to get the successors
+ object_type
+ Object type to restrict the successors to (optional)
+
+ Returns
+ -------
+ Set
+ Set of successor elements (places or transitions) of the specified object type.
+ """
+ post = set()
+ for a in elem.out_arcs:
+ if object_type is None or a.object_type == object_type:
+ post.add(a.target)
+ return post
\ No newline at end of file
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..72bd3e3cd642f056c5b481ff3bf7a8c4387cccd1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.ocpn.variants import to_oc_causal_net, to_alternative_format
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/to_alternative_format.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/to_alternative_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd05fd06ea041b904edfeef82ad2315d683d4f79
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/to_alternative_format.py
@@ -0,0 +1,301 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Any, Dict, Set, Tuple
+from pm4py.objects.ocpn.obj import OCMarking, OCPetriNet
+from pm4py.objects.petri_net.obj import Marking, PetriNet
+from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to
+
+
+def apply(ocpn: OCPetriNet, parameters=None) -> Dict[str, Any]:
+ """
+ Converts an OCPetriNet object to the alternative format as a Dict[str, Any] specified in pm4py.algo.discovery.ocel.ocpn.variants.classic.
+ Only the essential components of the OCPetriNet are retained in the alternative format: `activities`, `object_types`, `petri_nets`, `double_arcs_on_activity`, `start_activities`, and `end_activities`.
+
+ Parameters
+ ----------
+ ocpn: OCPetriNet
+ The object-centric Petri net to be converted.
+ parameters: dict, optional
+ Additional parameters for the conversion (not used in this implementation).
+
+ Returns
+ ----------
+ ocpn: Dict[str, Any]
+ Alternative format representation of the object-centric Petri net.
+ """
+ if parameters is None:
+ parameters = {}
+
+ object_types = ocpn.object_types
+ activities = {t.label for t in ocpn.transitions if t.label}
+ activities_per_object_type = _get_activities_per_object_type(ocpn)
+ petri_nets = {ot: _project_ocpn_on_object_type(ocpn, ot) for ot in object_types}
+ double_arcs_on_activity = _get_double_arcs(ocpn)
+ start_activities = _get_start_end_activities(
+ ocpn, ocpn.initial_marking, use_out_arcs=True
+ )
+ end_activities = _get_start_end_activities(
+ ocpn, ocpn.final_marking, use_out_arcs=False
+ )
+
+ alternative_format = {
+ "activities": activities,
+ "object_types": object_types,
+ "petri_nets": petri_nets,
+ "double_arcs_on_activity": double_arcs_on_activity,
+ "start_activities": start_activities,
+ "end_activities": end_activities,
+ # information that is not available on a standalone OCPN object is
+ # exposed using the same shape as the legacy discovery dictionary.
+ "edges": _initialize_edge_metrics(object_types),
+ "edges_performance": {
+ "event_couples": {ot: {} for ot in object_types},
+ "total_objects": {ot: {} for ot in object_types},
+ },
+ "activities_indep": _initialize_activity_metrics(activities),
+ "activities_ot": _initialize_ot_activity_metrics(
+ object_types, activities_per_object_type
+ ),
+ "tbr_results": {},
+ }
+
+ return alternative_format
+
+
+def _get_activities_per_object_type(ocpn: OCPetriNet) -> Dict[str, Set[str]]:
+ activities = {ot: set() for ot in ocpn.object_types}
+ for arc in ocpn.arcs:
+ transition = None
+ if isinstance(arc.source, OCPetriNet.Transition):
+ transition = arc.source
+ elif isinstance(arc.target, OCPetriNet.Transition):
+ transition = arc.target
+
+ if transition is not None and transition.label is not None:
+ activities[arc.object_type].add(transition.label)
+
+ return activities
+
+
+def _initialize_edge_metrics(object_types) -> Dict[str, Dict[str, Dict[str, Any]]]:
+ return {
+ "event_couples": {ot: {} for ot in object_types},
+ "unique_objects": {ot: {} for ot in object_types},
+ "total_objects": {ot: {} for ot in object_types},
+ }
+
+
+def _initialize_activity_metrics(activities) -> Dict[str, Dict[str, set]]:
+ return {
+ "events": {act: set() for act in activities},
+ "unique_objects": {act: set() for act in activities},
+ "total_objects": {act: set() for act in activities},
+ }
+
+
+def _initialize_ot_activity_metrics(
+ object_types, activities_per_object_type=None
+) -> Dict[str, Dict[str, Dict[str, set]]]:
+ ret = {"events": {}, "unique_objects": {}, "total_objects": {}}
+
+ for ot in object_types:
+ activities = (
+ activities_per_object_type.get(ot, set())
+ if activities_per_object_type is not None
+ else set()
+ )
+ ret["events"][ot] = {act: set() for act in activities}
+ ret["unique_objects"][ot] = {act: set() for act in activities}
+ ret["total_objects"][ot] = {act: set() for act in activities}
+
+ return ret
+
+
+def _project_ocpn_on_object_type(
+ ocpn: OCPetriNet, object_type
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Projects the OCPetriNet into a tuple containing the Petri net projection and the initial and final marking projections for the object type.
+
+ Parameters
+ ----------
+ ocpn: OCPetriNet
+ The object-centric Petri net to be split.
+ object_type: str
+ The object type for which the projection is to be created.
+
+ Returns
+ ----------
+ tuple[PetriNet, ~pm4py.objects.petri_net.obj.Marking, ~pm4py.objects.petri_net.obj.Marking]
+ A tuple containing the Petri net projection, initial marking, and final marking projection for the object type.
+ """
+ # extract places by ot
+ places = [p for p in ocpn.places if p.object_type == object_type]
+
+ # extract arcs from those places
+ arcs = [
+ a
+ for p in places
+ for a in p.out_arcs | p.in_arcs
+ if a.object_type == object_type
+ ]
+
+ # extract transitions as those used in the arcs
+ transitions = {
+ a.source for a in arcs if isinstance(a.source, OCPetriNet.Transition)
+ } | {a.target for a in arcs if isinstance(a.target, OCPetriNet.Transition)}
+
+ # construct net projection
+ pn_places = {p: PetriNet.Place(p.name) for p in places}
+ pn_transitions = {t: PetriNet.Transition(name=t.name, label=t.label) for t in transitions}
+
+ # create pn
+ pn = PetriNet(
+ name=f"{ocpn.name}_{object_type}",
+ places=set(pn_places.values()),
+ transitions=set(pn_transitions.values()),
+ )
+
+ # add arcs
+ for arc in arcs:
+ source = pn_places.get(arc.source, pn_transitions.get(arc.source))
+ target = pn_places.get(arc.target, pn_transitions.get(arc.target))
+
+ add_arc_from_to(source, target, pn)
+
+ # initial (& final) marking as multiset of places in the initial marking where the count is the number of objects of that type in the place
+ initial_marking = oc_marking_to_petri(ocpn.initial_marking, pn_places)
+ final_marking = oc_marking_to_petri(ocpn.final_marking, pn_places)
+
+ return pn, initial_marking, final_marking
+
+
+def oc_marking_to_petri(
+ oc_marking: OCMarking,
+ pn_places: Dict[OCPetriNet.Place, PetriNet.Place],
+) -> Marking:
+ """
+ Convert an object-centric marking to a classic Petri-net Marking that
+ contains only the places that are keys of the `pn_places` dictionary.
+
+ Parameters
+ ----------
+ oc_marking: OCMarking
+ The object-centric marking to convert.
+ pn_places: Dict[OCPetriNet.Place, PetriNet.Place]
+ A mapping from object-centric Petri net places to classic Petri net places.
+
+ Returns
+ ----------
+ Marking : ~pm4py.objects.petri_net.obj.Marking
+ A classic Petri net marking (place -> token count)
+ """
+ petri_marking = Marking()
+ if not oc_marking:
+ return petri_marking
+
+ # Aggregate multiplicities per place for the requested object type
+ for place, counter in oc_marking.items():
+ if place in pn_places.keys():
+ if pn_places[place] not in petri_marking:
+ petri_marking[pn_places[place]] = 0
+ petri_marking[pn_places[place]] += sum(counter.values())
+
+ return petri_marking
+
+
+def _get_double_arcs(ocpn: OCPetriNet) -> Dict[str, Any]:
+ """
+ Returns a dictionary mapping each object type to a dict mapping an activity to True if only connected to variable arcs, or False if only connected to non-variable arcs.
+
+ Parameters
+ ----------
+ ocpn: OCPetriNet
+ The object-centric Petri net to analyze.
+
+ Returns
+ ----------
+ Dict[str, Any]
+ A dictionary where keys are object types and values are dicts where keys are
+ activity names and values are True if only connected to variable arcs, or False if only connected to non-variable arcs.
+ """
+ double_arcs = {ot: {} for ot in ocpn.object_types}
+ for arc in ocpn.arcs:
+ ot = arc.object_type
+ act = arc.source.label if isinstance(arc.source, OCPetriNet.Transition) else arc.target.label
+ if act is None:
+ continue
+ if act in double_arcs[ot]:
+ if double_arcs[ot][act] != arc.is_variable:
+ raise ValueError(
+ f"Transition {act} in object type {ot} is connected to both variable and non-variable arcs. The given OCPetriNet is invalid."
+ )
+ double_arcs[ot][act] = arc.is_variable
+
+ return double_arcs
+
+
+def _get_start_end_activities(
+ ocpn: OCPetriNet,
+ marking: OCMarking,
+ use_out_arcs: bool = True,
+) -> Dict[str, Any]:
+ """
+ Returns a dictionary mapping each object type to a dict mapping the start/end activities to empty sets for events, unique_objects, and total_objects.
+
+ Parameters
+ ----------
+ ocpn: OCPetriNet
+ The object-centric Petri net to analyze.
+ marking: OCMarking
+ The initial or final marking of the OCPetriNet, used to determine start or end activities.
+
+ Returns
+ ----------
+ Dict[str, Any]
+ The start or end activities dictionaries.
+ """
+ activities = _initialize_ot_activity_metrics(ocpn.object_types)
+
+ if marking is None:
+ return activities
+
+ for p in marking.places:
+ ot = p.object_type
+ arcs = p.out_arcs if use_out_arcs else p.in_arcs
+ for arc in arcs:
+ if use_out_arcs and isinstance(arc.target, OCPetriNet.Transition):
+ transition = arc.target
+ elif not use_out_arcs and isinstance(arc.source, OCPetriNet.Transition):
+ transition = arc.source
+ else:
+ transition = None
+
+ if transition is None or transition.label is None:
+ continue
+
+ activities["events"][ot].setdefault(transition.label, set())
+ activities["unique_objects"][ot].setdefault(transition.label, set())
+ activities["total_objects"][ot].setdefault(transition.label, set())
+
+ return activities
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/to_oc_causal_net.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/to_oc_causal_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdb4570107ab74dc83c62ecf22b3ab698b9bb8cc
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/ocpn/variants/to_oc_causal_net.py
@@ -0,0 +1,631 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.oc_causal_net.obj import OCCausalNet
+from pm4py.objects.ocpn.obj import OCPetriNet
+import networkx as nx
+
+
+AUX_ACTIVITY_PREFIX = "_silent_aux_"
+POST_AUX_ACTIVITY_PREFIX = AUX_ACTIVITY_PREFIX + "out_"
+PRE_AUX_ACTIVITY_PREFIX = AUX_ACTIVITY_PREFIX + "in_"
+
+
+def apply(ocpn: OCPetriNet, parameters=None) -> OCCausalNet:
+ """
+ Convets an Object-centric Petri Net to an Object-centric Causal Net.
+
+ Parameters
+ ----------
+ ocpn: OCPetriNet
+ The Object-centric Petri Net to be converted.
+ parameters: dict, optional
+ Additional parameters for the conversion (not used in this implementation).
+
+ Returns
+ ----------
+ OCCausalNet: OCCausalNet
+ The resulting Object-centric Causal Net.
+ """
+ # assert no place start with AUX_ACTIVITY_PREFIX to be able to identify auxiliary places
+ for p in ocpn.places:
+ if p.name.startswith(AUX_ACTIVITY_PREFIX):
+ raise ValueError(
+ f"Place {p.name} starts with the reserved prefix '{AUX_ACTIVITY_PREFIX}'."
+ )
+
+ places = ocpn.places
+ transitions = ocpn.transitions
+ object_types = ocpn.object_types
+
+ dependencies = dict()
+ input_marker_groups = dict()
+ output_marker_groups = dict()
+
+ # get multi-object types per transition
+ multi_ots = get_multi_object_types(ocpn)
+
+ # create dependencies and marker groups for transitions
+ transition_dependencies_marker_groups(
+ transitions,
+ multi_ots,
+ dependencies,
+ input_marker_groups,
+ output_marker_groups,
+ )
+
+ # create dependencies and marker groups for places
+ place_dependencies_marker_groups(
+ places,
+ multi_ots,
+ dependencies,
+ input_marker_groups,
+ output_marker_groups,
+ )
+
+ # handle start and end places
+ start_places = {
+ ot: [p for p in ocpn.initial_marking.places if p.object_type == ot]
+ for ot in ocpn.object_types
+ }
+ end_places = {
+ ot: [p for p in ocpn.final_marking.places if p.object_type == ot]
+ for ot in ocpn.object_types
+ }
+
+ # add START and END activities and their dependencies and marker groups
+ start_end_act_dependencies_marker_groups(
+ object_types,
+ dependencies,
+ input_marker_groups,
+ output_marker_groups,
+ start_places,
+ end_places,
+ )
+
+ # add START and END activities to marker groups of start and end places
+ add_start_end_act_markers(
+ object_types,
+ input_marker_groups,
+ output_marker_groups,
+ start_places,
+ end_places,
+ )
+
+ # create the occn
+ occn = OCCausalNet(
+ dependency_graph=nx.MultiDiGraph(dependencies),
+ output_marker_groups=output_marker_groups,
+ input_marker_groups=input_marker_groups,
+ )
+
+ return occn
+
+
+def get_multi_object_types(ocpn: OCPetriNet) -> dict:
+ """
+ Returns a dictionary mapping transition names to two dictionaries of multi-input/multi-output
+ object types
+ mapping object types to True if they are variable and False otherwise.
+ A multi-input/output object type is one that has at least two incoming/outgoing arcs
+ to/from the transition.
+
+ Parameters
+ ----------
+ ocpn: OCPetriNet
+ The Object-centric Petri Net to analyze.
+
+ Returns
+ -------
+ dict: Dictionary with transition names as keys a dictionary mapping "input" and "output"
+ to dictionaries of multi-input/multi-output object types to True/False.
+ """
+ multi_ots = {}
+ for t in ocpn.transitions:
+ multi_ots[t.name] = {"input": dict(), "output": dict()}
+ in_ots = [arc.object_type for arc in t.in_arcs]
+ multi_ots[t.name]["output"] = dict()
+ out_ots = [arc.object_type for arc in t.out_arcs]
+
+ for ot in set(in_ots):
+ if in_ots.count(ot) > 1:
+ multi_ots[t.name]["input"][ot] = any(
+ arc.is_variable for arc in t.in_arcs if arc.object_type == ot
+ )
+
+ for ot in set(out_ots):
+ if out_ots.count(ot) > 1:
+ multi_ots[t.name]["output"][ot] = any(
+ arc.is_variable for arc in t.out_arcs if arc.object_type == ot
+ )
+
+ return multi_ots
+
+
+def get_aux_place_name(transition_name, object_type, is_input_aux):
+ """
+ Returns the name of the auxiliary place for a given transition and object type.
+
+ Parameters
+ ----------
+ transition_name: str
+ The name of the transition.
+ object_type: str
+ The object type associated with the auxiliary place.
+ is_input_aux: bool
+ Whether the auxiliary place is an input auxiliary place (True) or output auxiliary place (False).
+
+ Returns
+ -------
+ str: The name of the auxiliary place.
+ """
+ prefix = PRE_AUX_ACTIVITY_PREFIX if is_input_aux else POST_AUX_ACTIVITY_PREFIX
+ return f"{prefix}{transition_name}_{object_type}"
+
+
+def transition_dependencies_marker_groups(
+ transitions,
+ multi_ots,
+ dependencies,
+ input_marker_groups,
+ output_marker_groups,
+):
+ """
+ Creates dependencies and marker groups for transitions in the Object-centric Petri Net.
+ Each transition has one input marker group featuring a marker for each input arc,
+ and one output marker group featuring a marker for each output arc.
+
+ Parameters
+ ----------
+ transitions: list
+ List of transitions in the Object-centric Petri Net.
+ multi_ots: dict
+ Dictionary mapping transition names to multi-object types.
+ dependencies: dict
+ Dictionary to store dependencies between activities.
+ input_marker_groups: dict
+ Dictionary to store input marker groups.
+ output_marker_groups: dict
+ Dictionary to store output marker groups.
+ """
+ for t in transitions:
+ # dependencies
+ dependencies[t.name] = dict() # add as activity
+
+ # get multi object types for this transition
+ multi_input = multi_ots.get(t.name, dict()).get("input", dict())
+ multi_output = multi_ots.get(t.name, dict()).get("output", dict())
+
+ for arc in t.in_arcs:
+ if arc.object_type in multi_input:
+ # aux. place goes in between source place and transition
+ aux_place_name = get_aux_place_name(
+ t.name, arc.object_type, is_input_aux=True
+ )
+ add_dependency(
+ dependencies, arc.source, aux_place_name, arc.object_type
+ )
+ add_dependency(dependencies, aux_place_name, t, arc.object_type)
+ else:
+ add_dependency(dependencies, arc.source, t, arc.object_type)
+ for arc in t.out_arcs:
+ if arc.object_type in multi_output:
+ # aux. place goes in between transition and target place
+ aux_place_name = get_aux_place_name(
+ t.name, arc.object_type, is_input_aux=False
+ )
+ add_dependency(dependencies, t, aux_place_name, arc.object_type)
+ add_dependency(
+ dependencies, aux_place_name, arc.target, arc.object_type
+ )
+ else:
+ add_dependency(dependencies, t, arc.target, arc.object_type)
+
+ # markers from input aux activities
+ input_aux_markers = [
+ OCCausalNet.Marker(
+ related_activity=(
+ get_aux_place_name(t.name, object_type, is_input_aux=True)
+ ),
+ object_type=object_type,
+ count_range=(0, float("inf")) if multi_input[object_type] else (1, 1),
+ marker_key=get_next_key(),
+ )
+ for object_type in multi_input
+ ]
+
+ # single input marker group
+ input_marker_groups[t.name] = [
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=arc.source.name,
+ object_type=arc.object_type,
+ count_range=(0, float("inf")) if arc.is_variable else (1, 1),
+ marker_key=get_next_key(),
+ )
+ for arc in t.in_arcs
+ if arc.object_type not in multi_input
+ ]
+ + input_aux_markers
+ )
+ ]
+
+ # markers to output aux activities
+ output_aux_markers = [
+ OCCausalNet.Marker(
+ related_activity=(
+ get_aux_place_name(t.name, object_type, is_input_aux=False)
+ ),
+ object_type=object_type,
+ count_range=(0, float("inf")) if multi_output[object_type] else (1, 1),
+ marker_key=get_next_key(),
+ )
+ for object_type in multi_output
+ ]
+
+ # single output marker group
+ output_marker_groups[t.name] = [
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=(arc.target.name),
+ object_type=arc.object_type,
+ count_range=(0, float("inf")) if arc.is_variable else (1, 1),
+ marker_key=get_next_key(),
+ )
+ for arc in t.out_arcs
+ if arc.object_type not in multi_output
+ ]
+ + output_aux_markers
+ )
+ ]
+
+ # add marker groups for input auxiliary places
+ for ot in multi_input:
+ aux_place_name = get_aux_place_name(t.name, ot, is_input_aux=True)
+ output_marker_groups[aux_place_name] = [
+ # single marker group with one marker for the transition
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=t.name,
+ object_type=ot,
+ count_range=(1, 1),
+ marker_key=get_next_key(),
+ )
+ ]
+ )
+ ]
+ input_marker_groups[aux_place_name] = [
+ # marker for every predecessor of t with this object type
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=arc.source.name,
+ object_type=ot,
+ count_range=(1, 1),
+ marker_key=get_next_key(),
+ )
+ for arc in t.in_arcs
+ if arc.object_type == ot
+ ]
+ )
+ ]
+
+ # add marker groups for output auxiliary places
+ for ot in multi_output:
+ aux_place_name = get_aux_place_name(t.name, ot, is_input_aux=False)
+ input_marker_groups[aux_place_name] = [
+ # single marker group with one marker for the transition
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=t.name,
+ object_type=ot,
+ count_range=(1, 1),
+ marker_key=get_next_key(),
+ )
+ ]
+ )
+ ]
+ output_marker_groups[aux_place_name] = [
+ # marker for every successor of t with this object type
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=arc.target.name,
+ object_type=ot,
+ count_range=(1, 1),
+ marker_key=get_next_key(),
+ )
+ for arc in t.out_arcs
+ if arc.object_type == ot
+ ]
+ )
+ ]
+
+
+def place_dependencies_marker_groups(
+ places, multi_ots, dependencies, input_marker_groups, output_marker_groups
+):
+ """
+ Creates dependencies and marker groups for places in the Object-centric Petri Net.
+ Each place has one input marker group per input arc having one marker each,
+ and one output marker group per output arc having one marker each.
+
+ Parameters
+ ----------
+ places: list
+ List of places in the Object-centric Petri Net.
+ multi_ots: dict
+ Dictionary mapping transition names to multi-object types.
+ dependencies: dict
+ Dictionary to store dependencies between activities.
+ input_marker_groups: dict
+ Dictionary to store input marker groups.
+ output_marker_groups: dict
+ Dictionary to store output marker groups.
+ """
+
+ def is_predecessor_transition_with_multi_variant(arc):
+ """
+ Checks if the source of the arc is a transition with and the object type
+ of the arc is a multi-output object type for the given transition.
+ """
+ return isinstance(
+ arc.source, OCPetriNet.Transition
+ ) and arc.object_type in multi_ots.get(arc.source.name, dict()).get(
+ "output", dict()
+ )
+
+ def is_successor_transition_with_multi_variant(arc):
+ """
+ Checks if the target of the arc is a transition with and the object type
+ of the arc is a multi-input object type for the given transition.
+ """
+ return isinstance(
+ arc.target, OCPetriNet.Transition
+ ) and arc.object_type in multi_ots.get(arc.target.name, dict()).get(
+ "input", dict()
+ )
+
+ for p in places:
+ # dependencies
+ if p.name not in dependencies:
+ dependencies[p.name] = dict() # add as activity
+ for arc in p.in_arcs:
+ if not is_predecessor_transition_with_multi_variant(arc):
+ add_dependency(dependencies, arc.source, p, arc.object_type)
+ else:
+ pass # dependency for auxiliary places was already added
+ for arc in p.out_arcs:
+ if not is_successor_transition_with_multi_variant(arc):
+ add_dependency(dependencies, p, arc.target, arc.object_type)
+ else:
+ pass # dependency for auxiliary places was already added
+
+ # one-element marker group per arc
+ input_marker_groups[p.name] = [
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=(
+ arc.source.name
+ if not is_predecessor_transition_with_multi_variant(arc)
+ else get_aux_place_name(
+ arc.source.name, arc.object_type, is_input_aux=False
+ )
+ ), # connect to aux place instead if multi-variant ot
+ object_type=arc.object_type,
+ count_range=(1, float("inf")),
+ marker_key=get_next_key(),
+ )
+ ]
+ )
+ for arc in p.in_arcs
+ ]
+
+ output_marker_groups[p.name] = [
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=(
+ arc.target.name
+ if not is_successor_transition_with_multi_variant(arc)
+ else get_aux_place_name(
+ arc.target.name, arc.object_type, is_input_aux=True
+ )
+ ),
+ object_type=arc.object_type,
+ count_range=(1, float("inf")),
+ marker_key=get_next_key(),
+ )
+ ]
+ )
+ for arc in p.out_arcs
+ ]
+
+
+def start_end_act_dependencies_marker_groups(
+ object_types,
+ dependencies,
+ input_marker_groups,
+ output_marker_groups,
+ start_places,
+ end_places,
+):
+ """
+ Adds a START and END activity for each object type.
+ Creates dependencies and marker groups for those new activities.
+ Each START / END activity has one input / output marker group consisting
+ of markers for every start / end place.
+
+ Parameters
+ ----------
+ object_types: list
+ List of object types in the Object-centric Petri Net.
+ dependencies: dict
+ Dictionary to store dependencies between activities.
+ input_marker_groups: dict
+ Dictionary to store input marker groups.
+ output_marker_groups: dict
+ Dictionary to store output marker groups.
+ start_places: dict
+ Dictionary mapping object types to their start places.
+ end_places: dict
+ Dictionary mapping object types to their end places.
+ """
+ for ot in object_types:
+ # START places
+ dependencies[f"START_{ot}"] = dict()
+ for p in start_places[ot]:
+ add_dependency(dependencies, f"START_{ot}", p, ot)
+
+ # one output marker group
+ output_marker_groups[f"START_{ot}"] = [
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=p.name,
+ object_type=ot,
+ count_range=(1, float("inf")),
+ marker_key=get_next_key(),
+ )
+ for p in start_places[ot]
+ ]
+ )
+ ]
+
+ # END places
+ dependencies[f"END_{ot}"] = dict()
+ for p in end_places[ot]:
+ add_dependency(dependencies, p, f"END_{ot}", ot)
+
+ # one input marker group
+ input_marker_groups[f"END_{ot}"] = [
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=p.name,
+ object_type=ot,
+ count_range=(1, float("inf")),
+ marker_key=get_next_key(),
+ )
+ for p in end_places[ot]
+ ]
+ )
+ ]
+
+
+def add_start_end_act_markers(
+ object_types, input_marker_groups, output_marker_groups, start_places, end_places
+):
+ """
+ Adds markers for the START and END activities to the start / end places.
+ These markers are the same as for any other predecessor / successor activity.
+
+ Parameters
+ ----------
+ object_types: list
+ List of object types in the Object-centric Petri Net.
+ input_marker_groups: dict
+ Dictionary to store input marker groups.
+ output_marker_groups: dict
+ Dictionary to store output marker groups.
+ start_places: dict
+ Dictionary mapping object types to their start places.
+ end_places: dict
+ Dictionary mapping object types to their end places.
+ """
+ for ot in object_types:
+ for p in start_places[ot]:
+ # add new marker group
+ if p.name not in input_marker_groups:
+ input_marker_groups[p.name] = []
+ input_marker_groups[p.name].append(
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=f"START_{ot}",
+ object_type=ot,
+ count_range=(1, float("inf")),
+ marker_key=get_next_key(),
+ )
+ ]
+ )
+ )
+ for p in end_places[ot]:
+ # add new marker group
+ if p.name not in output_marker_groups:
+ output_marker_groups[p.name] = []
+ output_marker_groups[p.name].append(
+ OCCausalNet.MarkerGroup(
+ [
+ OCCausalNet.Marker(
+ related_activity=f"END_{ot}",
+ object_type=ot,
+ count_range=(1, float("inf")),
+ marker_key=get_next_key(),
+ )
+ ]
+ )
+ )
+
+
+def add_dependency(dependencies: dict, source, target, object_type):
+ """
+ Adds a dependency to the dependencies dictionary. Ignores duplicate dependencies.
+
+ Parameters
+ ----------
+ dependencies: dict
+ The dictionary to which the dependency will be added.
+ source: str or OCPetriNet.Place or OCPetriNet.Transition
+ The source of the dependency arc.
+ target str or OCPetriNet.Place or OCPetriNet.Transition
+ The target of the dependency arc.
+ object_type
+ The object type associated with the dependency.
+ """
+ source_label = source if isinstance(source, str) else source.name
+ target_label = target if isinstance(target, str) else target.name
+ if source_label not in dependencies:
+ dependencies[source_label] = dict()
+ if target_label not in dependencies[source_label]:
+ dependencies[source_label][target_label] = dict()
+ if object_type not in dependencies[source_label][target_label]:
+ dependencies[source_label][target_label][object_type] = {
+ "object_type": object_type
+ }
+
+
+def get_next_key():
+ """
+ Will return a unique key for each call, starting from 0.
+ """
+ # initialize on first call
+ if not hasattr(get_next_key, "counter"):
+ get_next_key.counter = 0
+ current = get_next_key.counter
+ get_next_key.counter += 1
+ return current
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..89d724371ed83931ef37c9e7b30295355fb2ec42
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.org import roles, sna
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/roles/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/roles/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e886fa0b1291c3af6c08add07473b4ab91cddf1c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/roles/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.org.roles import obj
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/roles/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/roles/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..16f870a01bae0384fcbc8895a4b5dc488f8c81cc
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/roles/obj.py
@@ -0,0 +1,49 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import List, Dict
+
+
+class Role(object):
+ activities: List[str]
+ originator_importance = Dict[str, float]
+
+ def __init__(
+ self, activities: List[str], originator_importance: Dict[str, float]
+ ):
+ self.activities = activities
+ self.originator_importance = originator_importance
+
+ def __repr__(self):
+ return (
+ "Activities: "
+ + str(self.activities)
+ + " Originators importance "
+ + str(self.originator_importance)
+ )
+
+ def __str__(self):
+ return (
+ "Activities: "
+ + str(self.activities)
+ + " Originators importance "
+ + str(self.originator_importance)
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/sna/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/sna/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..443eace677afdf4412edc66d887dcaddbb960aeb
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/sna/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.org.sna import obj
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/sna/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/sna/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..7706e73bc1cacd01b297aac3a9fc4f3e8aca63c6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/org/sna/obj.py
@@ -0,0 +1,33 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from typing import Dict, Tuple
+
+
+class SNA(object):
+ connections: Dict[Tuple[str, str], float]
+ is_directed: bool
+
+ def __init__(
+ self, connections: Dict[Tuple[str, str], int], is_directed: bool
+ ):
+ self.connections = connections
+ self.is_directed = is_directed
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a138bc6a5bf5736b5df0be10dbab277ffd3c469b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/__init__.py
@@ -0,0 +1,32 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.petri_net import (
+ obj,
+ properties,
+ semantics,
+ utils,
+ saw_net,
+ stochastic,
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/data_marking.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/data_marking.py
new file mode 100644
index 0000000000000000000000000000000000000000..20a0d6fddb3c8d69c3c66397027163e98ca1884d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/data_marking.py
@@ -0,0 +1,43 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.obj import Marking
+
+
+class DataMarking(Marking):
+ def __init__(self, marking=None):
+ Marking.__init__(self, marking)
+ self.data_dict = {}
+
+ def __repr__(self):
+ # return str([str(p.name) + ":" + str(self.get(p)) for p in self.keys()])
+ # The previous representation had a bug, it took into account the order
+ # of the places with tokens
+ return (
+ str(
+ [
+ str(p.name) + ":" + str(self.get(p))
+ for p in sorted(list(self.keys()), key=lambda x: x.name)
+ ]
+ )
+ + " "
+ + str(self.data_dict)
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ad47be552dee4ba506f20cfaa7a2348651bb5ab
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/data_petri_nets/semantics.py
@@ -0,0 +1,222 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+from pm4py.objects.petri_net import properties as petri_properties
+from pm4py.objects.petri_net.sem_interface import Semantics
+import re
+
+
+security_pattern = re.compile(r"[.]|\\x[0-9a-fA-F]+")
+
+
+class DataPetriNetSemantics(Semantics):
+ def is_enabled(self, t, pn, m, **kwargs):
+ """
+ Verifies whether a given transition is enabled in a given Petri net and marking
+
+ Parameters
+ ----------
+ :param t: transition to check
+ :param pn: Petri net
+ :param m: marking to check
+ :param e: associated event (optional, as keyword argument)
+
+ Returns
+ -------
+ :return: true if enabled, false otherwise
+ """
+ e = kwargs["e"] if "e" in kwargs else {}
+ return is_enabled(t, pn, m, e)
+
+ def execute(self, t, pn, m, **kwargs):
+ """
+ Executes a given transition in a given Petri net, the given data marking and the associated event
+
+ Parameters
+ ----------
+ :param t: transition to execute
+ :param pn: Petri net
+ :param m: marking to use
+ :param e: associated event (optional, as keyword argument)
+
+ Returns
+ -------
+ :return: newly reached marking if :param t: is enabled, None otherwise
+ """
+ e = kwargs["e"] if "e" in kwargs else {}
+ return execute(t, pn, m, e)
+
+ def weak_execute(self, t, pn, m, **kwargs):
+ """
+ Executes a given transition in a given Petri net, the given data marking and the associated event,
+ even if not fully enabled
+
+ Parameters
+ ----------
+ :param t: transition to execute
+ :param pn: Petri net
+ :param m: marking to use
+ :param e: associated event (optional, as keyword argument)
+
+ Returns
+ -------
+ :return: newly reached marking
+ """
+ e = kwargs["e"] if "e" in kwargs else {}
+ return weak_execute(t, m, e)
+
+ def enabled_transitions(self, pn, m, **kwargs):
+ """
+ Returns a set of enabled transitions in a Petri net, the given data marking and the associated event
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param m: marking of the pn
+ :param e: associated event (optional, as keyword argument)
+
+ Returns
+ -------
+ :return: set of enabled transitions
+ """
+ e = kwargs["e"] if "e" in kwargs else {}
+ return enabled_transitions(pn, m, e)
+
+
+def check_guard_safety(guard):
+ """
+ Checks the security of a guard before evaluating that
+
+ Parameters
+ ----------------
+ guard
+ Guard
+
+ Returns
+ ----------------
+ safety
+ True if the guard is safe to execute, False otherwise
+ """
+ return not security_pattern.search(guard)
+
+
+def evaluate_guard(guard, read_variables, data):
+ """
+ Evaluates a data Petri net guard given the current data
+
+ Parameters
+ ------------------
+ guard
+ Guard
+ read_variables
+ Read variables
+
+ Returns
+ ------------------
+ boolean
+ Boolean value
+ """
+ guard = (
+ guard.replace("&&", " and ")
+ .replace("||", " or ")
+ .replace("true", "True")
+ .replace("false", "False")
+ )
+ try:
+ dct = {}
+ for k in read_variables:
+ dct[k] = None
+ for k, v in data.items():
+ dct[k] = v
+ if check_guard_safety(guard):
+ ret = eval(guard, dct)
+ return ret
+ return False
+ except BaseException:
+ # the guard could not be evaluated (for example, given missing data)
+ return False
+
+
+# 29/08/2021: the following methods have been incapsulated in the DataPetriNetSemantics class.
+# the long term idea is to remove them. However, first we need to adapt the existing code to the new
+# structure. Moreover, for performance reason, it is better to leave the code here, without having
+# to instantiate a DataPetriNetSemantics object.
+def is_enabled(t, pn, m, e):
+ if t not in pn.transitions:
+ return False
+ else:
+ for a in t.in_arcs:
+ if m[a.source] < a.weight:
+ return False
+
+ if petri_properties.TRANS_GUARD in t.properties:
+ guard = t.properties[petri_properties.TRANS_GUARD]
+ read_variables = (
+ t.properties[petri_properties.READ_VARIABLE]
+ if petri_properties.READ_VARIABLE in t.properties
+ else []
+ )
+ data = copy.copy(m.data_dict)
+ data.update(e)
+ evaluate_guard(guard, read_variables, data)
+
+ return True
+
+
+def execute(t, pn, m, e):
+ if not is_enabled(t, pn, m, e):
+ return None
+
+ m_out = copy.copy(m)
+ for a in t.in_arcs:
+ m_out[a.source] -= a.weight
+ if m_out[a.source] == 0:
+ del m_out[a.source]
+
+ for a in t.out_arcs:
+ m_out[a.target] += a.weight
+
+ m_out.data_dict.update(e)
+
+ return m_out
+
+
+def weak_execute(t, m, e):
+ m_out = copy.copy(m)
+ for a in t.in_arcs:
+ m_out[a.source] -= a.weight
+ if m_out[a.source] <= 0:
+ del m_out[a.source]
+ for a in t.out_arcs:
+ m_out[a.target] += a.weight
+
+ m_out.data_dict.update(e)
+
+ return m_out
+
+
+def enabled_transitions(pn, m, e):
+ enabled = set()
+ for t in pn.transitions:
+ if is_enabled(t, pn, m, e):
+ enabled.add(t)
+ return enabled
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a362d419451354bf646ddeb40d8ec654a9a3dd46
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.exporter import variants, exporter
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..822c734a466ffe9af5bf167214b82c2deb9dcfb5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/exporter.py
@@ -0,0 +1,94 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.petri_net.exporter.variants import pnml
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ PNML = pnml
+
+
+PNML = Variants.PNML
+
+
+def apply(
+ net,
+ initial_marking,
+ output_filename,
+ final_marking=None,
+ variant=PNML,
+ parameters=None,
+):
+ """
+ Export a Petri net along with an initial marking (and possibly a final marking) to an output file
+
+ Parameters
+ ------------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ output_filename
+ Output filename
+ final_marking
+ Final marking
+ variant
+ Variant of the algorithm, possible values:
+ - Variants.PNML
+ parameters
+ Parameters of the exporter
+ """
+ return exec_utils.get_variant(variant).export_net(
+ net,
+ initial_marking,
+ output_filename,
+ final_marking=final_marking,
+ parameters=parameters,
+ )
+
+
+def serialize(net, initial_marking, final_marking=None, variant=PNML):
+ """
+ Serialize a Petri net along with an initial marking (and possibly a final marking) to a binary PNML string
+
+ Parameters
+ ------------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ final_marking
+ Final marking
+ variant
+ Variant of the algorithm, possible values:
+ - Variants.PNML
+
+ Returns
+ -------------
+ serialization
+ Binary string (BPMN 2.0 XML standard)
+ """
+ return exec_utils.get_variant(variant).export_petri_as_string(
+ net, initial_marking, final_marking=final_marking
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4ab5d7bfe9c73dba872f45b75befd7ee9e2b981
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.exporter.variants import pnml
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/variants/pnml.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/variants/pnml.py
new file mode 100644
index 0000000000000000000000000000000000000000..276353324a67fb19768c7df37686e3699e858a81
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/exporter/variants/pnml.py
@@ -0,0 +1,392 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import uuid
+
+from lxml import etree
+
+from pm4py.objects.petri_net.obj import Marking
+from pm4py.objects.petri_net.obj import PetriNet, ResetNet, InhibitorNet
+from pm4py.objects.petri_net import properties as petri_properties
+from pm4py.util import constants, exec_utils
+from enum import Enum
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def export_petri_tree(
+ petrinet, marking, final_marking=None, export_prom5=False, parameters=None
+):
+ """
+ Export a Petrinet to a XML tree
+
+ Parameters
+ ----------
+ petrinet: :class:`pm4py.entities.petri.petrinet.PetriNet`
+ Petri net
+ marking: :class:`pm4py.entities.petri.petrinet.Marking`
+ Marking
+ final_marking: :class:`pm4py.entities.petri.petrinet.Marking`
+ Final marking (optional)
+ export_prom5
+ Enables exporting PNML files in a format that is ProM5-friendly
+ parameters
+ Other parameters of the algorithm
+
+ Returns
+ ----------
+ tree
+ XML tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ if final_marking is None:
+ final_marking = Marking()
+
+ root = etree.Element("pnml")
+ net = etree.SubElement(root, "net")
+ net.set("id", petrinet.name)
+ netname = etree.SubElement(net, "name")
+ netnametext = etree.SubElement(netname, "text")
+ netnametext.text = petrinet.name
+ net.set("type", "http://www.pnml.org/version-2009/grammar/pnmlcoremodel")
+ if export_prom5 is True:
+ page = net
+ else:
+ page = etree.SubElement(net, "page")
+ page.set("id", "n0")
+ places_map = {}
+ for place in petrinet.places:
+ places_map[place] = place.name
+ pl = etree.SubElement(page, "place")
+ pl.set("id", place.name)
+ pl_name = etree.SubElement(pl, "name")
+ pl_name_text = etree.SubElement(pl_name, "text")
+ pl_name_text.text = (
+ place.properties[constants.PLACE_NAME_TAG]
+ if constants.PLACE_NAME_TAG in place.properties
+ else place.name
+ )
+ if place in marking:
+ pl_initial_marking = etree.SubElement(pl, "initialMarking")
+ pl_initial_marking_text = etree.SubElement(
+ pl_initial_marking, "text"
+ )
+ pl_initial_marking_text.text = str(marking[place])
+ if constants.LAYOUT_INFORMATION_PETRI in place.properties:
+ graphics = etree.SubElement(pl, "graphics")
+ position = etree.SubElement(graphics, "position")
+ position.set(
+ "x",
+ str(
+ place.properties[constants.LAYOUT_INFORMATION_PETRI][0][0]
+ ),
+ )
+ position.set(
+ "y",
+ str(
+ place.properties[constants.LAYOUT_INFORMATION_PETRI][0][1]
+ ),
+ )
+ dimension = etree.SubElement(graphics, "dimension")
+ dimension.set(
+ "x",
+ str(
+ place.properties[constants.LAYOUT_INFORMATION_PETRI][1][0]
+ ),
+ )
+ dimension.set(
+ "y",
+ str(
+ place.properties[constants.LAYOUT_INFORMATION_PETRI][1][1]
+ ),
+ )
+ transitions_map = {}
+ for transition in petrinet.transitions:
+ transitions_map[transition] = transition.name
+ trans = etree.SubElement(page, "transition")
+ trans.set("id", transition.name)
+ trans_name = etree.SubElement(trans, "name")
+ trans_text = etree.SubElement(trans_name, "text")
+ if constants.LAYOUT_INFORMATION_PETRI in transition.properties:
+ graphics = etree.SubElement(trans, "graphics")
+ position = etree.SubElement(graphics, "position")
+ position.set(
+ "x",
+ str(
+ transition.properties[constants.LAYOUT_INFORMATION_PETRI][
+ 0
+ ][0]
+ ),
+ )
+ position.set(
+ "y",
+ str(
+ transition.properties[constants.LAYOUT_INFORMATION_PETRI][
+ 0
+ ][1]
+ ),
+ )
+ dimension = etree.SubElement(graphics, "dimension")
+ dimension.set(
+ "x",
+ str(
+ transition.properties[constants.LAYOUT_INFORMATION_PETRI][
+ 1
+ ][0]
+ ),
+ )
+ dimension.set(
+ "y",
+ str(
+ transition.properties[constants.LAYOUT_INFORMATION_PETRI][
+ 1
+ ][1]
+ ),
+ )
+ if constants.STOCHASTIC_DISTRIBUTION in transition.properties:
+ random_variable = transition.properties[
+ constants.STOCHASTIC_DISTRIBUTION
+ ]
+ stochastic_information = etree.SubElement(trans, "toolspecific")
+ stochastic_information.set("tool", "StochasticPetriNet")
+ stochastic_information.set("version", "0.2")
+ distribution_type = etree.SubElement(
+ stochastic_information, "property"
+ )
+ distribution_type.set("key", "distributionType")
+ distribution_type.text = random_variable.get_distribution_type()
+ if not random_variable.get_distribution_type() == "IMMEDIATE":
+ distribution_parameters = etree.SubElement(
+ stochastic_information, "property"
+ )
+ distribution_parameters.set("key", "distributionParameters")
+ distribution_parameters.text = (
+ random_variable.get_distribution_parameters()
+ )
+ distribution_priority = etree.SubElement(
+ stochastic_information, "property"
+ )
+ distribution_priority.set("key", "priority")
+ distribution_priority.text = str(random_variable.get_priority())
+ distribution_invisible = etree.SubElement(
+ stochastic_information, "property"
+ )
+ distribution_invisible.set("key", "invisible")
+ distribution_invisible.text = str(
+ True if transition.label is None else False
+ ).lower()
+ distribution_weight = etree.SubElement(
+ stochastic_information, "property"
+ )
+ distribution_weight.set("key", "weight")
+ distribution_weight.text = str(random_variable.get_weight())
+ if transition.label is not None:
+ trans_text.text = transition.label
+ else:
+ trans_text.text = transition.name
+ tool_specific = etree.SubElement(trans, "toolspecific")
+ tool_specific.set("tool", "ProM")
+ tool_specific.set("version", "6.4")
+ tool_specific.set("activity", "$invisible$")
+ tool_specific.set("localNodeID", str(uuid.uuid4()))
+ if export_prom5 is True:
+ if transition.label is not None:
+ prom5_specific = etree.SubElement(trans, "toolspecific")
+ prom5_specific.set("tool", "ProM")
+ prom5_specific.set("version", "5.2")
+ log_event_prom5 = etree.SubElement(prom5_specific, "logevent")
+ event_name = transition.label.split("+")[0]
+ event_transition = (
+ transition.label.split("+")[1]
+ if len(transition.label.split("+")) > 1
+ else "complete"
+ )
+ log_event_prom5_name = etree.SubElement(
+ log_event_prom5, "name"
+ )
+ log_event_prom5_name.text = event_name
+ log_event_prom5_type = etree.SubElement(
+ log_event_prom5, "type"
+ )
+ log_event_prom5_type.text = event_transition
+ # specific for data Petri nets
+ if petri_properties.TRANS_GUARD in transition.properties:
+ trans.set(
+ petri_properties.TRANS_GUARD,
+ transition.properties[petri_properties.TRANS_GUARD],
+ )
+ if petri_properties.READ_VARIABLE in transition.properties:
+ read_variables = transition.properties[
+ petri_properties.READ_VARIABLE
+ ]
+ for rv in read_variables:
+ rv_el = etree.SubElement(trans, petri_properties.READ_VARIABLE)
+ rv_el.text = rv
+ if petri_properties.WRITE_VARIABLE in transition.properties:
+ write_variables = transition.properties[
+ petri_properties.WRITE_VARIABLE
+ ]
+ for wv in write_variables:
+ wv_el = etree.SubElement(
+ trans, petri_properties.WRITE_VARIABLE
+ )
+ wv_el.text = wv
+ for arc in petrinet.arcs:
+ arc_el = etree.SubElement(page, "arc")
+ arc_el.set("id", str(hash(arc)))
+ if type(arc.source) is PetriNet.Place:
+ arc_el.set("source", str(places_map[arc.source]))
+ arc_el.set("target", str(transitions_map[arc.target]))
+ else:
+ arc_el.set("source", str(transitions_map[arc.source]))
+ arc_el.set("target", str(places_map[arc.target]))
+
+ if arc.weight > 1:
+ inscription = etree.SubElement(arc_el, "inscription")
+ arc_weight = etree.SubElement(inscription, "text")
+ arc_weight.text = str(arc.weight)
+
+ if isinstance(arc, ResetNet.ResetArc):
+ element = etree.SubElement(arc_el, petri_properties.ARCTYPE)
+ element_text = etree.SubElement(element, "text")
+ element_text.text = petri_properties.RESET_ARC
+ elif isinstance(arc, InhibitorNet.InhibitorArc):
+ element = etree.SubElement(arc_el, petri_properties.ARCTYPE)
+ element_text = etree.SubElement(element, "text")
+ element_text.text = petri_properties.INHIBITOR_ARC
+
+ for prop_key in arc.properties:
+ if prop_key != petri_properties.ARCTYPE:
+ element = etree.SubElement(arc_el, prop_key)
+ element_text = etree.SubElement(element, "text")
+ element_text.text = str(arc.properties[prop_key])
+
+ if len(final_marking) > 0:
+ finalmarkings = etree.SubElement(net, "finalmarkings")
+ marking = etree.SubElement(finalmarkings, "marking")
+
+ for place in final_marking:
+ placem = etree.SubElement(marking, "place")
+ placem.set("idref", place.name)
+ placem_text = etree.SubElement(placem, "text")
+ placem_text.text = str(final_marking[place])
+
+ # specific for data Petri nets
+ if petri_properties.VARIABLES in petrinet.properties:
+ variables = etree.SubElement(net, "variables")
+ for prop in petrinet.properties[petri_properties.VARIABLES]:
+ variable = etree.SubElement(variables, "variable")
+ variable.set("type", prop["type"])
+ variable_name = etree.SubElement(variable, "name")
+ variable_name.text = prop["name"]
+
+ tree = etree.ElementTree(root)
+
+ return tree
+
+
+def export_petri_as_string(
+ petrinet, marking, final_marking=None, export_prom5=False, parameters=None
+):
+ """
+ Parameters
+ ----------
+ petrinet: :class:`pm4py.entities.petri.petrinet.PetriNet`
+ Petri net
+ marking: :class:`pm4py.entities.petri.petrinet.Marking`
+ Marking
+ final_marking: :class:`pm4py.entities.petri.petrinet.Marking`
+ Final marking (optional)
+ export_prom5
+ Enables exporting PNML files in a format that is ProM5-friendly
+
+ Returns
+ ----------
+ string
+ Petri net as string
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ # gets the XML tree
+ tree = export_petri_tree(
+ petrinet,
+ marking,
+ final_marking=final_marking,
+ export_prom5=export_prom5,
+ )
+
+ # removing default decoding (return binary string as in other parts of the
+ # application)
+ return etree.tostring(tree, xml_declaration=True, encoding=encoding)
+
+
+def export_net(
+ petrinet,
+ marking,
+ output_filename,
+ final_marking=None,
+ export_prom5=False,
+ parameters=None,
+):
+ """
+ Export a Petrinet to a PNML file
+
+ Parameters
+ ----------
+ petrinet: :class:`pm4py.entities.petri.petrinet.PetriNet`
+ Petri net
+ marking: :class:`pm4py.entities.petri.petrinet.Marking`
+ Marking
+ final_marking: :class:`pm4py.entities.petri.petrinet.Marking`
+ Final marking (optional)
+ output_filename:
+ Absolute output file name for saving the pnml file
+ export_prom5
+ Enables exporting PNML files in a format that is ProM5-friendly
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ # gets the XML tree
+ tree = export_petri_tree(
+ petrinet,
+ marking,
+ final_marking=final_marking,
+ export_prom5=export_prom5,
+ )
+
+ # write the tree to a file
+ F = open(output_filename, "wb")
+ tree.write(F, pretty_print=True, xml_declaration=True, encoding=encoding)
+ F.close()
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c129232bd43f34db0b2e0ef2f48910caa87a8dd2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.importer import variants, importer
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8bc68aac9cf9bf2282193f0720dee1cfca00782
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/importer.py
@@ -0,0 +1,70 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.petri_net.importer.variants import pnml
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ PNML = pnml
+
+
+PNML = Variants.PNML
+
+
+def apply(input_file_path, variant=PNML, parameters=None):
+ """
+ Import a Petri net from a PNML file
+
+ Parameters
+ ------------
+ input_file_path
+ Input file path
+ parameters
+ Other parameters of the importer
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.PNML
+ """
+ return exec_utils.get_variant(variant).import_net(
+ input_file_path, parameters=parameters
+ )
+
+
+def deserialize(petri_string, variant=PNML, parameters=None):
+ """
+ Deserialize a text/binary string representing a Petri net in the PNML format
+
+ Parameters
+ ----------
+ petri_string
+ Petri net expressed as PNML string
+ variant
+ Variant of the algorithm to use, possible values:
+ - Variants.PNML
+ parameters
+ Other parameters of the algorithm
+ """
+ return exec_utils.get_variant(variant).import_net_from_string(
+ petri_string, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..11d6ab6aefbcd6c62650993b62c62adc7de1aa38
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.importer.variants import pnml
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/variants/pnml.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/variants/pnml.py
new file mode 100644
index 0000000000000000000000000000000000000000..56ead03653c6fc2cfa144606f1e84a89276dfe5d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/importer/variants/pnml.py
@@ -0,0 +1,463 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import time
+
+from lxml import etree, objectify
+
+from pm4py.objects.petri_net.utils import final_marking
+from pm4py.objects.petri_net.obj import (
+ PetriNet,
+ Marking,
+ ResetNet,
+ InhibitorNet,
+ ResetInhibitorNet,
+)
+from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to
+from pm4py.objects.petri_net import properties as petri_properties
+from pm4py.util import constants, exec_utils
+import warnings
+from enum import Enum
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+ AUTO_GUESS_FINAL_MARKING = "auto_guess_final_marking"
+ RETURN_STOCHASTIC_MAP = "return_stochastic_map"
+
+
+def import_net(input_file_path, parameters=None):
+ """
+ Import a Petri net from a PNML file
+
+ Parameters
+ ----------
+ input_file_path
+ Input file path
+ parameters
+ Other parameters of the algorithm
+
+ Returns
+ -----------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, None
+ )
+
+ parser = etree.XMLParser(remove_comments=True, encoding=encoding)
+
+ F = open(input_file_path, "rb")
+ tree = objectify.parse(F, parser=parser)
+ F.close()
+
+ root = tree.getroot()
+
+ return import_net_from_xml_object(root, parameters=parameters)
+
+
+def import_net_from_string(petri_string, parameters=None):
+ """
+ Imports a Petri net from a string
+
+ Parameters
+ -------------
+ petri_string
+ (Binary) string representing the Petri net
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ if type(petri_string) is str:
+ petri_string = petri_string.encode(constants.DEFAULT_ENCODING)
+
+ parser = etree.XMLParser(remove_comments=True)
+ root = objectify.fromstring(petri_string, parser=parser)
+
+ return import_net_from_xml_object(root, parameters=parameters)
+
+
+def import_net_from_xml_object(root, parameters=None):
+ """
+ Import a Petri net from an etree XML object
+
+ Parameters
+ ----------
+ root
+ Root object of the XML
+ parameters
+ Other parameters of the algorithm:
+ - AUTO_GUESS_FINAL_MARKING: automatic guessing the final marking from the .pnml file
+ """
+ if parameters is None:
+ parameters = {}
+
+ auto_guess_final_marking = exec_utils.get_param_value(
+ Parameters.AUTO_GUESS_FINAL_MARKING, parameters, True
+ )
+ return_stochastic_information = exec_utils.get_param_value(
+ Parameters.RETURN_STOCHASTIC_MAP, parameters, False
+ )
+
+ net = PetriNet("imported_" + str(time.time()))
+ marking = Marking()
+ fmarking = None
+
+ nett = None
+ page = None
+ finalmarkings = None
+ variables = None
+
+ stochastic_map = {}
+
+ for child in root:
+ nett = child
+
+ places_dict = {}
+ trans_dict = {}
+
+ if nett is not None:
+ for child in nett:
+ if "page" in child.tag:
+ page = child
+ if "finalmarkings" in child.tag:
+ finalmarkings = child
+ if "variables" in child.tag:
+ variables = child
+
+ if page is None:
+ page = nett
+
+ if page is not None:
+ for child in page:
+ if "place" in child.tag:
+ position_X = None
+ position_Y = None
+ dimension_X = None
+ dimension_Y = None
+ place_id = child.get("id")
+ place_name = place_id
+ number = 0
+ for child2 in child:
+ if child2.tag.endswith("name"):
+ for child3 in child2:
+ if child3.text:
+ place_name = child3.text
+ if child2.tag.endswith("initialMarking"):
+ for child3 in child2:
+ if child3.tag.endswith("text"):
+ number = int(child3.text)
+ if child2.tag.endswith("graphics"):
+ for child3 in child2:
+ if child3.tag.endswith("position"):
+ position_X = float(child3.get("x"))
+ position_Y = float(child3.get("y"))
+ elif child3.tag.endswith("dimension"):
+ dimension_X = float(child3.get("x"))
+ dimension_Y = float(child3.get("y"))
+ places_dict[place_id] = PetriNet.Place(place_id)
+ places_dict[place_id].properties[
+ constants.PLACE_NAME_TAG
+ ] = place_name
+ net.places.add(places_dict[place_id])
+ if (
+ position_X is not None
+ and position_Y is not None
+ and dimension_X is not None
+ and dimension_Y is not None
+ ):
+ places_dict[place_id].properties[
+ constants.LAYOUT_INFORMATION_PETRI
+ ] = ((position_X, position_Y), (dimension_X, dimension_Y))
+ if number > 0:
+ marking[places_dict[place_id]] = number
+ del place_name
+
+ if page is not None:
+ for child in page:
+ if child.tag.endswith("transition"):
+ position_X = None
+ position_Y = None
+ dimension_X = None
+ dimension_Y = None
+ trans_id = child.get("id")
+ trans_name = trans_id
+ trans_visible = True
+ trans_properties = {}
+ trans_guard = child.get("guard")
+ if trans_guard is not None:
+ trans_properties[petri_properties.TRANS_GUARD] = (
+ trans_guard
+ )
+
+ random_variable = None
+
+ for child2 in child:
+ if child2.tag.endswith("name"):
+ for child3 in child2:
+ if child3.text:
+ if trans_name == trans_id:
+ trans_name = child3.text
+ elif child2.tag.endswith("graphics"):
+ for child3 in child2:
+ if child3.tag.endswith("position"):
+ position_X = float(child3.get("x"))
+ position_Y = float(child3.get("y"))
+ elif child3.tag.endswith("dimension"):
+ dimension_X = float(child3.get("x"))
+ dimension_Y = float(child3.get("y"))
+ elif child2.tag.endswith("toolspecific"):
+ tool = child2.get("tool")
+ if "ProM" in tool:
+ activity = child2.get("activity")
+ if "invisible" in activity:
+ trans_visible = False
+ elif "StochasticPetriNet" in tool:
+ distribution_type = None
+ distribution_parameters = None
+ priority = None
+ weight = None
+
+ for child3 in child2:
+ key = child3.get("key")
+ value = child3.text
+
+ if key == "distributionType":
+ distribution_type = value
+ elif key == "distributionParameters":
+ distribution_parameters = value
+ elif key == "priority":
+ priority = int(value)
+ elif key == "weight":
+ weight = float(value)
+ elif key == "invisible":
+ if value.lower() == "true":
+ trans_visible = False
+
+ from pm4py.objects.random_variables.random_variable import (
+ RandomVariable, )
+
+ random_variable = RandomVariable()
+ random_variable.read_from_string(
+ distribution_type, distribution_parameters
+ )
+ random_variable.set_priority(priority)
+ random_variable.set_weight(weight)
+ elif child2.tag.endswith(petri_properties.WRITE_VARIABLE):
+ # property for data Petri nets
+ if (
+ petri_properties.WRITE_VARIABLE
+ not in trans_properties
+ ):
+ trans_properties[
+ petri_properties.WRITE_VARIABLE
+ ] = []
+ trans_properties[
+ petri_properties.WRITE_VARIABLE
+ ].append(child2.text)
+ elif child2.tag.endswith(petri_properties.READ_VARIABLE):
+ # property for data Petri nets
+ if (
+ petri_properties.READ_VARIABLE
+ not in trans_properties
+ ):
+ trans_properties[
+ petri_properties.READ_VARIABLE
+ ] = []
+ trans_properties[
+ petri_properties.READ_VARIABLE
+ ].append(child2.text)
+
+ # 15/02/2021: the name associated in the PNML to invisible transitions was lost.
+ # at least save that as property.
+ if trans_visible:
+ trans_label = trans_name
+ else:
+ trans_label = None
+
+ trans_dict[trans_id] = PetriNet.Transition(
+ trans_id, trans_label
+ )
+ trans_dict[trans_id].properties[
+ constants.TRANS_NAME_TAG
+ ] = trans_name
+ for prop in trans_properties:
+ trans_dict[trans_id].properties[prop] = trans_properties[
+ prop
+ ]
+ net.transitions.add(trans_dict[trans_id])
+
+ if random_variable is not None:
+ trans_dict[trans_id].properties[
+ constants.STOCHASTIC_DISTRIBUTION
+ ] = random_variable
+ stochastic_map[trans_dict[trans_id]] = random_variable
+
+ if (
+ position_X is not None
+ and position_Y is not None
+ and dimension_X is not None
+ and dimension_Y is not None
+ ):
+ trans_dict[trans_id].properties[
+ constants.LAYOUT_INFORMATION_PETRI
+ ] = ((position_X, position_Y), (dimension_X, dimension_Y))
+
+ if page is not None:
+ for child in page:
+ if child.tag.endswith("arc"):
+ arc_source = child.get("source")
+ arc_target = child.get("target")
+ arc_weight = 1
+ arc_type = None
+ arc_properties = {}
+
+ for arc_child in child:
+ if arc_child.tag.endswith("inscription"):
+ for text_element in arc_child:
+ if text_element.tag.endswith("text"):
+ arc_weight = int(text_element.text)
+ elif arc_child.tag.endswith(petri_properties.ARCTYPE):
+ for text_element in arc_child:
+ if text_element.tag.endswith("text"):
+ arc_type = text_element.text
+
+ if arc_source in places_dict and arc_target in trans_dict:
+ if (
+ arc_type == petri_properties.INHIBITOR_ARC
+ and not isinstance(net, InhibitorNet)
+ ):
+ if isinstance(net, ResetNet):
+ net = ResetInhibitorNet(
+ name=net.name,
+ places=net.places,
+ transitions=net.transitions,
+ arcs=net.arcs,
+ properties=net.properties,
+ )
+ else:
+ net = InhibitorNet(
+ name=net.name,
+ places=net.places,
+ transitions=net.transitions,
+ arcs=net.arcs,
+ properties=net.properties,
+ )
+ if (
+ arc_type == petri_properties.RESET_ARC
+ and not isinstance(net, ResetNet)
+ ):
+ if isinstance(net, InhibitorNet):
+ net = ResetInhibitorNet(
+ name=net.name,
+ places=net.places,
+ transitions=net.transitions,
+ arcs=net.arcs,
+ properties=net.properties,
+ )
+ else:
+ net = ResetNet(
+ name=net.name,
+ places=net.places,
+ transitions=net.transitions,
+ arcs=net.arcs,
+ properties=net.properties,
+ )
+ a = add_arc_from_to(
+ places_dict[arc_source],
+ trans_dict[arc_target],
+ net,
+ weight=arc_weight,
+ type=arc_type,
+ )
+ for prop in arc_properties:
+ a.properties[prop] = arc_properties[prop]
+ elif arc_target in places_dict and arc_source in trans_dict:
+ a = add_arc_from_to(
+ trans_dict[arc_source],
+ places_dict[arc_target],
+ net,
+ weight=arc_weight,
+ type=arc_type,
+ )
+ for prop in arc_properties:
+ a.properties[prop] = arc_properties[prop]
+
+ if finalmarkings is not None:
+ fmarking = Marking()
+ for child in finalmarkings:
+ for child2 in child:
+ place_id = child2.get("idref")
+ for child3 in child2:
+ if child3.tag.endswith("text"):
+ number = int(child3.text)
+ if number > 0:
+ fmarking[places_dict[place_id]] = number
+
+ if variables is not None:
+ net.properties[petri_properties.VARIABLES] = []
+ for child in variables:
+ variable_type = child.get("type")
+ variable_name = ""
+ for child2 in child:
+ if child2.tag.endswith("name"):
+ variable_name = child2.text
+ net.properties[petri_properties.VARIABLES].append(
+ {"type": variable_type, "name": variable_name}
+ )
+
+ if fmarking is None:
+ if auto_guess_final_marking:
+ # generate the final marking in the case has not been found
+ fmarking = final_marking.discover_final_marking(net)
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "the Petri net has been imported without a specified final marking. Please create it using the method pm4py.generate_marking"
+ )
+
+ if return_stochastic_information:
+ return net, marking, fmarking, stochastic_map
+
+ return net, marking, fmarking
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/inhibitor_reset/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/inhibitor_reset/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/inhibitor_reset/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/inhibitor_reset/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/inhibitor_reset/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e8ef9548dbf76ffd455c5e4a7bda6321c35d8d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/inhibitor_reset/semantics.py
@@ -0,0 +1,156 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+from pm4py.objects.petri_net.sem_interface import Semantics
+from pm4py.objects.petri_net.obj import ResetNet
+from pm4py.objects.petri_net.obj import InhibitorNet
+
+
+class InhibitorResetSemantics(Semantics):
+ def is_enabled(self, t, pn, m, **kwargs):
+ """
+ Verifies whether a given transition is enabled in a given Petri net and marking
+
+ Parameters
+ ----------
+ :param t: transition to check
+ :param pn: Petri net
+ :param m: marking to check
+
+ Returns
+ -------
+ :return: true if enabled, false otherwise
+ """
+ return is_enabled(t, pn, m)
+
+ def execute(self, t, pn, m, **kwargs):
+ """
+ Executes a given transition in a given Petri net and Marking
+
+ Parameters
+ ----------
+ :param t: transition to execute
+ :param pn: Petri net
+ :param m: marking to use
+
+ Returns
+ -------
+ :return: newly reached marking if :param t: is enabled, None otherwise
+ """
+ return execute(t, pn, m)
+
+ def weak_execute(self, t, pn, m, **kwargs):
+ """
+ Execute a transition even if it is not fully enabled
+
+ Parameters
+ ----------
+ :param t: transition to execute
+ :param pn: Petri net
+ :param m: marking to use
+
+ Returns
+ -------
+ :return: newly reached marking if :param t: is enabled, None otherwise
+ """
+ return weak_execute(t, m)
+
+ def enabled_transitions(self, pn, m, **kwargs):
+ """
+ Returns a set of enabled transitions in a Petri net and given marking
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param m: marking of the pn
+
+ Returns
+ -------
+ :return: set of enabled transitions
+ """
+ return enabled_transitions(pn, m)
+
+
+# 29/08/2021: the following methods have been incapsulated in the InhibitorResetSemantics class.
+# the long term idea is to remove them. However, first we need to adapt the existing code to the new
+# structure. Moreover, for performance reason, it is better to leave the code here, without having
+# to instantiate a InhibitorResetSemantics object.
+def is_enabled(t, pn, m):
+ if t not in pn.transitions:
+ return False
+ else:
+ for a in t.in_arcs:
+ if isinstance(a, InhibitorNet.InhibitorArc):
+ if m[a.source] > 0:
+ return False
+ elif isinstance(a, ResetNet.ResetArc):
+ pass
+ elif m[a.source] < a.weight:
+ return False
+ return True
+
+
+def execute(t, pn, m):
+ if not is_enabled(t, pn, m):
+ return None
+
+ m_out = copy.copy(m)
+ for a in t.in_arcs:
+ if isinstance(a, ResetNet.ResetArc):
+ m_out[a.source] = 0
+ del m_out[a.source]
+ elif isinstance(a, InhibitorNet.InhibitorArc):
+ pass
+ else:
+ m_out[a.source] -= a.weight
+ if m_out[a.source] == 0:
+ del m_out[a.source]
+
+ for a in t.out_arcs:
+ m_out[a.target] += a.weight
+
+ return m_out
+
+
+def weak_execute(t, m):
+ m_out = copy.copy(m)
+ for a in t.in_arcs:
+ if isinstance(a, ResetNet.ResetArc):
+ m_out[a.source] = 0
+ del m_out[a.source]
+ elif isinstance(a, InhibitorNet.InhibitorArc):
+ pass
+ else:
+ m_out[a.source] -= a.weight
+ if m_out[a.source] <= 0:
+ del m_out[a.source]
+ for a in t.out_arcs:
+ m_out[a.target] += a.weight
+ return m_out
+
+
+def enabled_transitions(pn, m):
+ enabled = set()
+ for t in pn.transitions:
+ if is_enabled(t, pn, m):
+ enabled.add(t)
+ return enabled
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaeb9aff94df4697e169f028d93ca875cdd9fbcf
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/obj.py
@@ -0,0 +1,461 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections import Counter
+from copy import deepcopy
+from typing import Any, Collection, Dict
+
+
+class Marking(Counter):
+ pass
+
+ def __hash__(self):
+ return frozenset(self).__hash__() # credits egrocha
+
+ def __eq__(self, other):
+ if not self.keys() == other.keys():
+ return False
+ for p in self.keys():
+ if other.get(p) != self.get(p):
+ return False
+ return True
+
+ def __le__(self, other):
+ if not self.keys() <= other.keys():
+ return False
+ for p in self.keys():
+ if other.get(p) < self.get(p):
+ return False
+ return True
+
+ def __add__(self, other):
+ m = Marking()
+ for p in self.items():
+ m[p[0]] = p[1]
+ for p in other.items():
+ m[p[0]] += p[1]
+ return m
+
+ def __sub__(self, other):
+ m = Marking()
+ for p in self.items():
+ m[p[0]] = p[1]
+ for p in other.items():
+ m[p[0]] -= p[1]
+ if m[p[0]] == 0:
+ del m[p[0]]
+ return m
+
+ def __repr__(self):
+ return str(
+ [
+ str(p.name) + ":" + str(self.get(p))
+ for p in sorted(list(self.keys()), key=lambda x: x.name)
+ ]
+ )
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __deepcopy__(self, memodict={}):
+ marking = Marking()
+ memodict[id(self)] = marking
+ for place in self:
+ place_occ = self[place]
+ new_place = (
+ memodict[id(place)]
+ if id(place) in memodict
+ else PetriNet.Place(place.name, properties=place.properties)
+ )
+ marking[new_place] = place_occ
+ return marking
+
+
+class PetriNet(object):
+ class Place(object):
+
+ def __init__(self, name, in_arcs=None, out_arcs=None, properties=None):
+ self.__name = name
+ self.__in_arcs = set() if in_arcs is None else in_arcs
+ self.__out_arcs = set() if out_arcs is None else out_arcs
+ self.__properties = dict() if properties is None else properties
+
+ def __set_name(self, name):
+ self.__name = name
+
+ def __get_name(self):
+ return self.__name
+
+ def __get_out_arcs(self):
+ return self.__out_arcs
+
+ def __get_in_arcs(self):
+ return self.__in_arcs
+
+ def __get_properties(self):
+ return self.__properties
+
+ def __repr__(self):
+ return str(self.name)
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __eq__(self, other):
+ # keep the ID for now in places
+ return id(self) == id(other)
+
+ def __hash__(self):
+ # keep the ID for now in places
+ return id(self)
+
+ def __deepcopy__(self, memodict={}):
+ if id(self) in memodict:
+ return memodict[id(self)]
+ new_place = PetriNet.Place(self.name, properties=self.properties)
+ memodict[id(self)] = new_place
+ for arc in self.in_arcs:
+ new_arc = deepcopy(arc, memo=memodict)
+ new_place.in_arcs.add(new_arc)
+ for arc in self.out_arcs:
+ new_arc = deepcopy(arc, memo=memodict)
+ new_place.out_arcs.add(new_arc)
+ return new_place
+
+ name = property(__get_name, __set_name)
+ in_arcs = property(__get_in_arcs)
+ out_arcs = property(__get_out_arcs)
+ properties = property(__get_properties)
+
+ class Transition(object):
+
+ def __init__(
+ self,
+ name,
+ label=None,
+ in_arcs=None,
+ out_arcs=None,
+ properties=None,
+ ):
+ self.__name = name
+ self.__label = None if label is None else label
+ self.__in_arcs = set() if in_arcs is None else in_arcs
+ self.__out_arcs = set() if out_arcs is None else out_arcs
+ self.__properties = dict() if properties is None else properties
+
+ def __set_name(self, name):
+ self.__name = name
+
+ def __get_name(self):
+ return self.__name
+
+ def __set_label(self, label):
+ self.__label = label
+
+ def __get_label(self):
+ return self.__label
+
+ def __get_out_arcs(self):
+ return self.__out_arcs
+
+ def __get_in_arcs(self):
+ return self.__in_arcs
+
+ def __get_properties(self):
+ return self.__properties
+
+ def __repr__(self):
+ if self.label is None:
+ return "(" + str(self.name) + ", None)"
+ else:
+ return "(" + str(self.name) + ", '" + str(self.label) + "')"
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __eq__(self, other):
+ # keep the ID for now in transitions
+ return id(self) == id(other)
+
+ def __hash__(self):
+ # keep the ID for now in transitions
+ return id(self)
+
+ def __deepcopy__(self, memodict={}):
+ if id(self) in memodict:
+ return memodict[id(self)]
+ new_trans = PetriNet.Transition(
+ self.name, self.label, properties=self.properties
+ )
+ memodict[id(self)] = new_trans
+ for arc in self.in_arcs:
+ new_arc = deepcopy(arc, memo=memodict)
+ new_trans.in_arcs.add(new_arc)
+ for arc in self.out_arcs:
+ new_arc = deepcopy(arc, memo=memodict)
+ new_trans.out_arcs.add(new_arc)
+ return new_trans
+
+ name = property(__get_name, __set_name)
+ label = property(__get_label, __set_label)
+ in_arcs = property(__get_in_arcs)
+ out_arcs = property(__get_out_arcs)
+ properties = property(__get_properties)
+
+ class Arc(object):
+
+ def __init__(self, source, target, weight=1, properties=None):
+ if type(source) is type(target):
+ raise Exception("Petri nets are bipartite graphs!")
+ self.__source = source
+ self.__target = target
+ self.__weight = weight
+ self.__properties = dict() if properties is None else properties
+
+ def __get_source(self):
+ return self.__source
+
+ def __get_target(self):
+ return self.__target
+
+ def __set_weight(self, weight):
+ self.__weight = weight
+
+ def __get_weight(self):
+ return self.__weight
+
+ def __get_properties(self):
+ return self.__properties
+
+ def __repr__(self):
+ source_rep = repr(self.source)
+ target_rep = repr(self.target)
+ return source_rep + "->" + target_rep
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __hash__(self):
+ return id(self)
+
+ def __eq__(self, other):
+ return self.source == other.source and self.target == other.target
+
+ def __deepcopy__(self, memodict={}):
+ if id(self) in memodict:
+ return memodict[id(self)]
+ new_source = (
+ memodict[id(self.source)]
+ if id(self.source) in memodict
+ else deepcopy(self.source, memo=memodict)
+ )
+ new_target = (
+ memodict[id(self.target)]
+ if id(self.target) in memodict
+ else deepcopy(self.target, memo=memodict)
+ )
+ memodict[id(self.source)] = new_source
+ memodict[id(self.target)] = new_target
+ new_arc = PetriNet.Arc(
+ new_source,
+ new_target,
+ weight=self.weight,
+ properties=self.properties,
+ )
+ memodict[id(self)] = new_arc
+ return new_arc
+
+ source = property(__get_source)
+ target = property(__get_target)
+ weight = property(__get_weight, __set_weight)
+ properties = property(__get_properties)
+
+ def __init__(
+ self,
+ name: str = None,
+ places: Collection[Place] = None,
+ transitions: Collection[Transition] = None,
+ arcs: Collection[Arc] = None,
+ properties: Dict[str, Any] = None,
+ ):
+ self.__name = "" if name is None else name
+ self.__places = set() if places is None else places
+ self.__transitions = set() if transitions is None else transitions
+ self.__arcs = set() if arcs is None else arcs
+ self.__properties = dict() if properties is None else properties
+
+ def __get_name(self) -> str:
+ return self.__name
+
+ def __set_name(self, name):
+ self.__name = name
+
+ def __get_places(self) -> Collection[Place]:
+ return self.__places
+
+ def __get_transitions(self) -> Collection[Transition]:
+ return self.__transitions
+
+ def __get_arcs(self) -> Collection[Arc]:
+ return self.__arcs
+
+ def __get_properties(self) -> Dict[str, Any]:
+ return self.__properties
+
+ def __hash__(self):
+ ret = 0
+ for p in self.places:
+ ret += hash(p)
+ ret = ret % 479001599
+ for t in self.transitions:
+ ret += hash(t)
+ ret = ret % 479001599
+ return ret
+
+ def __eq__(self, other):
+ # for the Petri net equality keep the ID for now
+ return id(self) == id(other)
+
+ def __deepcopy__(self, memodict={}):
+ from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to
+
+ this_copy = PetriNet(self.name)
+ memodict[id(self)] = this_copy
+ for place in self.places:
+ place_copy = PetriNet.Place(
+ place.name, properties=place.properties
+ )
+ this_copy.places.add(place_copy)
+ memodict[id(place)] = place_copy
+ for trans in self.transitions:
+ trans_copy = PetriNet.Transition(
+ trans.name, trans.label, properties=trans.properties
+ )
+ this_copy.transitions.add(trans_copy)
+ memodict[id(trans)] = trans_copy
+ for arc in self.arcs:
+ add_arc_from_to(
+ memodict[id(arc.source)],
+ memodict[id(arc.target)],
+ this_copy,
+ weight=arc.weight,
+ )
+ return this_copy
+
+ def __repr__(self):
+ ret = ["places: ["]
+ places_rep = []
+ for place in self.places:
+ places_rep.append(repr(place))
+ places_rep.sort()
+ ret.append(" " + ", ".join(places_rep) + " ")
+ ret.append("]\ntransitions: [")
+ trans_rep = []
+ for trans in self.transitions:
+ trans_rep.append(repr(trans))
+ trans_rep.sort()
+ ret.append(" " + ", ".join(trans_rep) + " ")
+ ret.append("]\narcs: [")
+ arcs_rep = []
+ for arc in self.arcs:
+ arcs_rep.append(repr(arc))
+ arcs_rep.sort()
+ ret.append(" " + ", ".join(arcs_rep) + " ")
+ ret.append("]")
+ return "".join(ret)
+
+ def __str__(self):
+ return self.__repr__()
+
+ name = property(__get_name, __set_name)
+ places = property(__get_places)
+ transitions = property(__get_transitions)
+ arcs = property(__get_arcs)
+ properties = property(__get_properties)
+
+
+class InhibitorNet(PetriNet):
+ def __init__(
+ self,
+ name=None,
+ places=None,
+ transitions=None,
+ arcs=None,
+ properties=None,
+ ):
+ PetriNet.__init__(
+ self,
+ name=name,
+ places=places,
+ transitions=transitions,
+ arcs=arcs,
+ properties=properties,
+ )
+
+ class InhibitorArc(PetriNet.Arc):
+ def __init__(self, source, target, weight=1, properties=None):
+ PetriNet.Arc.__init__(
+ self, source, target, weight=weight, properties=properties
+ )
+
+
+class ResetNet(PetriNet):
+ def __init__(
+ self,
+ name=None,
+ places=None,
+ transitions=None,
+ arcs=None,
+ properties=None,
+ ):
+ PetriNet.__init__(
+ self,
+ name=name,
+ places=places,
+ transitions=transitions,
+ arcs=arcs,
+ properties=properties,
+ )
+
+ class ResetArc(PetriNet.Arc):
+ def __init__(self, source, target, weight=1, properties=None):
+ PetriNet.Arc.__init__(
+ self, source, target, weight=weight, properties=properties
+ )
+
+
+class ResetInhibitorNet(InhibitorNet, ResetNet):
+ def __init__(
+ self,
+ name=None,
+ places=None,
+ transitions=None,
+ arcs=None,
+ properties=None,
+ ):
+ PetriNet.__init__(
+ self,
+ name=name,
+ places=places,
+ transitions=transitions,
+ arcs=arcs,
+ properties=properties,
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/properties.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/properties.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5a05cc3b19014154ed4ed7bc6e4539d01d42009
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/properties.py
@@ -0,0 +1,38 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+# list of properties that can be associated to a Petri net or its entities
+
+
+# distinguish Petri nets that are synchronous product nets
+IS_SYNC_NET = "is_sync_net"
+TRACE_NET_TRANS_INDEX = "trace_net_trans_index"
+TRACE_NET_PLACE_INDEX = "trace_net_place_index"
+
+ARCTYPE = "arctype"
+INHIBITOR_ARC = "inhibitor"
+RESET_ARC = "reset"
+STOCHASTIC_ARC = "stochastic_arc"
+
+TRANS_GUARD = "guard"
+WRITE_VARIABLE = "writeVariable"
+READ_VARIABLE = "readVariable"
+VARIABLES = "variables"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c27689c11cfd030d7633f94f9b8345b9b400a71
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/__init__.py
@@ -0,0 +1,23 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.petri_net.saw_net import obj, semantics, convert
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/convert.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b437c663560f3dbf7da28096de3dfe8e56133a0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/convert.py
@@ -0,0 +1,142 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.petri_net.saw_net.obj import StochasticArcWeightNet
+from pm4py.objects.petri_net.stochastic.obj import StochasticPetriNet
+from pm4py.objects.petri_net.saw_net.semantics import (
+ GlobalStochasticArcWeightNetSemantics as sawsem_global,
+ LocalStochasticArcWeightNetSemantics as sawsem_local,
+)
+from typing import Counter as TCounter, Tuple
+from collections import deque
+
+
+def convert_saw_net_to_stochastic_net_global_semantics(
+ saw: StochasticArcWeightNet,
+) -> StochasticPetriNet:
+ sn = StochasticPetriNet()
+ p_map = dict()
+ for p in saw.places:
+ p_new = StochasticPetriNet.Place(p.name, properties=p.properties)
+ sn.places.add(p_new)
+ p_map[p] = p_new
+
+ a_sums = dict()
+ for a in saw.arcs:
+ a_sums[a] = 0
+ for w, v in a.weight_distribution.items():
+ a_sums[a] = a_sums[a] + v
+
+ for t in saw.transitions:
+ bindings = sawsem_global.all_legal_bindings(saw, t)
+ for b in bindings:
+ transition_weight = t.weight
+ t_new = StochasticPetriNet.Transition(
+ "t" + str(len(sn.transitions)), t.label
+ )
+ sn.transitions.add(t_new)
+ for a, w in b:
+ a_new = (
+ StochasticPetriNet.Arc(t_new, p_map[a.target], w)
+ if a.source == t
+ else StochasticPetriNet.Arc(p_map[a.source], t_new, w)
+ )
+ if a.source == t:
+ t_new.out_arcs.add(a_new)
+ p_map[a.target].in_arcs.add(a_new)
+ else:
+ t_new.in_arcs.add(a_new)
+ p_map[a.source].out_arcs.add(a_new)
+ sn.arcs.add(a_new)
+ transition_weight = transition_weight * (
+ a.weight_distribution[w] / a_sums[a]
+ )
+ t_new.weight = transition_weight
+ return sn, p_map
+
+
+def convert_saw_net_to_stochastic_net_local_semantics(
+ saw: StochasticArcWeightNet,
+ marking: TCounter[StochasticArcWeightNet.Place],
+) -> Tuple[StochasticPetriNet, TCounter[StochasticArcWeightNet.Place]]:
+ sn = StochasticPetriNet()
+ open = deque()
+ closed = set()
+ markings = dict()
+ markings[marking] = {
+ p: StochasticPetriNet.Place(p.name + "-" + str(marking))
+ for p in marking
+ if marking[p] > 0
+ }
+ for p in markings[marking]:
+ sn.places.add(markings[marking][p])
+ open.append(marking)
+ while len(open) > 0:
+ m = open.pop()
+ for t in saw.transitions:
+ if sawsem_local.is_enabled(saw, t, m):
+ for b in sawsem_local.all_enabled_bindings(saw, t, m):
+ m_out = sawsem_local.fire(saw, b, m)
+ if m_out not in markings:
+ markings[m_out] = {
+ p: StochasticPetriNet.Place(
+ p.name + "-" + str(m_out)
+ )
+ for p in m_out
+ if m_out[p] > 0
+ }
+ for p in markings[m_out]:
+ sn.places.add(markings[m_out][p])
+ t_new = StochasticPetriNet.Transition(
+ t.name + "-" + str(b),
+ t.label,
+ weight=t.weight
+ * sawsem_local.amortized_priority(b)
+ / sum(
+ [
+ sawsem_local.amortized_priority(bb)
+ for bb in sawsem_local.all_enabled_bindings(
+ saw, t, m
+ )
+ ]
+ ),
+ )
+ sn.transitions.add(t_new)
+ plcs_in = markings[m]
+ plcs_out = markings[m_out]
+ for p in m:
+ if m[p] > 0:
+ a = StochasticPetriNet.Arc(plcs_in[p], t_new, m[p])
+ plcs_in[p].out_arcs.add(a)
+ t_new.in_arcs.add(a)
+ sn.arcs.add(a)
+ for p in m_out:
+ if m_out[p] > 0:
+ a = StochasticPetriNet.Arc(
+ t_new, plcs_out[p], m_out[p]
+ )
+ plcs_out[p].in_arcs.add(a)
+ t_new.out_arcs.add(a)
+ sn.arcs.add(a)
+ if m_out not in closed and m_out is not m:
+ open.append(m_out)
+ return sn, {markings[marking][p]: marking[p] for p in marking}
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..36216a0abf113331e687697701e0292357d6ac7e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/obj.py
@@ -0,0 +1,43 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Dict, List, Tuple
+from pm4py.objects.petri_net.stochastic.obj import StochasticPetriNet
+
+
+class StochasticArcWeightNet(StochasticPetriNet):
+ """
+ Petri nets with stochastic arc weights. Arcs are assumed to desribe distributions of token consumption/production.
+ We utilize the weight attribute that is defined in the Petri net based class to store the distribution.
+ """
+
+ class Arc(StochasticPetriNet.Arc):
+
+ def __init__(self, source, target, weight={1: 1.0}, properties=None):
+ super().__init__(source, target, weight, properties)
+
+ def __get_weight_distribution(self) -> Dict[int, float]:
+ return self.weight
+
+ weight_distribution = property(__get_weight_distribution)
+
+ Binding = List[Tuple[Arc, int]]
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbb9c1c8005c209bbfb1ed109e627ca40eee2962
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/saw_net/semantics.py
@@ -0,0 +1,367 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import copy
+import itertools
+import random
+from abc import ABC, abstractclassmethod
+from collections import Counter
+from typing import Counter as TCounter
+from typing import Generic, List, Optional, Tuple, TypeVar
+
+from pm4py.objects.petri_net.saw_net.obj import StochasticArcWeightNet
+from pm4py.objects.petri_net.stochastic.semantics import (
+ StochasticPetriNetSemantics,
+)
+
+N = TypeVar("N", bound=StochasticArcWeightNet)
+T = TypeVar("T", bound=StochasticArcWeightNet.Transition)
+P = TypeVar("P", bound=StochasticArcWeightNet.Place)
+A = TypeVar("A", bound=StochasticArcWeightNet.Arc)
+B = TypeVar("B", bound=StochasticArcWeightNet.Binding)
+
+
+class StochasticArcWeightNetSemantics(
+ StochasticPetriNetSemantics[N], Generic[N], ABC
+):
+
+ @classmethod
+ def is_enabled(cls, pn: N, transition: T, marking: TCounter[P]) -> bool:
+ """
+ Checks whether a given transition is enabled in a given Petri net and marking.
+ Every place should at least have the same number of tokens as the minimum binding that has a weight above 0
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param transition: transition to check
+ :param marking: marking to check
+
+ Returns
+ -------
+ :return: true if enabled, false otherwise
+ """
+ if transition not in pn.transitions:
+ return False
+ for a in transition.in_arcs:
+ if marking[a.source] < min(
+ [k for k, v in a.weight_distribution.items() if v > 0]
+ ):
+ return False
+ return True
+
+ @classmethod
+ def fire(cls, pn: N, binding: B, marking: TCounter[P]) -> TCounter[P]:
+ """fires the binding in the given marking. Does not check if the the binding is feasible (this should be handled by the invoking code)
+
+ Args:
+ pn (N): saw net to use
+ marking (TCounter[P]): marking to use
+ binding (B): binding to use
+
+ Returns:
+ TCounter[P]: _description_
+ """
+ m_out = copy.copy(marking)
+ for a, w in binding:
+ if isinstance(a.source, StochasticArcWeightNet.Place):
+ m_out[a.source] -= w
+ else:
+ m_out[a.target] += w
+ return m_out
+
+ @classmethod
+ def all_legal_bindings(
+ cls, pn: N, transition: T
+ ) -> List[List[Tuple[A, int]]]:
+ """
+ Creates all possible bindings for a given input transition
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param transition: transition to genereate all bindings for
+
+ Returns
+ -------
+ :return: list containing all posible bindings
+ """
+ if transition not in pn.transitions:
+ return []
+ else:
+ l = list()
+ for a in transition.in_arcs:
+ l.append(
+ [(a, k) for k, v in a.weight_distribution.items() if v > 0]
+ )
+ for a in transition.out_arcs:
+ l.append(
+ [(a, k) for k, v in a.weight_distribution.items() if v > 0]
+ )
+ return list(itertools.product(*l))
+
+ @classmethod
+ def all_enabled_bindings(
+ cls, pn: N, transition: T, marking: TCounter[P]
+ ) -> List[List[Tuple[A, int]]]:
+ """
+ Creates all possible feasible bindings for a given input transition in a given marking
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param marking: marking to use
+ :param transition: transition to genereate all feasible bindings for
+
+ Returns
+ -------
+ :return: list containing all posible feasible bindings
+ """
+ return list(
+ filter(
+ lambda b: cls.is_enabled_binding(pn, transition, b, marking),
+ cls.all_legal_bindings(pn, transition),
+ )
+ )
+
+ @classmethod
+ def is_enabled_binding(
+ cls,
+ pn: N,
+ transition: T,
+ binding: StochasticArcWeightNet.Binding,
+ marking: TCounter[P],
+ ) -> bool:
+ """
+ Checks if the provided binding is enabled
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param marking: marking to use
+ :param transition: transition to genereate all feasible bindings for
+
+ Returns
+ -------
+ :return: bool indicates if the binding is enabled
+ """
+ if transition not in pn.transitions:
+ return False
+ places_in_bindings = set(
+ filter(
+ lambda x: isinstance(x, StochasticArcWeightNet.Place),
+ [
+ x
+ for x in list(
+ itertools.chain(
+ *[(a.source, a.target) for (a, w) in binding]
+ )
+ )
+ ],
+ )
+ )
+ for a in transition.in_arcs:
+ if a.source not in places_in_bindings:
+ return False
+ for a in transition.out_arcs:
+ if a.target not in places_in_bindings:
+ return False
+ for a, w in binding:
+ if a.weight_distribution[w] == 0.0:
+ return False
+ if transition not in {a.source, a.target}:
+ return False
+ if transition == a.target:
+ if w > marking[a.source]:
+ return False
+ return True
+
+ @classmethod
+ def amortized_priority(
+ cls, binding: StochasticArcWeightNet.Binding
+ ) -> float:
+ """
+ Computes the amortized priority (a.k.a weight) of a binding. The amortized priority is equal to the product of all individual weights of the arc weights includec in the binding.
+
+ Args:
+ binding (StochasticArcWeightNet.Binding): input binding
+
+ Returns:
+ float: amortized weight
+ """
+ prod = 1
+ for a, w in binding:
+ prod *= a.weight_distribution[w]
+ return prod
+
+ @abstractclassmethod
+ def probability_of_binding(
+ cls,
+ pn: N,
+ transition: T,
+ binding: StochasticArcWeightNet.Binding,
+ marking: TCounter[P],
+ ) -> float:
+ """
+ Calculates the probability of firing a transition t under binding b in the net, in the given marking.
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param transition: transition to fire
+ :param binding: binding to consider
+ :param marking: marking to use
+
+ Returns
+ -------
+ :return: firing probability of transition t under binding b
+ """
+ pass
+
+
+class LocalStochasticArcWeightNetSemantics(
+ StochasticArcWeightNetSemantics[N], Generic[N]
+):
+
+ @classmethod
+ def probability_of_binding(
+ cls,
+ pn: N,
+ transition: T,
+ binding: StochasticArcWeightNet.Binding,
+ marking: TCounter[P],
+ ) -> float:
+ """
+ Calculates the probability of firing a transition t under binding b in the net, in the given marking.
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param transition: transition to fire
+ :param binding: binding to consider
+ :param marking: marking to use
+
+ Returns
+ -------
+ :return: firing probability of transition t under binding b
+ """
+ s = 0
+ for t in pn.transitions:
+ if cls.is_enabled(pn, t, marking):
+ for b in cls.all_enabled_bindings(pn, transition, marking):
+ s += t.weight * cls.amortized_priority(b)
+
+ print(cls.amortized_priority(binding))
+ return transition.weight * cls.amortized_priority(binding) / s
+
+
+class GlobalStochasticArcWeightNetSemantics(
+ StochasticArcWeightNetSemantics[N], Generic[N]
+):
+
+ @classmethod
+ def probability_of_transition(
+ cls, pn: N, transition: T, marking: TCounter[P]
+ ) -> float:
+ """
+ Compute the probability of firing a transition in the net and marking.
+
+ Args:
+ pn (N): Stochastic net
+ transition (T): transition to fire
+ marking (Counter[P]): marking to use
+
+ Returns:
+ float: _description_
+ """
+ return (
+ 0.0
+ if transition not in pn.transitions
+ or not cls.is_enabled(pn, transition, marking)
+ else sum(
+ [
+ transition.weight * cls.amortized_priority(b)
+ for b in cls.all_enabled_bindings(pn, transition, marking)
+ ]
+ )
+ / sum(
+ [
+ t.weight * cls.amortized_priority(b)
+ for t in pn.transitions
+ if cls.is_enabled(pn, t, marking)
+ for b in cls.all_enabled_bindings(pn, t, marking)
+ ]
+ )
+ )
+
+ @classmethod
+ def sample_enabled_transition(
+ cls, pn: N, marking: TCounter[P], seed: int = None
+ ) -> Optional[Tuple[T, B]]:
+ if seed is not None:
+ random.seed(seed)
+ bindings = list()
+ probs = list()
+ for t in [t for t in pn.transitions if cls.is_enabled(pn, t, marking)]:
+ for b in cls.all_enabled_bindings(pn, t, marking):
+ bindings.append((t, b))
+ probs.append(cls.probability_of_binding(pn, t, b, marking))
+ return (
+ None if len(bindings) == 0 else random.choices(bindings, probs)[0]
+ )
+
+ @classmethod
+ def probability_of_binding(
+ cls,
+ pn: N,
+ transition: T,
+ binding: StochasticArcWeightNet.Binding,
+ marking: TCounter[P],
+ ) -> float:
+ """
+ Calculates the probability of firing a transition t under binding b in the net, in the given marking.
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param transition: transition to fire
+ :param binding: binding to consider
+ :param marking: marking to use
+
+ Returns
+ -------
+ :return: firing probability of transition t under binding b
+ """
+ return (
+ 0.0
+ if transition not in pn.transitions
+ or not cls.is_enabled_binding(pn, transition, binding, marking)
+ else (transition.weight * cls.amortized_priority(binding))
+ / sum(
+ [
+ t.weight * cls.amortized_priority(b)
+ for t in pn.transitions
+ if cls.is_enabled(pn, t, marking)
+ for b in cls.all_enabled_bindings(pn, t, marking)
+ ]
+ )
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/sem_interface.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/sem_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..d46310168f0adf9d34237284dedb2dda3ce6d70a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/sem_interface.py
@@ -0,0 +1,54 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import deprecation
+
+
+class Semantics(object):
+ @deprecation.deprecated(
+ "2.3.0",
+ "3.0.0",
+ details="this method will be removed, use PetriNetSemantics.is_enabled() instead",
+ )
+ def is_enabled(self, t, pn, m, **kwargs):
+ pass
+
+ @deprecation.deprecated(
+ "2.3.0",
+ "3.0.0",
+ details="this method will be removed, use PetriNetSemantics.fire() instead",
+ )
+ def execute(self, t, pn, m, **kwargs):
+ pass
+
+ @deprecation.deprecated(
+ "2.3.0",
+ "3.0.0",
+ details="this method will be removed, use PetriNetSemantics.fire() instead",
+ )
+ def weak_execute(self, t, pn, m, **kwargs):
+ pass
+
+ @deprecation.deprecated(
+ "2.3.0", "3.0.0", details="this method will be removed"
+ )
+ def enabled_transitions(self, pn, m, **kwargs):
+ pass
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8101785c72a7305e4b3488838575cd4cbebceed
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/semantics.py
@@ -0,0 +1,188 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+from typing import Counter, Generic, TypeVar
+from pm4py.objects.petri_net.obj import PetriNet
+from pm4py.objects.petri_net.sem_interface import Semantics
+
+N = TypeVar("N", bound=PetriNet)
+T = TypeVar("T", bound=PetriNet.Transition)
+P = TypeVar("P", bound=PetriNet.Place)
+
+
+class PetriNetSemantics(Generic[N]):
+
+ @classmethod
+ def is_enabled(cls, pn: N, transition: T, marking: Counter[P]) -> bool:
+ """
+ Checks whether a given transition is enabled in a given Petri net and marking
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param transition: transition to check
+ :param marking: marking to check
+
+ Returns
+ -------
+ :return: true if enabled, false otherwise
+ """
+ if transition not in pn.transitions:
+ return False
+ else:
+ for a in transition.in_arcs:
+ if marking[a.source] < a.weight:
+ return False
+ return True
+
+ @classmethod
+ def fire(cls, pn: N, transition: T, marking: Counter[P]) -> Counter[P]:
+ """
+ Execute a transition
+ For performance reasons, the algorithm method not check if the transition is enabled, i.e., this should be performed by the invoking algorithm (if needed). Hence, markings can become negative.
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param transition: transition to execute
+ :param marking: marking to use
+
+ Returns
+ -------
+ :return: newly reached marking
+ """
+ m_out = copy.copy(marking)
+ for a in transition.in_arcs:
+ m_out[a.source] -= a.weight
+ for a in transition.out_arcs:
+ m_out[a.target] += a.weight
+ return m_out
+
+
+class ClassicSemantics(Semantics):
+ def is_enabled(self, t, pn, m, **kwargs):
+ """
+ Verifies whether a given transition is enabled in a given Petri net and marking
+
+ Parameters
+ ----------
+ :param t: transition to check
+ :param pn: Petri net
+ :param m: marking to check
+
+ Returns
+ -------
+ :return: true if enabled, false otherwise
+ """
+ return is_enabled(t, pn, m)
+
+ def execute(self, t, pn, m, **kwargs):
+ """
+ Executes a given transition in a given Petri net and Marking
+
+ Parameters
+ ----------
+ :param t: transition to execute
+ :param pn: Petri net
+ :param m: marking to use
+
+ Returns
+ -------
+ :return: newly reached marking if :param t: is enabled, None otherwise
+ """
+ return execute(t, pn, m)
+
+ def weak_execute(self, t, pn, m, **kwargs):
+ """
+ Execute a transition even if it is not fully enabled
+
+ Parameters
+ ----------
+ :param t: transition to execute
+ :param pn: Petri net
+ :param m: marking to use
+
+ Returns
+ -------
+ :return: newly reached marking if :param t: is enabled, None otherwise
+ """
+ return weak_execute(t, m)
+
+ def enabled_transitions(self, pn, m, **kwargs):
+ """
+ Returns a set of enabled transitions in a Petri net and given marking
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param m: marking of the pn
+
+ Returns
+ -------
+ :return: set of enabled transitions
+ """
+ return enabled_transitions(pn, m)
+
+
+def is_enabled(t, pn, m):
+ if t not in pn.transitions:
+ return False
+ else:
+ for a in t.in_arcs:
+ if m[a.source] < a.weight:
+ return False
+ return True
+
+
+def execute(t, pn, m):
+ if not is_enabled(t, pn, m):
+ return None
+
+ m_out = copy.copy(m)
+ for a in t.in_arcs:
+ m_out[a.source] -= a.weight
+ if m_out[a.source] == 0:
+ del m_out[a.source]
+
+ for a in t.out_arcs:
+ m_out[a.target] += a.weight
+
+ return m_out
+
+
+def weak_execute(t, m):
+ m_out = copy.copy(m)
+ for a in t.in_arcs:
+ m_out[a.source] -= a.weight
+ if m_out[a.source] <= 0:
+ del m_out[a.source]
+ for a in t.out_arcs:
+ m_out[a.target] += a.weight
+ return m_out
+
+
+def enabled_transitions(pn, m):
+ enabled = set()
+ for t in pn.transitions:
+ if is_enabled(t, pn, m):
+ enabled.add(t)
+ return enabled
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..be6fc81ce3ad1099ab1b092520f01a689b930d2e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/__init__.py
@@ -0,0 +1,23 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.petri_net.stochastic import obj, semantics
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..4abe8708fab5b2442e05e0f5682816ccbcee7962
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/obj.py
@@ -0,0 +1,49 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Any, Collection, Dict
+
+from pm4py.objects.petri_net.obj import PetriNet
+
+
+class StochasticPetriNet(PetriNet):
+
+ class Transition(PetriNet.Transition):
+ def __init__(
+ self,
+ name: str,
+ label: str = None,
+ in_arcs: Collection[PetriNet.Arc] = None,
+ out_arcs: Collection[PetriNet.Arc] = None,
+ weight: float = 1.0,
+ properties: Dict[str, Any] = None,
+ ):
+ super().__init__(name, label, in_arcs, out_arcs, properties)
+ self.__weight = weight
+
+ def __set_weight(self, weight: float):
+ self.__weight = weight
+
+ def __get_weight(self) -> float:
+ return self.__weight
+
+ weight = property(__get_weight, __set_weight)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..3279c91ecc3e08ad662e256b775ac997b276bc62
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/stochastic/semantics.py
@@ -0,0 +1,99 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import random
+from typing import Counter, Generic, TypeVar
+
+from pm4py.objects.petri_net.semantics import PetriNetSemantics
+from pm4py.objects.petri_net.stochastic.obj import StochasticPetriNet
+
+N = TypeVar("N", bound=StochasticPetriNet)
+T = TypeVar("T", bound=StochasticPetriNet.Transition)
+P = TypeVar("P", bound=StochasticPetriNet.Place)
+
+
+class StochasticPetriNetSemantics(PetriNetSemantics[N], Generic[N]):
+
+ @classmethod
+ def sample_enabled_transition(
+ cls, pn: N, marking: Counter[P], seed: int = None
+ ) -> T:
+ """
+ Randomly samples a transition from all enabled transitions
+
+ Parameters
+ ----------
+ :param pn: Petri net
+ :param marking: marking to use
+
+ Returns
+ -------
+ :return: a transition sampled from the enabled transitions
+ """
+ if seed is not None:
+ random.seed(seed)
+ enabled = list(
+ filter(
+ lambda t: cls.is_enabled(pn, t, marking),
+ [t for t in pn.transitions],
+ )
+ )
+ weights = list(
+ map(
+ lambda t: cls.probability_of_transition(pn, t, marking),
+ enabled,
+ )
+ )
+ return random.choices(enabled, weights)[0]
+
+ @classmethod
+ def probability_of_transition(
+ cls, pn: N, transition: T, marking: Counter[P]
+ ) -> float:
+ """
+ Compute the probability of firing a transition in the net and marking.
+
+ Args:
+ pn (N): Stochastic net
+ transition (T): transition to fire
+ marking (Counter[P]): marking to use
+
+ Returns:
+ float: _description_
+ """
+ if transition not in pn.transitions or not cls.is_enabled(
+ pn, transition, marking
+ ):
+ return 0.0
+ return transition.weight / sum(
+ list(
+ map(
+ lambda t: t.weight,
+ list(
+ filter(
+ lambda t: cls.is_enabled(pn, t, marking),
+ [t for t in pn.transitions],
+ )
+ ),
+ )
+ )
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9962572aaa200744fbe1d18eef529e67a1578d8a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/__init__.py
@@ -0,0 +1,38 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.utils import (
+ align_utils,
+ check_soundness,
+ consumption_matrix,
+ decomposition,
+ embed_stochastic_map,
+ explore_path,
+ final_marking,
+ incidence_matrix,
+ initial_marking,
+ performance_map,
+ petri_utils,
+ projection,
+ reachability_graph,
+ reduction,
+ synchronous_product,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/align_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/align_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc0ceb0bbe4ca99b6724196e8f85efab3d3bf61e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/align_utils.py
@@ -0,0 +1,637 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import heapq
+import sys
+from copy import copy
+from typing import List, Tuple
+
+import numpy as np
+
+from pm4py.objects.petri_net import semantics, properties
+from pm4py.objects.petri_net.obj import Marking, PetriNet
+from pm4py.util.lp import solver as lp_solver
+
+SKIP = ">>"
+STD_MODEL_LOG_MOVE_COST = 10000
+STD_TAU_COST = 1
+STD_SYNC_COST = 0
+
+
+def search_path_among_sol(
+ sync_net: PetriNet,
+ ini: Marking,
+ fin: Marking,
+ activated_transitions: List[PetriNet.Transition],
+ skip=SKIP,
+) -> Tuple[List[PetriNet.Transition], bool, int]:
+ """
+ (Efficient method) Searches a firing sequence among the X vector that is the solution of the
+ (extended) marking equation
+
+ Parameters
+ ---------------
+ sync_net
+ Synchronous product net
+ ini
+ Initial marking of the net
+ fin
+ Final marking of the net
+ activated_transitions
+ Transitions that have non-zero occurrences in the X vector
+ skip
+ Skip transition
+
+ Returns
+ ---------------
+ firing_sequence
+ Firing sequence
+ reach_fm
+ Boolean value that tells if the final marking is reached by the firing sequence
+ explained_events
+ Number of explained events
+ """
+ reach_fm = False
+ trans_empty_preset = set(
+ t for t in sync_net.transitions if len(t.in_arcs) == 0
+ )
+ trans_with_index = {}
+ trans_wo_index = set()
+ for t in activated_transitions:
+ if properties.TRACE_NET_TRANS_INDEX in t.properties:
+ trans_with_index[
+ t.properties[properties.TRACE_NET_TRANS_INDEX]
+ ] = t
+ else:
+ trans_wo_index.add(t)
+ keys = sorted(list(trans_with_index.keys()))
+ trans_with_index = [trans_with_index[i] for i in keys]
+ best_tuple = (0, 0, ini, list())
+ open_set = [best_tuple]
+ heapq.heapify(open_set)
+ visited = 0
+ closed = set()
+ len_trace_with_index = len(trans_with_index)
+ while len(open_set) > 0:
+ curr = heapq.heappop(open_set)
+ index = -curr[0]
+ marking = curr[2]
+ if marking in closed:
+ continue
+ if index == len_trace_with_index:
+ reach_fm = True
+ if curr[0] < best_tuple[0]:
+ best_tuple = curr
+ break
+ if curr[0] < best_tuple[0]:
+ best_tuple = curr
+ closed.add(marking)
+ corr_trans = trans_with_index[index]
+ if corr_trans.sub_marking <= marking:
+ visited += 1
+ new_marking = semantics.weak_execute(corr_trans, marking)
+ heapq.heappush(
+ open_set,
+ (-index - 1, visited, new_marking, curr[3] + [corr_trans]),
+ )
+ else:
+ enabled = copy(trans_empty_preset)
+ for p in marking:
+ for t in p.ass_trans:
+ if t in trans_wo_index and t.sub_marking <= marking:
+ enabled.add(t)
+ for new_trans in enabled:
+ visited += 1
+ new_marking = semantics.weak_execute(new_trans, marking)
+ heapq.heappush(
+ open_set,
+ (-index, visited, new_marking, curr[3] + [new_trans]),
+ )
+ return best_tuple[-1], reach_fm, -best_tuple[0]
+
+
+def construct_standard_cost_function(synchronous_product_net, skip):
+ """
+ Returns the standard cost function, which is:
+ * event moves: cost 1000
+ * model moves: cost 1000
+ * tau moves: cost 1
+ * sync moves: cost 0
+ :param synchronous_product_net:
+ :param skip:
+ :return:
+ """
+ costs = {}
+ for t in synchronous_product_net.transitions:
+ if (skip == t.label[0] or skip == t.label[1]) and (
+ t.label[0] is not None and t.label[1] is not None
+ ):
+ costs[t] = STD_MODEL_LOG_MOVE_COST
+ else:
+ if skip == t.label[0] and t.label[1] is None:
+ costs[t] = STD_TAU_COST
+ else:
+ costs[t] = STD_SYNC_COST
+ return costs
+
+
+def pretty_print_alignments(alignments):
+ """Takes an alignment and prints it to the console, e.g.::
+
+ A | B | C | D |
+ --------------------
+ A | B | C | >> |
+
+ :param alignment: The alignment object (list of moves).
+ :return: Nothing.
+ """
+ if isinstance(alignments, list):
+ for alignment in alignments:
+ __print_single_alignment(alignment["alignment"])
+ else:
+ __print_single_alignment(alignments["alignment"])
+
+
+def __print_single_alignment(step_list):
+ trace_steps = []
+ model_steps = []
+ max_label_length = 0
+ for step in step_list:
+ trace_steps.append(" " + str(step[0]) + " ")
+ model_steps.append(" " + str(step[1]) + " ")
+ if len(step[0]) > max_label_length:
+ max_label_length = len(str(step[0]))
+ if len(str(step[1])) > max_label_length:
+ max_label_length = len(str(step[1]))
+ for i in range(len(trace_steps)):
+ if len(str(trace_steps[i])) - 2 < max_label_length:
+ step_length = len(str(trace_steps[i])) - 2
+ spaces_to_add = max_label_length - step_length
+ for j in range(spaces_to_add):
+ if j % 2 == 0:
+ trace_steps[i] = trace_steps[i] + " "
+ else:
+ trace_steps[i] = " " + trace_steps[i]
+ print(trace_steps[i], end="|")
+ divider = ""
+ length_divider = len(trace_steps) * (max_label_length + 3)
+ for i in range(length_divider):
+ divider += "-"
+ print("\n" + divider)
+ for i in range(len(model_steps)):
+ if len(model_steps[i]) - 2 < max_label_length:
+ step_length = len(model_steps[i]) - 2
+ spaces_to_add = max_label_length - step_length
+ for j in range(spaces_to_add):
+ if j % 2 == 0:
+ model_steps[i] = model_steps[i] + " "
+ else:
+ model_steps[i] = " " + model_steps[i]
+
+ print(model_steps[i], end="|")
+ print("\n\n")
+
+
+def add_markings(curr, add):
+ m = Marking()
+ for p in curr.items():
+ m[p[0]] = p[1]
+ for p in add.items():
+ m[p[0]] += p[1]
+ if m[p[0]] == 0:
+ del m[p[0]]
+ return m
+
+
+def __get_alt(open_set, new_marking):
+ for item in open_set:
+ if item.m == new_marking:
+ return item
+
+
+def __reconstruct_alignment(
+ state,
+ visited,
+ queued,
+ traversed,
+ ret_tuple_as_trans_desc=False,
+ lp_solved=0,
+):
+ alignment = list()
+ if state.p is not None and state.t is not None:
+ parent = state.p
+ if ret_tuple_as_trans_desc:
+ alignment = [(state.t.name, state.t.label)]
+ while parent.p is not None:
+ alignment = [(parent.t.name, parent.t.label)] + alignment
+ parent = parent.p
+ else:
+ alignment = [state.t.label]
+ while parent.p is not None:
+ alignment = [parent.t.label] + alignment
+ parent = parent.p
+ return {
+ "alignment": alignment,
+ "cost": state.g,
+ "visited_states": visited,
+ "queued_states": queued,
+ "traversed_arcs": traversed,
+ "lp_solved": lp_solved,
+ }
+
+
+def __derive_heuristic(incidence_matrix, cost_vec, x, t, h):
+ x_prime = x.copy()
+ x_prime[incidence_matrix.transitions[t]] -= 1
+ return max(0, h - cost_vec[incidence_matrix.transitions[t]]), x_prime
+
+
+def __is_model_move(t, skip):
+ return t.label[0] == skip and t.label[1] != skip
+
+
+def __is_log_move(t, skip):
+ return t.label[0] != skip and t.label[1] == skip
+
+
+def __trust_solution(x):
+ for v in x:
+ if v < -0.001:
+ return False
+ return True
+
+
+def __compute_exact_heuristic_new_version(
+ sync_net,
+ a_matrix,
+ h_cvx,
+ g_matrix,
+ cost_vec,
+ incidence_matrix,
+ marking,
+ fin_vec,
+ variant,
+ use_cvxopt=False,
+ strict=True,
+):
+ m_vec = incidence_matrix.encode_marking(marking)
+ b_term = [i - j for i, j in zip(fin_vec, m_vec)]
+ b_term = np.matrix([x * 1.0 for x in b_term]).transpose()
+
+ if not strict:
+ g_matrix = np.vstack([g_matrix, a_matrix])
+ h_cvx = np.vstack([h_cvx, b_term])
+ a_matrix = np.zeros((0, a_matrix.shape[1]))
+ b_term = np.zeros((0, b_term.shape[1]))
+
+ if use_cvxopt:
+ # not available in the latest version of PM4Py
+ from cvxopt import matrix
+
+ b_term = matrix(b_term)
+
+ parameters_solving = {"solver": "glpk"}
+
+ sol = lp_solver.apply(
+ cost_vec,
+ g_matrix,
+ h_cvx,
+ a_matrix,
+ b_term,
+ parameters=parameters_solving,
+ variant=variant,
+ )
+ prim_obj = lp_solver.get_prim_obj_from_sol(sol, variant=variant)
+ points = lp_solver.get_points_from_sol(sol, variant=variant)
+
+ prim_obj = prim_obj if prim_obj is not None else sys.maxsize
+ points = (
+ points if points is not None else [0.0] * len(sync_net.transitions)
+ )
+
+ return prim_obj, points
+
+
+def __get_tuple_from_queue(marking, queue):
+ for t in queue:
+ if t.m == marking:
+ return t
+ return None
+
+
+def __vectorize_initial_final_cost(incidence_matrix, ini, fin, cost_function):
+ ini_vec = incidence_matrix.encode_marking(ini)
+ fini_vec = incidence_matrix.encode_marking(fin)
+ cost_vec = [0] * len(cost_function)
+ for t in cost_function.keys():
+ cost_vec[incidence_matrix.transitions[t]] = cost_function[t]
+ return ini_vec, fini_vec, cost_vec
+
+
+class SearchTuple:
+ # different properties of the class:
+ # - g => actual cost of the alignment moves
+ # - h => computed heuristic value
+ # - f => the sum of g and h, used for the A* algorithm
+ # - m => marking reached in the synchronous product net in the current state
+ # - p => parent state of the alignment (used at the end to reconstruct the alignment)
+ # - t => transition just visited
+ # - trustable => indicates if the heuristic comes from an exact solution of an (I)LP problem
+ # - x => solution vector of the (I)LP
+ def __init__(self, f, g, h, m, p, t, x, trust):
+ self.f = f
+ self.g = g
+ self.h = h
+ self.m = m
+ self.p = p
+ self.t = t
+ self.x = x
+ self.trust = trust
+
+ def __lt__(self, other):
+ if self.f < other.f:
+ return True
+ elif other.f < self.f:
+ return False
+ elif self.trust and not other.trust:
+ return True
+ else:
+ return self.h < other.h
+
+ def __get_firing_sequence(self):
+ ret = []
+ if self.p is not None:
+ ret = ret + self.p.__get_firing_sequence()
+ if self.t is not None:
+ ret.append(self.t)
+ return ret
+
+ def __repr__(self):
+ string_build = [
+ "\nm=" + str(self.m),
+ " f=" + str(self.f),
+ " g=" + str(self.g),
+ " h=" + str(self.h),
+ " path=" + str(self.__get_firing_sequence()) + "\n\n",
+ ]
+ return " ".join(string_build)
+
+
+class DijkstraSearchTuple:
+ def __init__(self, g, m, p, t, l):
+ self.g = g
+ self.m = m
+ self.p = p
+ self.t = t
+ self.l = l
+
+ def __lt__(self, other):
+ if self.g < other.g:
+ return True
+ elif other.g < self.g:
+ return False
+ else:
+ return other.l < self.l
+
+ def __get_firing_sequence(self):
+ ret = []
+ if self.p is not None:
+ ret = ret + self.p.__get_firing_sequence()
+ if self.t is not None:
+ ret.append(self.t)
+ return ret
+
+ def __repr__(self):
+ string_build = [
+ "\nm=" + str(self.m),
+ " g=" + str(self.g),
+ " path=" + str(self.__get_firing_sequence()) + "\n\n",
+ ]
+ return " ".join(string_build)
+
+class DijkstraSearchTupleForAntiAndMulti:
+ # in this version we keep the run and not the previous element
+ # the display is different
+ def __init__(self, g, m, r):
+ self.g = g
+ self.m = m
+ self.r = r
+
+ def __lt__(self, other):
+ if self.g < other.g:
+ return True
+ elif other.g < self.g:
+ return False
+ else:
+ return len(other.r) < len(self.r)
+
+ def __get_firing_sequence(self):
+ return self.r
+
+ def __repr__(self):
+ string_build = ["\nm=" + str(self.m), " g=" + str(self.g),
+ " path=" + str(self.__get_firing_sequence()) + "\n\n"]
+ return " ".join(string_build)
+
+class TweakedSearchTuple:
+ def __init__(self, f, g, h, m, p, t, x, trust, virgin):
+ self.f = f
+ self.g = g
+ self.h = h
+ self.m = m
+ self.p = p
+ self.t = t
+ self.x = x
+ self.trust = trust
+ # a virgin status must be explored in its firing sequence
+ self.virgin = virgin
+
+ def __lt__(self, other):
+ if self.f < other.f:
+ return True
+ elif other.f < self.f:
+ return False
+ elif self.virgin and not other.virgin:
+ return True
+ elif self.trust and not other.trust:
+ return True
+ else:
+ return self.h < other.h
+
+ def __get_firing_sequence(self):
+ ret = []
+ if self.p is not None:
+ ret = ret + self.p.__get_firing_sequence()
+ if self.t is not None:
+ ret.append(self.t)
+ return ret
+
+ def __repr__(self):
+ string_build = [
+ "\nm=" + str(self.m),
+ " f=" + str(self.f),
+ " g=" + str(self.g),
+ " h=" + str(self.h),
+ " path=" + str(self.__get_firing_sequence()) + "\n\n",
+ ]
+ return " ".join(string_build)
+
+
+def get_visible_transitions_eventually_enabled_by_marking(net, marking):
+ """
+ Get visible transitions eventually enabled by marking (passing possibly
+ through hidden transitions)
+
+ Parameters
+ ----------
+ net
+ Petri net
+ marking
+ Current marking
+
+ """
+ all_enabled_transitions = sorted(
+ list(semantics.enabled_transitions(net, marking)),
+ key=lambda x: (str(x.name), id(x)),
+ )
+ initial_all_enabled_transitions_marking_dictio = {}
+ all_enabled_transitions_marking_dictio = {}
+ for trans in all_enabled_transitions:
+ all_enabled_transitions_marking_dictio[trans] = marking
+ initial_all_enabled_transitions_marking_dictio[trans] = marking
+ visible_transitions = set()
+ visited_transitions = set()
+
+ i = 0
+ while i < len(all_enabled_transitions):
+ t = all_enabled_transitions[i]
+ marking_copy = copy(all_enabled_transitions_marking_dictio[t])
+
+ if repr([t, marking_copy]) not in visited_transitions:
+ if t.label is not None:
+ visible_transitions.add(t)
+ else:
+ if semantics.is_enabled(t, net, marking_copy):
+ new_marking = semantics.execute(t, net, marking_copy)
+ new_enabled_transitions = sorted(
+ list(semantics.enabled_transitions(net, new_marking)),
+ key=lambda x: (str(x.name), id(x)),
+ )
+ for t2 in new_enabled_transitions:
+ all_enabled_transitions.append(t2)
+ all_enabled_transitions_marking_dictio[t2] = (
+ new_marking
+ )
+ visited_transitions.add(repr([t, marking_copy]))
+ i = i + 1
+
+ return visible_transitions
+
+def discountedEditDistance(s1, s2, exponent=2, modeled=True):
+ '''
+ Fast implementation of the discounted distance
+ Inspired from the faster version of the edit distance
+ '''
+ # print(s1, s2)
+ if len(s1) < len(s2):
+ return discountedEditDistance(
+ s2, s1, exponent=exponent, modeled=False
+ )
+
+ previous_row = [0]
+ for a in range(len(s2)):
+ if not modeled and (
+ s2[a] == "tau" or s2[a] is None or s2[a][0] == "n"
+ ):
+ previous_row.append(previous_row[-1])
+ else:
+ previous_row.append(previous_row[-1] + exponent ** (-a))
+ for i, c1 in enumerate(s1):
+ if modeled:
+ exp1 = sum(
+ exponent ** (-a)
+ for a in range(i + 1)
+ if s1[a] != "tau" and s1[a] is not None and s1[a][0] != "n"
+ )
+ else:
+ exp1 = sum(exponent ** (-a) for a in range(i + 1))
+ current_row = [exp1]
+ for j, c2 in enumerate(s2):
+ exp2 = exponent ** (-(i + 1 + j))
+ if modeled and (
+ c1 in ["tau", None] or c1[0] == "n" or "skip" in c1
+ ):
+ insertions = previous_row[
+ j + 1
+ ] # j+1 instead of j since previous_row and current_row are one character longer
+ deletions = current_row[j] + exp2 # than s2
+ elif not modeled and (c2 in ["tau", None] or c2[0] == "n"):
+ insertions = previous_row[
+ j + 1
+ ] + exp2 # j+1 instead of j since previous_row and current_row are one character longer
+ deletions = current_row[j]
+ else:
+ insertions = previous_row[
+ j + 1
+ ] + exp2 # j+1 instead of j since previous_row and current_row are one character longer
+ deletions = current_row[j] + exp2
+ if c1 != c2:
+ current_row.append(min(insertions, deletions))
+ else:
+ substitutions = previous_row[j]
+ current_row.append(min(insertions, deletions, substitutions))
+
+ previous_row = current_row
+ return len(s1) + len(s2), previous_row[-1]
+
+
+def levenshtein(seq1, seq2):
+ '''
+ Edit distance without substitution
+ '''
+ size_x = len(seq1) + 1
+ size_y = len(seq2) + 1
+ matrix = np.zeros ((size_x, size_y))
+ for x in range(size_x):
+ matrix [x, 0] = x
+ for y in range(size_y):
+ matrix [0, y] = y
+
+ for x in range(1, size_x):
+ for y in range(1, size_y):
+ if seq1[x-1] in [None,"tau"] or seq1[x-1][0]=='n' or "skip" in seq1[x-1] or "tau" in seq1[x-1] :
+ matrix [x,y] = min(
+ matrix[x-1, y],
+ matrix[x,y-1] + 1
+ )
+ elif seq1[x-1] == seq2[y-1]:
+ matrix [x,y] = min(
+ matrix[x-1, y] + 1,
+ matrix[x-1, y-1],
+ matrix[x, y-1] + 1
+ )
+ else:
+ matrix [x,y] = min(
+ matrix[x-1,y] + 1,
+ matrix[x,y-1] + 1
+ )
+ return (matrix[size_x - 1, size_y - 1])
+
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/check_soundness.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/check_soundness.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c48848b0eea50730659524c53f1e5d3a1c14d57
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/check_soundness.py
@@ -0,0 +1,222 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.utils.networkx_graph import (
+ create_networkx_undirected_graph,
+)
+from pm4py.objects.petri_net.utils import explore_path
+from pm4py.objects.petri_net import obj
+from pm4py.util import nx_utils
+
+
+def check_source_and_sink_reachability(net, unique_source, unique_sink):
+ """
+ Checks reachability of the source and the sink place from all simulation nodes (places/transitions)
+ of the Petri net
+
+ Parameters
+ -------------
+ net
+ Petri net
+ unique_source
+ Unique source place of the Petri net
+ unique_sink
+ Unique sink place of the Petri net
+
+ Returns
+ -------------
+ boolean
+ Boolean value that is true if each node is in a path from the source place to the sink place
+ """
+ graph, unique_source_corr, unique_sink_corr, inv_dictionary = (
+ create_networkx_undirected_graph(net, unique_source, unique_sink)
+ )
+ if unique_source_corr is not None and unique_sink_corr is not None:
+ nodes_list = list(graph.nodes())
+ finish_to_sink = list(nx_utils.ancestors(graph, unique_sink_corr))
+ connected_to_source = list(
+ nx_utils.descendants(graph, unique_source_corr)
+ )
+ if (
+ len(finish_to_sink) == len(nodes_list) - 1
+ and len(connected_to_source) == len(nodes_list) - 1
+ ):
+ return True
+ return False
+
+
+def check_source_place_presence(net):
+ """
+ Check if there is a unique source place with empty connections
+
+ Parameters
+ -------------
+ net
+ Petri net
+
+ Returns
+ -------------
+ place
+ Unique source place (or None otherwise)
+ """
+ count_empty_input = 0
+ unique_source = None
+ for place in net.places:
+ if len(place.in_arcs) == 0:
+ count_empty_input = count_empty_input + 1
+ unique_source = place
+ if count_empty_input == 1:
+ return unique_source
+ return None
+
+
+def check_sink_place_presence(net):
+ """
+ Check if there is a unique sink place with empty connections
+
+ Parameters
+ -------------
+ net
+ Petri net
+
+ Returns
+ -------------
+ place
+ Unique source place (or None otherwise)
+ """
+ count_empty_output = 0
+ unique_sink = None
+ for place in net.places:
+ if len(place.out_arcs) == 0:
+ count_empty_output = count_empty_output + 1
+ unique_sink = place
+ if count_empty_output == 1:
+ return unique_sink
+ return None
+
+
+def check_wfnet(net):
+ """
+ Check if the Petri net is a workflow net
+
+ Parameters
+ ------------
+ net
+ Petri net
+
+ Returns
+ ------------
+ boolean
+ Boolean value that is true when the Petri net is a workflow net
+ """
+ unique_source_place = check_source_place_presence(net)
+ unique_sink_place = check_sink_place_presence(net)
+ source_sink_reachability = check_source_and_sink_reachability(
+ net, unique_source_place, unique_sink_place
+ )
+
+ return (
+ (unique_source_place is not None)
+ and (unique_sink_place is not None)
+ and source_sink_reachability
+ )
+
+
+def check_source_sink_place_conditions(net):
+ """
+ Check some conditions on the source/sink place important
+ for a sound workflow net
+
+ Parameters
+ --------------
+ net
+ Petri net
+
+ Returns
+ --------------
+ boolean
+ Boolean value (True is good)
+ """
+ # check also that the transitions connected to the source/sink place have
+ # unique arcs
+ unique_source_place = check_source_place_presence(net)
+ unique_sink_place = check_sink_place_presence(net)
+ if unique_source_place is not None:
+ for arc in unique_source_place.out_arcs:
+ trans = arc.target
+ if len(trans.in_arcs) > 1:
+ return False
+ if unique_sink_place is not None:
+ for arc in unique_sink_place.in_arcs:
+ trans = arc.source
+ if len(trans.out_arcs) > 1:
+ return False
+ return True
+
+
+def check_easy_soundness_net_in_fin_marking(net, ini, fin):
+ """
+ Checks the easy soundness of a Petri net having the initial and the final marking
+
+ Parameters
+ -------------
+ net
+ Petri net
+ ini
+ Initial marking
+ fin
+ Final marking
+
+ Returns
+ -------------
+ boolean
+ Boolean value
+ """
+ try:
+ alignment = explore_path.__search(net, ini, fin)
+ if alignment is not None:
+ return True
+ return False
+ except BaseException:
+ return False
+
+
+def check_easy_soundness_of_wfnet(net):
+ """
+ Checks the easy soundness of a workflow net
+
+ Parameters
+ -------------
+ net
+ Petri net
+
+ Returns
+ -------------
+ boolean
+ Boolean value
+ """
+ source = list(x for x in net.places if len(x.in_arcs) == 0)[0]
+ sink = list(x for x in net.places if len(x.out_arcs) == 0)[0]
+
+ ini = obj.Marking({source: 1})
+ fin = obj.Marking({sink: 1})
+
+ return check_easy_soundness_net_in_fin_marking(net, ini, fin)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/consumption_matrix.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/consumption_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..0517d5d0bdd5de0458f956e8d92f4e8b61c1b487
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/consumption_matrix.py
@@ -0,0 +1,128 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from typing import Dict
+
+import numpy as np
+
+from pm4py.objects.petri_net.obj import PetriNet
+
+
+class ConsumptionMatrix(object):
+ def __init__(self, net: PetriNet):
+ """
+ Constructor
+
+ Parameters
+ --------------
+ net
+ Petri net
+ """
+ self.__place_indices = {}
+ self.__transition_indices = {}
+ self.__C = None
+ places = sorted([x for x in net.places], key=lambda x: (x.name, id(x)))
+ transitions = sorted(
+ [x for x in net.transitions], key=lambda x: (x.name, id(x))
+ )
+
+ for p in places:
+ self.__place_indices[p] = len(self.__place_indices)
+ for t in transitions:
+ self.__transition_indices[t] = len(self.__transition_indices)
+ self.__compute_C_matrix(net)
+
+ def __compute_C_matrix(self, net: PetriNet):
+ """
+ Builds the C matrix
+
+ Parameters
+ ---------------
+ net
+ Petri net
+ """
+ inv_indices = {y: x for x, y in self.__transition_indices.items()}
+ inv_indices = [inv_indices[i] for i in range(len(inv_indices))]
+ self.__C = [
+ [0 for i in range(len(self.__transition_indices))]
+ for j in range(len(self.__place_indices))
+ ]
+ for p in net.places:
+ outgoing_trans = [a.target for a in p.out_arcs]
+ self.__C[self.__place_indices[p]] = [
+ -1 if inv_indices[i] in outgoing_trans else 0
+ for i in range(len(inv_indices))
+ ]
+
+ def __get_transition_indices(self) -> Dict[PetriNet.Transition, int]:
+ """
+ Gets the transitions in the order in which they have been inserted in the consumption matrix
+
+ Returns
+ -------------
+ trans_indices
+ Dictionary associating to each transition an incremental number
+ """
+ return self.__transition_indices
+
+ def __get_place_indices(self) -> Dict[PetriNet.Place, int]:
+ """
+ Gets the places in the order in which they have been inserted in the consumption matrix
+
+ Returns
+ -------------
+ place_indices
+ Dictionary associating to each place an incremental number
+ """
+ return self.__place_indices
+
+ def __get_c_matrix(self) -> np.ndarray:
+ """
+ Gets the Numpy representation of the consumption matrix
+
+ Returns
+ -------------
+ C
+ C matrix
+ """
+ return self.__C
+
+ places = property(__get_place_indices)
+ transitions = property(__get_transition_indices)
+ c_matrix = property(__get_c_matrix)
+
+
+def construct(net: PetriNet) -> ConsumptionMatrix:
+ """
+ Construct a consumption matrix given a Petri net
+
+ Parameters
+ ----------------
+ net
+ Petri net
+
+ Returns
+ ---------------
+ cons_mat
+ Consumption matrix object
+ """
+ return ConsumptionMatrix(net)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/decomposition.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/decomposition.py
new file mode 100644
index 0000000000000000000000000000000000000000..53917588aac2541d3d3e0dfaff223f300a285da3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/decomposition.py
@@ -0,0 +1,219 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import hashlib
+
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to
+from pm4py.util import constants, nx_utils
+
+
+def get_graph_components(places, inv_trans, trans_dup_label, tmap):
+ G = nx_utils.Graph()
+ for x in places:
+ G.add_node(x)
+ for x in inv_trans:
+ G.add_node(x)
+ for x in trans_dup_label:
+ G.add_node(x)
+ for x in trans_dup_label:
+ i = 0
+ while i < len(tmap[x]) - 1:
+ j = i + 1
+ while j < len(tmap[x]):
+ G.add_edge(tmap[x][i].label, tmap[x][j].label)
+ j = j + 1
+ i = i + 1
+ all_inserted_val = (
+ set(places.values())
+ .union(inv_trans.values())
+ .union(trans_dup_label.values())
+ )
+ for v1 in all_inserted_val:
+ for arc in v1.out_arcs:
+ v2 = arc.target
+ if v2 in all_inserted_val:
+ G.add_edge(v1.name, v2.name)
+ conn_comp = list(nx_utils.connected_components(G))
+ return conn_comp
+
+
+def decompose(net, im, fm):
+ places = {x.name: x for x in net.places}
+ inv_trans = {x.name: x for x in net.transitions if x.label is None}
+ tmap = {}
+ for t in net.transitions:
+ if t.label is not None:
+ if t.label not in tmap:
+ tmap[t.label] = []
+ tmap[t.label].append(t)
+ trans_dup_label = {
+ x.label: x
+ for x in net.transitions
+ if x.label is not None and len(tmap[x.label]) > 1
+ }
+ trans_labels = {x.name: x.label for x in net.transitions}
+ conn_comp = get_graph_components(places, inv_trans, trans_dup_label, tmap)
+ list_nets = []
+ for cmp in conn_comp:
+ net_new = PetriNet("")
+ im_new = Marking()
+ fm_new = Marking()
+ lmap = {}
+ for el in cmp:
+ if el in places:
+ lmap[el] = PetriNet.Place(el)
+ net_new.places.add(lmap[el])
+ elif el in inv_trans:
+ lmap[el] = PetriNet.Transition(el, None)
+ net_new.transitions.add(lmap[el])
+ elif el in trans_labels:
+ lmap[el] = PetriNet.Transition(el, trans_labels[el])
+ net_new.transitions.add(lmap[el])
+ for el in cmp:
+ if el in places:
+ old_place = places[el]
+ for arc in old_place.in_arcs:
+ st = arc.source
+ if st.name not in lmap:
+ lmap[st.name] = PetriNet.Transition(
+ st.name, trans_labels[st.name]
+ )
+ net_new.transitions.add(lmap[st.name])
+ add_arc_from_to(lmap[st.name], lmap[el], net_new)
+ for arc in old_place.out_arcs:
+ st = arc.target
+ if st.name not in lmap:
+ lmap[st.name] = PetriNet.Transition(
+ st.name, trans_labels[st.name]
+ )
+ net_new.transitions.add(lmap[st.name])
+ add_arc_from_to(lmap[el], lmap[st.name], net_new)
+ if old_place in im:
+ im_new[lmap[el]] = im[old_place]
+ if old_place in fm:
+ fm_new[lmap[el]] = fm[old_place]
+ lvis_labels = sorted(
+ [t.label for t in net_new.transitions if t.label is not None]
+ )
+ t_tuple = tuple(
+ sorted(
+ list(
+ int(
+ hashlib.md5(
+ t.name.encode(constants.DEFAULT_ENCODING)
+ ).hexdigest(),
+ 16,
+ )
+ for t in net_new.transitions
+ )
+ )
+ )
+ net_new.lvis_labels = lvis_labels
+ net_new.t_tuple = t_tuple
+
+ if len(net_new.places) > 0 or len(net_new.transitions) > 0:
+ list_nets.append((net_new, im_new, fm_new))
+
+ return list_nets
+
+
+def merge_comp(comp1, comp2):
+ net = PetriNet("")
+ im = Marking()
+ fm = Marking()
+ places = {}
+ trans = {}
+
+ for pl in comp1[0].places:
+ places[pl.name] = PetriNet.Place(pl.name)
+ net.places.add(places[pl.name])
+ if pl in comp1[1]:
+ im[places[pl.name]] = comp1[1][pl]
+ if pl in comp1[2]:
+ fm[places[pl.name]] = comp1[2][pl]
+
+ for pl in comp2[0].places:
+ places[pl.name] = PetriNet.Place(pl.name)
+ net.places.add(places[pl.name])
+ if pl in comp2[1]:
+ im[places[pl.name]] = comp2[1][pl]
+ if pl in comp2[2]:
+ fm[places[pl.name]] = comp2[2][pl]
+
+ for tr in comp1[0].transitions:
+ trans[tr.name] = PetriNet.Transition(tr.name, tr.label)
+ net.transitions.add(trans[tr.name])
+
+ for tr in comp2[0].transitions:
+ if tr.name not in trans:
+ trans[tr.name] = PetriNet.Transition(tr.name, tr.label)
+ net.transitions.add(trans[tr.name])
+
+ for arc in comp1[0].arcs:
+ if type(arc.source) is PetriNet.Place:
+ add_arc_from_to(
+ places[arc.source.name], trans[arc.target.name], net
+ )
+ else:
+ add_arc_from_to(
+ trans[arc.source.name], places[arc.target.name], net
+ )
+
+ for arc in comp2[0].arcs:
+ if type(arc.source) is PetriNet.Place:
+ add_arc_from_to(
+ places[arc.source.name], trans[arc.target.name], net
+ )
+ else:
+ add_arc_from_to(
+ trans[arc.source.name], places[arc.target.name], net
+ )
+
+ lvis_labels = sorted(
+ [t.label for t in net.transitions if t.label is not None]
+ )
+ t_tuple = tuple(
+ sorted(
+ list(
+ int(
+ hashlib.md5(
+ t.name.encode(constants.DEFAULT_ENCODING)
+ ).hexdigest(),
+ 16,
+ )
+ for t in net.transitions
+ )
+ )
+ )
+ net.lvis_labels = lvis_labels
+ net.t_tuple = t_tuple
+
+ return (net, im, fm)
+
+
+def merge_sublist_nets(list_nets):
+ while len(list_nets) > 1:
+ list_nets.append(merge_comp(list_nets[0], list_nets[1]))
+ list_nets.pop(0)
+ list_nets.pop(0)
+
+ return list_nets[0]
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/embed_stochastic_map.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/embed_stochastic_map.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c2b4f6cb180783f5b49a98663da55503518348c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/embed_stochastic_map.py
@@ -0,0 +1,70 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util.constants import STOCHASTIC_DISTRIBUTION
+
+
+def apply(smap, parameters=None):
+ """
+ Embed the stochastic map into the Petri net
+
+ Parameters
+ ---------------
+ smap
+ Stochastic map
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ ---------------
+ void
+ """
+ if parameters is None:
+ parameters = {}
+
+ for t in smap:
+ t.properties[STOCHASTIC_DISTRIBUTION] = smap[t]
+
+
+def extract(net, parameters=None):
+ """
+ Extract the stochastic map from the Petri net
+
+ Parameters
+ --------------
+ net
+ Petri net
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ void
+ """
+ if parameters is None:
+ parameters = {}
+
+ smap = {}
+
+ for t in net.transitions:
+ smap[t] = t.properties[STOCHASTIC_DISTRIBUTION]
+
+ return smap
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/embeddings_similarity.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/embeddings_similarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..d57da15fe7edb55ef89491d17adc1edc287754b8
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/embeddings_similarity.py
@@ -0,0 +1,193 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import random
+from typing import List
+
+import numpy as np
+import networkx as nx
+from pm4py.objects.petri_net.obj import PetriNet
+
+
+###############################################################################
+# 1 ⸺ Convert the Petri net to a plain (bidirectional) graph
+###############################################################################
+
+def _petri_to_nx(net) -> nx.Graph:
+ """
+ Returns an undirected NetworkX graph with node attribute ``type``
+ ∈ {'place', 'transition'} and edge attribute ``flow`` (weight 1).
+ """
+ G = nx.Graph()
+ # add nodes
+ for p in net.places:
+ G.add_node(f"P_{p.name}", type="place")
+ for t in net.transitions:
+ G.add_node(f"T_{t.name}", type="transition")
+ # add arcs
+ for arc in net.arcs:
+ u, v = arc.source, arc.target
+ uid = f"{'P' if u in net.places else 'T'}_{u.name}"
+ vid = f"{'P' if v in net.places else 'T'}_{v.name}"
+ G.add_edge(uid, vid, flow=1)
+ return G
+
+
+###############################################################################
+# 2 ⸺ Node2Vec walk generation (simplified, unbiased)
+###############################################################################
+
+def _random_walk(G: nx.Graph, start: str, length: int) -> List[str]:
+ walk = [start]
+ for _ in range(length - 1):
+ cur = walk[-1]
+ neigh = list(G.neighbors(cur))
+ if not neigh:
+ break
+ walk.append(random.choice(neigh))
+ return walk
+
+
+def _generate_walks(G: nx.Graph,
+ num_walks: int = 10,
+ walk_length: int = 40,
+ seed: int = 42) -> List[List[str]]:
+ random.seed(seed)
+ nodes = list(G.nodes())
+ walks = []
+ for _ in range(num_walks):
+ random.shuffle(nodes)
+ for n in nodes:
+ walks.append(_random_walk(G, n, walk_length))
+ return walks
+
+
+###############################################################################
+# 3 ⸺ Train Skip-gram (gensim Word2Vec)
+###############################################################################
+
+def _train_word2vec(walks: List[List[str]],
+ dimensions: int = 64,
+ window: int = 5,
+ workers: int = 1,
+ epochs: int = 10):
+ from gensim.models import Word2Vec
+
+ return Word2Vec(
+ sentences=walks,
+ vector_size=dimensions,
+ window=window,
+ min_count=0,
+ sg=1, # skip-gram
+ workers=workers,
+ epochs=epochs,
+ )
+
+
+###############################################################################
+# 4 ⸺ Read-out: aggregate node embeddings into **one vector per net**
+###############################################################################
+
+def _readout(model,
+ G: nx.Graph,
+ mode: str = "mean",
+ transition_only: bool = False) -> np.ndarray:
+ """
+ Parameters
+ ----------
+ mode : {'mean', 'sum', 'max'}
+ How to pool the node embeddings.
+ transition_only : bool
+ If True, use only transition nodes (ignores places).
+ """
+ nodes = [
+ n for n, data in G.nodes(data=True)
+ if (not transition_only) or data["type"] == "transition"
+ ]
+ vecs = np.array([model.wv[n] for n in nodes])
+ if mode == "sum":
+ return vecs.sum(axis=0)
+ if mode == "max":
+ return vecs.max(axis=0)
+ return vecs.mean(axis=0) # default
+
+
+###############################################################################
+# 5 ⸺ Public helper
+###############################################################################
+
+def petri_net_embedding(net,
+ dimensions: int = 64,
+ num_walks: int = 10,
+ walk_length: int = 40,
+ window: int = 5,
+ workers: int = 1,
+ epochs: int = 10,
+ readout: str = "mean",
+ transition_only: bool = False,
+ seed: int = 42) -> np.ndarray:
+ """
+ Returns
+ -------
+ np.ndarray (shape = [dimensions,])
+ """
+ G = _petri_to_nx(net)
+ walks = _generate_walks(G, num_walks, walk_length, seed)
+ w2v = _train_word2vec(walks, dimensions, window, workers, epochs)
+ return _readout(w2v, G, readout, transition_only)
+
+
+def cosine_similarity(a, b, eps=1e-10):
+ a = np.asarray(a, dtype=float)
+ b = np.asarray(b, dtype=float)
+
+ num = np.dot(a, b) # dot product
+ denom = np.linalg.norm(a) * np.linalg.norm(b)
+
+ if denom < eps: # avoid division-by-zero
+ return 0.0 # or raise an error / np.nan
+ return num / denom
+
+
+def apply(net1: PetriNet, net2: PetriNet) -> float:
+ """
+ Computes the embeddings-based similarity between two Petri nets,
+ based on the approach described in:
+
+ Colonna, Juan G., et al. "Process mining embeddings: Learning vector representations for Petri nets." Intelligent Systems with Applications 23 (2024): 200423.
+
+
+ Parameters
+ ----------------
+ net1
+ Petri net
+ net2
+ Second Petri net
+
+ Returns
+ -----------------
+ similarity_metric
+ Cosine similarity between the two embeddings
+ """
+ emb1 = petri_net_embedding(net1)
+ emb2 = petri_net_embedding(net2)
+
+ return cosine_similarity(emb1, emb2)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/explore_path.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/explore_path.py
new file mode 100644
index 0000000000000000000000000000000000000000..81154ab06d64b303ce0d0b15cb8ff91f00e0009c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/explore_path.py
@@ -0,0 +1,180 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import numpy as np
+from pm4py.util.lp import solver as lp_solver
+from pm4py.objects.petri_net.utils import align_utils as utils
+from pm4py.objects.petri_net.utils.incidence_matrix import construct
+from pm4py.objects.petri_net.utils.petri_utils import (
+ decorate_places_preset_trans,
+ decorate_transitions_prepostset,
+)
+from copy import copy
+import heapq
+
+
+def __search(net, ini, fin):
+ cost_function = {t: 1 for t in net.transitions}
+
+ decorate_transitions_prepostset(net)
+ decorate_places_preset_trans(net)
+
+ incidence_matrix = construct(net)
+ ini_vec, fin_vec, cost_vec = utils.__vectorize_initial_final_cost(
+ incidence_matrix, ini, fin, cost_function
+ )
+
+ closed = set()
+
+ a_matrix = np.asmatrix(incidence_matrix.a_matrix).astype(np.float64)
+ g_matrix = -np.eye(len(net.transitions))
+ h_cvx = np.matrix(np.zeros(len(net.transitions))).transpose()
+ cost_vec = [x * 1.0 for x in cost_vec]
+
+ use_cvxopt = False
+ if (
+ lp_solver.DEFAULT_LP_SOLVER_VARIANT
+ == lp_solver.CVXOPT_SOLVER_CUSTOM_ALIGN
+ or lp_solver.DEFAULT_LP_SOLVER_VARIANT
+ == lp_solver.CVXOPT_SOLVER_CUSTOM_ALIGN_ILP
+ ):
+ use_cvxopt = True
+
+ if use_cvxopt:
+ # not available in the latest version of PM4Py
+ from cvxopt import matrix
+
+ a_matrix = matrix(a_matrix)
+ g_matrix = matrix(g_matrix)
+ h_cvx = matrix(h_cvx)
+ cost_vec = matrix(cost_vec)
+
+ h, x = utils.__compute_exact_heuristic_new_version(
+ net,
+ a_matrix,
+ h_cvx,
+ g_matrix,
+ cost_vec,
+ incidence_matrix,
+ ini,
+ fin_vec,
+ lp_solver.DEFAULT_LP_SOLVER_VARIANT,
+ use_cvxopt=use_cvxopt,
+ )
+ ini_state = utils.SearchTuple(0 + h, 0, h, ini, None, None, x, True)
+ open_set = [ini_state]
+ heapq.heapify(open_set)
+ visited = 0
+ queued = 0
+ traversed = 0
+
+ trans_empty_preset = set(t for t in net.transitions if len(t.in_arcs) == 0)
+
+ while not len(open_set) == 0:
+ curr = heapq.heappop(open_set)
+
+ current_marking = curr.m
+ # 11/10/2019 (optimization Y, that was optimization X,
+ # but with the good reasons this way): avoid checking markings in the cycle using
+ # the __get_alt function, but check them 'on the road'
+ already_closed = current_marking in closed
+ if already_closed:
+ continue
+
+ while not curr.trust:
+ h, x = utils.__compute_exact_heuristic_new_version(
+ net,
+ a_matrix,
+ h_cvx,
+ g_matrix,
+ cost_vec,
+ incidence_matrix,
+ curr.m,
+ fin_vec,
+ lp_solver.DEFAULT_LP_SOLVER_VARIANT,
+ use_cvxopt=use_cvxopt,
+ )
+
+ # 11/10/19: shall not a state for which we compute the exact heuristics be
+ # by nature a trusted solution?
+ tp = utils.SearchTuple(
+ curr.g + h, curr.g, h, curr.m, curr.p, curr.t, x, True
+ )
+ # 11/10/2019 (optimization ZA) heappushpop is slightly more efficient than pushing
+ # and popping separately
+ curr = heapq.heappushpop(open_set, tp)
+ current_marking = curr.m
+
+ # max allowed heuristics value (27/10/2019, due to the numerical
+ # instability of some of our solvers)
+ if curr.h > lp_solver.MAX_ALLOWED_HEURISTICS:
+ continue
+
+ # 12/10/2019: do it again, since the marking could be changed
+ already_closed = current_marking in closed
+ if already_closed:
+ continue
+
+ # 12/10/2019: the current marking can be equal to the final marking only if the heuristics
+ # (underestimation of the remaining cost) is 0. Low-hanging fruits
+ if curr.h < 0.01:
+ if current_marking == fin:
+ return utils.__reconstruct_alignment(
+ curr, visited, queued, traversed
+ )
+
+ closed.add(current_marking)
+ visited += 1
+
+ possible_enabling_transitions = copy(trans_empty_preset)
+ for p in current_marking:
+ for t in p.ass_trans:
+ possible_enabling_transitions.add(t)
+
+ enabled_trans = [
+ t
+ for t in possible_enabling_transitions
+ if t.sub_marking <= current_marking
+ ]
+
+ trans_to_visit_with_cost = [
+ (t, cost_function[t]) for t in enabled_trans
+ ]
+
+ for t, cost in trans_to_visit_with_cost:
+ traversed += 1
+ new_marking = utils.add_markings(current_marking, t.add_marking)
+
+ if new_marking in closed:
+ continue
+ g = curr.g + cost
+
+ queued += 1
+ h, x = utils.__derive_heuristic(
+ incidence_matrix, cost_vec, curr.x, t, curr.h
+ )
+ trustable = utils.__trust_solution(x)
+ new_f = g + h
+
+ tp = utils.SearchTuple(
+ new_f, g, h, new_marking, curr, t, x, trustable
+ )
+ heapq.heappush(open_set, tp)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/final_marking.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/final_marking.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a69b1e4d547293f7f426581bd1c60fe6d2d2b61
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/final_marking.py
@@ -0,0 +1,45 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.obj import Marking
+
+
+def discover_final_marking(petri):
+ """
+ Discovers final marking from a Petri net
+
+ Parameters
+ -----------
+ petri
+ Petri net
+
+ Returns
+ -----------
+ final_marking
+ Final marking
+ """
+ final_marking = Marking()
+
+ for place in petri.places:
+ if len(place.out_arcs) == 0:
+ final_marking[place] = 1
+
+ return final_marking
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/incidence_matrix.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/incidence_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d8d835dd30b361b0756a3e1940cc0f9b4f931f0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/incidence_matrix.py
@@ -0,0 +1,74 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+class IncidenceMatrix(object):
+
+ def __init__(self, net):
+ self.__A, self.__place_indices, self.__transition_indices = (
+ self.__construct_matrix(net)
+ )
+
+ def encode_marking(self, marking):
+ x = [0 for i in range(len(self.places))]
+ for p in marking:
+ x[self.places[p]] = marking[p]
+ return x
+
+ def __get_a_matrix(self):
+ return self.__A
+
+ def __get_transition_indices(self):
+ return self.__transition_indices
+
+ def __get_place_indices(self):
+ return self.__place_indices
+
+ def __construct_matrix(self, net):
+ self.matrix_built = True
+ p_index, t_index = {}, {}
+ places = sorted(
+ [x for x in net.places], key=lambda x: (str(x.name), id(x))
+ )
+ transitions = sorted(
+ [x for x in net.transitions], key=lambda x: (str(x.name), id(x))
+ )
+
+ for p in places:
+ p_index[p] = len(p_index)
+ for t in transitions:
+ t_index[t] = len(t_index)
+ a_matrix = [
+ [0 for i in range(len(t_index))] for j in range(len(p_index))
+ ]
+ for p in net.places:
+ for a in p.in_arcs:
+ a_matrix[p_index[p]][t_index[a.source]] += 1
+ for a in p.out_arcs:
+ a_matrix[p_index[p]][t_index[a.target]] -= 1
+ return a_matrix, p_index, t_index
+
+ a_matrix = property(__get_a_matrix)
+ places = property(__get_place_indices)
+ transitions = property(__get_transition_indices)
+
+
+def construct(net):
+ return IncidenceMatrix(net)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/initial_marking.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/initial_marking.py
new file mode 100644
index 0000000000000000000000000000000000000000..99245fc322a4048f2126e45ba60761a6eee16b3a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/initial_marking.py
@@ -0,0 +1,45 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.obj import Marking
+
+
+def discover_initial_marking(petri):
+ """
+ Discovers initial marking from a Petri net
+
+ Parameters
+ ------------
+ petri
+ Petri net
+
+ Returns
+ ------------
+ initial_marking
+ Initial marking of the Petri net
+ """
+ initial_marking = Marking()
+
+ for place in petri.places:
+ if len(place.in_arcs) == 0:
+ initial_marking[place] = 1
+
+ return initial_marking
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/label_replacing.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/label_replacing.py
new file mode 100644
index 0000000000000000000000000000000000000000..388a83297ad1e595b8258779f568f5aaf1bcf693
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/label_replacing.py
@@ -0,0 +1,60 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from typing import Optional, Dict, Any, Tuple
+from copy import deepcopy
+
+
+def apply(net: PetriNet, initial_marking: Marking, final_marking: Marking, string_dictio: Dict[str, str], parameters: Optional[Dict[Any, Any]] = None) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Replaces the labels in the provided accepting Petri net using the provided correspondence dictionary.
+
+ Parameters
+ ----------------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ final_marking
+ Final marking
+ string_dictio
+ Correspondence dictionary (old labels -> new labels)
+
+ Returns
+ ----------------
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ final_marking
+ Final marking
+ """
+ if parameters is None:
+ parameters = {}
+
+ net, initial_marking, final_marking = deepcopy([net, initial_marking, final_marking])
+
+ for trans in net.transitions:
+ if trans.label is not None and trans.label in string_dictio:
+ trans.label = string_dictio[trans.label]
+
+ return net, initial_marking, final_marking
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/murata.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/murata.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1e1003ab9c317f496b352ad1d3aeca336572314
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/murata.py
@@ -0,0 +1,212 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.util.lp import solver
+from pm4py.util import constants
+from pm4py.objects.petri_net.utils.petri_utils import remove_place
+from typing import Tuple
+import warnings
+import importlib.util
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+
+
+def apply_reduction(
+ net: PetriNet, im: Marking, fm: Marking
+) -> Tuple[PetriNet, Marking, Marking]:
+ """
+ Apply the Murata reduction to an accepting Petri net, removing structurally redundant (implicit) places.
+
+ This implementation follows the (Berthelot) implicit-place check by searching, via ILP,
+ for a place-flow f = a_p * p - Σ a_q * q (a_p >= 1, a_q >= 0) such that:
+
+ (1) f is a P-invariant (flow): a_p*C(p,t) - Σ a_q*C(q,t) = 0 for all transitions t
+ where C(p,t) = Post(p,t) - Pre(p,t)
+
+ (2) a_p*Pre(p,t) - Σ a_q*Pre(q,t) <= k for all transitions t
+ with k = a_p*M0(p) - Σ a_q*M0(q), and k >= 0
+
+ If such a solution exists, the candidate place is implicit and can be removed without changing behavior.
+
+ Parameters
+ ---------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+
+ Returns
+ --------------
+ net
+ Reduced Petri net
+ im
+ Initial marking (unchanged)
+ fm
+ Final marking (unchanged)
+ """
+ places = sorted(list(net.places), key=lambda x: x.name)
+ redundant = set()
+
+ # Choose solver backend
+ proposed_solver = solver.SCIPY
+ if importlib.util.find_spec("pulp"):
+ proposed_solver = solver.PULP
+ else:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "solution from scipy may be unstable. Please install PuLP (pip install pulp) for fully reliable results."
+ )
+
+ for place in places:
+ # Skip already proven redundant places
+ if place in redundant:
+ continue
+
+ # Skip places in the initial or final markings
+ if place in im or place in fm:
+ continue
+
+ # Work on the "current" net as if previously found redundant places were removed:
+ active_places = [p for p in places if p not in redundant]
+ active_places = sorted(active_places, key=lambda x: x.name)
+ place_index = {p: i for i, p in enumerate(active_places)}
+
+ n_places = len(active_places)
+ n_vars = n_places + 1 # last variable is k
+ k_idx = n_vars - 1
+
+ Aeq = []
+ Aub = []
+ beq = []
+ bub = []
+
+ # ---------------------------------------------------------------------
+ # (A) k = a_p*M0(p) - Σ a_q*M0(q)
+ # => a_p*M0(p) - Σ a_q*M0(q) - k = 0
+ # ---------------------------------------------------------------------
+ eq = [0] * n_vars
+ for p2 in active_places:
+ m0 = im[p2] if p2 in im else 0
+ if m0 == 0:
+ continue
+ if p2 == place:
+ eq[place_index[p2]] += m0
+ else:
+ eq[place_index[p2]] -= m0
+ eq[k_idx] = -1
+ Aeq.append(eq)
+ beq.append(0)
+
+ # ---------------------------------------------------------------------
+ # (B) Flow constraints: for all transitions t,
+ # a_p*C(p,t) - Σ a_q*C(q,t) = 0
+ # where C(p,t)=Post(p,t)-Pre(p,t)
+ # ---------------------------------------------------------------------
+ for trans in net.transitions:
+ pre = {}
+ post = {}
+
+ for arc in trans.in_arcs:
+ src = arc.source
+ if src in place_index:
+ pre[src] = pre.get(src, 0) + arc.weight
+
+ for arc in trans.out_arcs:
+ tgt = arc.target
+ if tgt in place_index:
+ post[tgt] = post.get(tgt, 0) + arc.weight
+
+ eq = [0] * n_vars
+ for p2 in active_places:
+ c_val = post.get(p2, 0) - pre.get(p2, 0)
+ if c_val == 0:
+ continue
+ if p2 == place:
+ eq[place_index[p2]] += c_val
+ else:
+ eq[place_index[p2]] -= c_val
+ # k has coefficient 0 here
+ Aeq.append(eq)
+ beq.append(0)
+
+ # ---------------------------------------------------------------------
+ # (C) Implicitness inequalities: for all transitions t,
+ # a_p*Pre(p,t) - Σ a_q*Pre(q,t) - k <= 0
+ # ---------------------------------------------------------------------
+ for trans in net.transitions:
+ ineq = [0] * n_vars
+ for arc in trans.in_arcs:
+ p2 = arc.source
+ if p2 not in place_index:
+ continue
+ if p2 == place:
+ ineq[place_index[p2]] += arc.weight
+ else:
+ ineq[place_index[p2]] -= arc.weight
+ ineq[k_idx] = -1
+ Aub.append(ineq)
+ bub.append(0)
+
+ # ---------------------------------------------------------------------
+ # (D) Variable lower bounds:
+ # a_p >= 1, a_q >= 0, k >= 0
+ # Implemented as -a <= b
+ # ---------------------------------------------------------------------
+ for p2 in active_places:
+ ineq = [0] * n_vars
+ ineq[place_index[p2]] = -1
+ Aub.append(ineq)
+ if p2 == place:
+ bub.append(-1) # -a_p <= -1 -> a_p >= 1
+ else:
+ bub.append(0) # -a_q <= 0 -> a_q >= 0
+
+ ineq = [0] * n_vars
+ ineq[k_idx] = -1
+ Aub.append(ineq)
+ bub.append(0) # -k <= 0 -> k >= 0
+
+ # Objective (any feasible solution is enough; minimize sum to keep it small)
+ c = [1] * n_vars
+ integrality = [1] * n_vars
+
+ xx = solver.apply(
+ c,
+ Aub,
+ bub,
+ Aeq,
+ beq,
+ variant=proposed_solver,
+ parameters={"integrality": integrality},
+ )
+
+ if (hasattr(xx, "success") and xx.success) or (
+ hasattr(xx, "sol_status") and xx.sol_status > -1
+ ):
+ redundant.add(place)
+
+ # Remove redundant places (deterministic order)
+ for pl in sorted(list(redundant), key=lambda x: x.name):
+ net = remove_place(net, pl)
+
+ return net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/networkx_graph.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/networkx_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..81d9380c13ef30856178f5062abab28127bbcd8d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/networkx_graph.py
@@ -0,0 +1,141 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.obj import PetriNet
+from pm4py.util import nx_utils
+
+
+def create_networkx_undirected_graph(net, unique_source, unique_sink):
+ """
+ Create a NetworkX undirected graph from a Petri net, returning also correspondences for the unique
+ source and the unique sink places that were discovered
+
+ Parameters
+ -------------
+ net
+ Petri net
+ unique_source
+ Unique source place
+ unique_sink
+ Unique sink place
+
+ Returns
+ -------------
+ graph
+ NetworkX graph
+ unique_source_corr
+ Correspondence in the NetworkX graph of the unique source place
+ unique_sink_corr
+ Correspondence in the NetworkX graph of the unique sink place
+ inv_dictionary
+ Correspondence between NetworkX nodes and Petri net entities
+ """
+ graph = nx_utils.Graph()
+ dictionary = {}
+ inv_dictionary = {}
+ for place in net.places:
+ value = len(dictionary)
+ dictionary[place] = value
+ inv_dictionary[value] = place
+ graph.add_node(dictionary[place])
+ for transition in net.transitions:
+ value = len(dictionary)
+ dictionary[transition] = value
+ inv_dictionary[value] = transition
+ graph.add_node(dictionary[transition])
+ for arc in net.arcs:
+ graph.add_edge(dictionary[arc.source], dictionary[arc.target])
+ unique_source_corr = (
+ dictionary[unique_source] if unique_source in dictionary else None
+ )
+ unique_sink_corr = (
+ dictionary[unique_sink] if unique_sink in dictionary else None
+ )
+
+ return graph, unique_source_corr, unique_sink_corr, inv_dictionary
+
+
+def create_networkx_directed_graph(net, weight=None):
+ """
+ Create a NetworkX directed graph from a Petri net
+
+ Parameters
+ --------------
+ net
+ Petri net
+
+ Returns
+ --------------
+ graph
+ NetworkX digraph
+ inv_dictionary
+ Correspondence between NetworkX nodes and Petri net entities
+ """
+ # forward to new function
+ G, d, id = create_networkx_directed_graph_ret_dict_both_ways(net, weight)
+ return G, id
+
+
+def create_networkx_directed_graph_ret_dict_both_ways(net, weight=None):
+ """
+ Create a NetworkX directed graph from a Petri net
+
+ Parameters
+ --------------
+ net
+ Petri net
+
+ Returns
+ --------------
+ graph
+ NetworkX digraph
+ dictionary
+ dict mapping Petri net nodes to NetworkX nodes
+ inv_dictionary
+ dict mapping NetworkX nodes to Petri net nodes
+ """
+ graph = nx_utils.DiGraph()
+ dictionary = {}
+ inv_dictionary = {}
+ for place in net.places:
+ value = len(dictionary)
+ dictionary[place] = value
+ inv_dictionary[value] = place
+ graph.add_node(dictionary[place])
+ for transition in net.transitions:
+ value = len(dictionary)
+ dictionary[transition] = value
+ inv_dictionary[value] = transition
+ graph.add_node(dictionary[transition])
+ for arc in net.arcs:
+ source = dictionary[arc.source]
+ target = dictionary[arc.target]
+ graph.add_edge(source, target)
+ if weight is not None:
+ if type(inv_dictionary[source]) is PetriNet.Transition:
+ graph.edges[source, target]["weight"] = weight[
+ inv_dictionary[source]
+ ]
+ else:
+ graph.edges[source, target]["weight"] = weight[
+ inv_dictionary[target]
+ ]
+ return graph, dictionary, inv_dictionary
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/obj_marking.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/obj_marking.py
new file mode 100644
index 0000000000000000000000000000000000000000..4544023e5895619763e5ee7b775b300870f72c8a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/obj_marking.py
@@ -0,0 +1,134 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import random
+
+
+class ObjMarking(dict):
+ def __init__(self, *args, **kwargs):
+ self.picked_items = set()
+ self.update(*args, **kwargs)
+
+ def __getitem_original__(self, key):
+ if key in self:
+ return dict.__getitem__(self, key)
+ return {}
+
+ def __getitem__(self, key):
+ return ObjMarkingAccessor(self, key)
+
+ def __setitem__(self, key, val):
+ dict.__setitem__(self, key, val)
+
+ def update(self, *args, **kwargs):
+ for k, v in dict(*args, **kwargs).items():
+ self[k] = v
+
+
+class ObjMarkingAccessor(object):
+ def __init__(self, obj_marking, key):
+ self.obj_marking = obj_marking
+ self.key = key
+
+ def __sub__(self, other):
+ if isinstance(other, int):
+ picked_items = set(
+ random.sample(
+ self.obj_marking.__getitem_original__(self.key),
+ min(
+ len(self.obj_marking.__getitem_original__(self.key)),
+ other,
+ ),
+ )
+ )
+ self.obj_marking.picked_items = picked_items
+ diff = self.obj_marking.__getitem_original__(self.key).difference(
+ picked_items
+ )
+ return diff
+ else:
+ diff = self.obj_marking.__getitem_original__(self.key).difference(
+ other
+ )
+ return diff
+
+ def __add__(self, other):
+ if isinstance(other, int):
+ picked_items = set(
+ random.sample(self.obj_marking.picked_items, other)
+ )
+ if self.key not in self.obj_marking:
+ self.obj_marking[self.key] = set()
+ new_value = self.obj_marking.__getitem_original__(self.key).union(
+ picked_items
+ )
+ self.obj_marking[self.key] = new_value
+ return new_value
+ else:
+ new_value = self.obj_marking.__getitem_original__(self.key).union(
+ other
+ )
+ self.obj_marking[self.key] = new_value
+ return new_value
+
+ def __repr__(self):
+ return str(self.obj_marking.__getitem_original__(self.key))
+
+ def __str__(self):
+ return str(self.obj_marking.__getitem_original__(self.key))
+
+ def __lt__(self, other):
+ if isinstance(other, int):
+ if len(self.obj_marking.__getitem_original__(self.key)) < other:
+ return True
+ return False
+
+ def __le__(self, other):
+ if isinstance(other, int):
+ if len(self.obj_marking.__getitem_original__(self.key)) <= other:
+ return True
+ return False
+
+ def __gt__(self, other):
+ if isinstance(other, int):
+ if len(self.obj_marking.__getitem_original__(self.key)) > other:
+ return True
+ return False
+
+ def __ge__(self, other):
+ if isinstance(other, int):
+ if len(self.obj_marking.__getitem_original__(self.key)) >= other:
+ return True
+ return False
+
+ def __lt__(self, other):
+ if isinstance(other, int):
+ if len(self.obj_marking.__getitem_original__(self.key)) < other:
+ return True
+ return False
+
+ def __eq__(self, other):
+ if isinstance(other, int):
+ if len(self.obj_marking.__getitem_original__(self.key)) <= other:
+ return True
+ return False
+ else:
+ return self.__dict__ == other.__dict__
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/performance_map.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/performance_map.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9dfb97ded200cd6eb2f2e241b718d1337d2eeee
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/performance_map.py
@@ -0,0 +1,720 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from copy import copy
+
+from pm4py.objects.petri_net import semantics
+from pm4py.objects.petri_net.obj import PetriNet
+from pm4py.util.vis_utils import (
+ human_readable_stat,
+ get_arc_penwidth,
+ get_trans_freq_color,
+)
+from pm4py.objects.log.obj import EventLog
+from pm4py.util.business_hours import BusinessHours
+from pm4py.util import constants
+
+MAX_NO_THREADS = 1000
+
+
+def calculate_annotation_for_trace(
+ trace, net, initial_marking, act_trans, activity_key, ht_perf_method="last"
+):
+ """
+ Calculate annotation for a trace in the variant, in order to retrieve information
+ useful for calculate frequency/performance for all the traces belonging to the variant
+
+ Parameters
+ -----------
+ trace
+ Trace
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ act_trans
+ Activated transitions during token replay of the given trace
+ activity_key
+ Attribute that identifies the activity (must be specified if different from concept:name)
+ ht_perf_method
+ Method to use in order to annotate hidden transitions (performance value could be put on the last possible
+ point (last) or in the first possible point (first)
+
+ Returns
+ ----------
+ annotation
+ Statistics annotation for the given trace
+ """
+ annotations_places_trans = {}
+ annotations_arcs = {}
+ trace_place_stats = {}
+ current_trace_index = 0
+ j = 0
+ marking = copy(initial_marking)
+ for place in marking:
+ if place not in annotations_places_trans:
+ annotations_places_trans[place] = {"count": 0}
+ annotations_places_trans[place]["count"] = (
+ annotations_places_trans[place]["count"] + marking[place]
+ )
+ trace_place_stats[place] = [current_trace_index] * marking[place]
+
+ for z in range(len(act_trans)):
+ enabled_trans_in_marking = semantics.enabled_transitions(net, marking)
+ # print("enabled_trans_in_marking", enabled_trans_in_marking)
+
+ for trans in enabled_trans_in_marking:
+ if trans not in annotations_places_trans:
+ annotations_places_trans[trans] = {
+ "count": 0,
+ "performance": [],
+ "no_of_times_enabled": 0,
+ "no_of_times_activated": 0,
+ }
+ annotations_places_trans[trans]["no_of_times_enabled"] = (
+ annotations_places_trans[trans]["no_of_times_enabled"] + 1
+ )
+
+ trans = act_trans[z]
+ if trans not in annotations_places_trans:
+ annotations_places_trans[trans] = {
+ "count": 0,
+ "performance": [],
+ "no_of_times_enabled": 0,
+ "no_of_times_activated": 0,
+ }
+ annotations_places_trans[trans]["count"] = (
+ annotations_places_trans[trans]["count"] + 1
+ )
+ if trans not in enabled_trans_in_marking:
+ annotations_places_trans[trans]["no_of_times_enabled"] = (
+ annotations_places_trans[trans]["no_of_times_enabled"] + 1
+ )
+ annotations_places_trans[trans]["no_of_times_activated"] = (
+ annotations_places_trans[trans]["no_of_times_activated"] + 1
+ )
+
+ new_marking = semantics.weak_execute(trans, marking)
+ if not new_marking:
+ break
+ marking_diff = set(new_marking).difference(set(marking))
+ for place in marking_diff:
+ if place not in annotations_places_trans:
+ annotations_places_trans[place] = {"count": 0}
+ annotations_places_trans[place]["count"] = (
+ annotations_places_trans[place]["count"]
+ + max(new_marking[place] - marking[place], 1)
+ )
+ marking = new_marking
+ if j < len(trace):
+ current_trace_index = j
+ if trans.label == trace[j][activity_key]:
+ j = j + 1
+
+ in_arc_indexes = [
+ trace_place_stats[arc.source][0]
+ for arc in trans.in_arcs
+ if arc.source in trace_place_stats
+ and trace_place_stats[arc.source]
+ ]
+ if in_arc_indexes:
+ min_in_arc_indexes = min(in_arc_indexes)
+ max_in_arc_indexes = max(in_arc_indexes)
+ else:
+ min_in_arc_indexes = None
+ max_in_arc_indexes = None
+ performance_for_this_trans_execution = []
+
+ for arc in trans.in_arcs:
+ source_place = arc.source
+ if arc not in annotations_arcs:
+ annotations_arcs[arc] = {"performance": [], "count": 0}
+ annotations_arcs[arc]["count"] = annotations_arcs[arc]["count"] + 1
+ if (
+ source_place in trace_place_stats
+ and trace_place_stats[source_place]
+ ):
+ if trans.label or ht_perf_method == "first":
+ annotations_arcs[arc]["performance"].append(
+ [
+ current_trace_index,
+ trace_place_stats[source_place][0],
+ ]
+ )
+ performance_for_this_trans_execution.append(
+ [
+ [
+ current_trace_index,
+ trace_place_stats[source_place][0],
+ ],
+ current_trace_index
+ - trace_place_stats[source_place][0],
+ ]
+ )
+ elif min_in_arc_indexes:
+ annotations_arcs[arc]["performance"].append(
+ [current_trace_index, current_trace_index]
+ )
+ performance_for_this_trans_execution.append(
+ [[current_trace_index, current_trace_index], 0]
+ )
+
+ del trace_place_stats[source_place][0]
+ for arc in trans.out_arcs:
+ target_place = arc.target
+ if arc not in annotations_arcs:
+ annotations_arcs[arc] = {"performance": [], "count": 0}
+ annotations_arcs[arc]["count"] = annotations_arcs[arc]["count"] + 1
+ if target_place not in trace_place_stats:
+ trace_place_stats[target_place] = []
+
+ if trans.label or ht_perf_method == "first":
+ trace_place_stats[target_place].append(current_trace_index)
+ elif max_in_arc_indexes:
+ trace_place_stats[target_place].append(max_in_arc_indexes)
+
+ if performance_for_this_trans_execution:
+ performance_for_this_trans_execution = sorted(
+ performance_for_this_trans_execution, key=lambda x: x[1]
+ )
+
+ annotations_places_trans[trans]["performance"].append(
+ performance_for_this_trans_execution[0][0]
+ )
+
+ return annotations_places_trans, annotations_arcs
+
+
+def single_element_statistics(
+ log,
+ net,
+ initial_marking,
+ aligned_traces,
+ variants_idx,
+ activity_key="concept:name",
+ timestamp_key="time:timestamp",
+ ht_perf_method="last",
+ parameters=None,
+):
+ """
+ Get single Petrinet element statistics
+
+ Parameters
+ ------------
+ log
+ Log
+ net
+ Petri net
+ initial_marking
+ Initial marking
+ aligned_traces
+ Result of the token-based replay
+ variants_idx
+ Variants along with indexes of belonging traces
+ activity_key
+ Activity key (must be specified if different from concept:name)
+ timestamp_key
+ Timestamp key (must be specified if different from time:timestamp)
+ ht_perf_method
+ Method to use in order to annotate hidden transitions (performance value could be put on the last possible
+ point (last) or in the first possible point (first)
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ ------------
+ statistics
+ Petri net element statistics (frequency, unaggregated performance)
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.objects.conversion.log import converter as log_converter
+
+ log = log_converter.apply(
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
+ )
+
+ business_hours = (
+ parameters["business_hours"]
+ if "business_hours" in parameters
+ else False
+ )
+ business_hours_slots = (
+ parameters["business_hour_slots"]
+ if "business_hour_slots" in parameters
+ else constants.DEFAULT_BUSINESS_HOUR_SLOTS
+ )
+ count_once_per_trace = (
+ parameters["count_once_per_trace"]
+ if "count_once_per_trace" in parameters
+ else False
+ )
+
+ statistics = {}
+
+ for variant in variants_idx:
+ first_trace = log[variants_idx[variant][0]]
+ act_trans0 = aligned_traces[variants_idx[variant][0]][
+ "activated_transitions"
+ ]
+ act_trans = []
+ if count_once_per_trace:
+ for t in act_trans0:
+ if t not in act_trans:
+ act_trans.append(t)
+ else:
+ act_trans = act_trans0
+ annotations_places_trans, annotations_arcs = (
+ calculate_annotation_for_trace(
+ first_trace,
+ net,
+ initial_marking,
+ act_trans,
+ activity_key,
+ ht_perf_method=ht_perf_method,
+ )
+ )
+
+ for el in annotations_places_trans:
+ if el not in statistics:
+ statistics[el] = {
+ "count": 0,
+ "performance": [],
+ "log_idx": [],
+ "no_of_times_enabled": 0,
+ "no_of_times_activated": 0,
+ }
+ statistics[el]["count"] += annotations_places_trans[el][
+ "count"
+ ] * len(variants_idx[variant])
+ if "no_of_times_enabled" in annotations_places_trans[el]:
+ statistics[el][
+ "no_of_times_enabled"
+ ] += annotations_places_trans[el]["no_of_times_enabled"] * len(
+ variants_idx[variant]
+ )
+ statistics[el][
+ "no_of_times_activated"
+ ] += annotations_places_trans[el][
+ "no_of_times_activated"
+ ] * len(
+ variants_idx[variant]
+ )
+
+ if "performance" in annotations_places_trans[el]:
+ for trace_idx in variants_idx[variant]:
+ trace = log[trace_idx]
+ for perf_couple in annotations_places_trans[el][
+ "performance"
+ ]:
+ if (
+ timestamp_key in trace[perf_couple[0]]
+ and timestamp_key in trace[perf_couple[1]]
+ ):
+ if business_hours:
+ bh = BusinessHours(
+ trace[perf_couple[1]][timestamp_key],
+ trace[perf_couple[0]][timestamp_key],
+ business_hour_slots=business_hours_slots,
+ )
+ perf = bh.get_seconds()
+ else:
+ perf = (
+ trace[perf_couple[0]][timestamp_key]
+ - trace[perf_couple[1]][timestamp_key]
+ ).total_seconds()
+ else:
+ perf = 0.0
+ statistics[el]["performance"].append(perf)
+ statistics[el]["log_idx"].append(trace_idx)
+ for el in annotations_arcs:
+ if el not in statistics:
+ statistics[el] = {"count": 0, "performance": []}
+ statistics[el]["count"] += annotations_arcs[el]["count"] * len(
+ variants_idx[variant]
+ )
+ for trace_idx in variants_idx[variant]:
+ trace = log[trace_idx]
+ for perf_couple in annotations_arcs[el]["performance"]:
+ if (
+ timestamp_key in trace[perf_couple[0]]
+ and timestamp_key in trace[perf_couple[1]]
+ ):
+ if business_hours:
+ bh = BusinessHours(
+ trace[perf_couple[1]][timestamp_key],
+ trace[perf_couple[0]][timestamp_key],
+ business_hour_slots=business_hours_slots,
+ )
+ perf = bh.get_seconds()
+ else:
+ perf = (
+ trace[perf_couple[0]][timestamp_key]
+ - trace[perf_couple[1]][timestamp_key]
+ ).total_seconds()
+ else:
+ perf = 0.0
+ statistics[el]["performance"].append(perf)
+
+ return statistics
+
+
+def find_min_max_trans_frequency(statistics):
+ """
+ Find minimum and maximum transition frequency
+
+ Parameters
+ -----------
+ statistics
+ Element statistics
+
+ Returns
+ ----------
+ min_frequency
+ Minimum transition frequency (in the replay)
+ max_frequency
+ Maximum transition frequency (in the replay)
+ """
+ min_frequency = 9999999999
+ max_frequency = 0
+ for elem in statistics.keys():
+ if type(elem) is PetriNet.Transition:
+ if statistics[elem]["count"] < min_frequency:
+ min_frequency = statistics[elem]["count"]
+ if statistics[elem]["count"] > max_frequency:
+ max_frequency = statistics[elem]["count"]
+ return min_frequency, max_frequency
+
+
+def find_min_max_arc_frequency(statistics):
+ """
+ Find minimum and maximum arc frequency
+
+ Parameters
+ -----------
+ statistics
+ Element statistics
+
+ Returns
+ -----------
+ min_frequency
+ Minimum arc frequency
+ max_frequency
+ Maximum arc frequency
+ """
+ min_frequency = 9999999999
+ max_frequency = 0
+ for elem in statistics.keys():
+ if type(elem) is PetriNet.Arc:
+ if statistics[elem]["count"] < min_frequency:
+ min_frequency = statistics[elem]["count"]
+ if statistics[elem]["count"] > max_frequency:
+ max_frequency = statistics[elem]["count"]
+ return min_frequency, max_frequency
+
+
+def aggregate_stats(statistics, elem, aggregation_measure):
+ """
+ Aggregate the statistics
+
+ Parameters
+ -----------
+ statistics
+ Element statistics
+ elem
+ Current element
+ aggregation_measure
+ Aggregation measure (e.g. mean, min) to use
+
+ Returns
+ -----------
+ aggr_stat
+ Aggregated statistics
+ """
+ from statistics import median, mean
+ from statistics import stdev
+
+ aggr_stat = 0
+ if aggregation_measure == "mean" or aggregation_measure is None:
+ aggr_stat = mean(statistics[elem]["performance"])
+ elif aggregation_measure == "median":
+ aggr_stat = median(statistics[elem]["performance"])
+ elif aggregation_measure == "stdev":
+ aggr_stat = stdev(statistics[elem]["performance"])
+ elif aggregation_measure == "sum":
+ aggr_stat = sum(statistics[elem]["performance"])
+ elif aggregation_measure == "min":
+ aggr_stat = min(statistics[elem]["performance"])
+ elif aggregation_measure == "max":
+ aggr_stat = max(statistics[elem]["performance"])
+
+ return aggr_stat
+
+
+def find_min_max_arc_performance(statistics, aggregation_measure):
+ """
+ Find minimum and maximum arc performance
+
+ Parameters
+ -----------
+ statistics
+ Element statistics
+ aggregation_measure
+ Aggregation measure (e.g. mean, min) to use
+
+ Returns
+ -----------
+ min_performance
+ Minimum performance
+ max_performance
+ Maximum performance
+ """
+ min_performance = 9999999999
+ max_performance = 0
+ for elem in statistics.keys():
+ if type(elem) is PetriNet.Arc:
+ if statistics[elem]["performance"]:
+ aggr_stat = aggregate_stats(
+ statistics, elem, aggregation_measure
+ )
+ if aggr_stat < min_performance:
+ min_performance = aggr_stat
+ if aggr_stat > max_performance:
+ max_performance = aggr_stat
+ return min_performance, max_performance
+
+
+def aggregate_statistics(
+ statistics,
+ measure="frequency",
+ aggregation_measure=None,
+ business_hour_slots=None,
+):
+ """
+ Gets aggregated statistics
+
+ Parameters
+ ----------
+ statistics
+ Individual element statistics (including unaggregated performances)
+ measure
+ Desidered view on data (frequency or performance)
+ aggregation_measure
+ Aggregation measure (e.g. mean, min) to use
+ business_hour_slots
+ Optional weekly schedule used to express durations in working days
+
+ Returns
+ ----------
+ aggregated_statistics
+ Aggregated statistics for arcs, transitions, places
+ """
+ min_trans_frequency, max_trans_frequency = find_min_max_trans_frequency(
+ statistics
+ )
+ min_arc_frequency, max_arc_frequency = find_min_max_arc_frequency(
+ statistics
+ )
+ min_arc_performance, max_arc_performance = find_min_max_arc_performance(
+ statistics, aggregation_measure
+ )
+ aggregated_statistics = {}
+ for elem in statistics.keys():
+ if type(elem) is PetriNet.Arc:
+ if measure == "frequency":
+ freq = statistics[elem]["count"]
+ arc_penwidth = get_arc_penwidth(
+ freq, min_arc_frequency, max_arc_frequency
+ )
+ aggregated_statistics[elem] = {
+ "label": str(freq),
+ "penwidth": str(arc_penwidth),
+ }
+ elif measure == "performance":
+ if statistics[elem]["performance"]:
+ aggr_stat = aggregate_stats(
+ statistics, elem, aggregation_measure
+ )
+ aggr_stat_hr = human_readable_stat(
+ aggr_stat,
+ business_hour_slots=business_hour_slots,
+ )
+ arc_penwidth = get_arc_penwidth(
+ aggr_stat, min_arc_performance, max_arc_performance
+ )
+ aggregated_statistics[elem] = {
+ "label": aggr_stat_hr,
+ "penwidth": str(arc_penwidth),
+ }
+ elif type(elem) is PetriNet.Transition:
+ if measure == "frequency":
+ if elem.label is not None:
+ freq = statistics[elem]["count"]
+ color = get_trans_freq_color(
+ freq, min_trans_frequency, max_trans_frequency
+ )
+ aggregated_statistics[elem] = {
+ "label": elem.label + " (" + str(freq) + ")",
+ "color": color,
+ }
+ elif type(elem) is PetriNet.Place:
+ pass
+ return aggregated_statistics
+
+
+def get_transition_performance_with_token_replay(log, net, im, fm):
+ """
+ Gets the transition performance through the usage of token-based replay
+
+ Parameters
+ -------------
+ log
+ Event log
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+
+ Returns
+ --------------
+ transition_performance
+ Dictionary where each transition label is associated to performance measures
+ """
+ from statistics import median, mean, stdev
+
+ from pm4py.algo.conformance.tokenreplay import algorithm as token_replay
+ from pm4py.statistics.variants.log import get as variants_get
+
+ variants_idx = variants_get.get_variants_from_log_trace_idx(log)
+ aligned_traces = token_replay.apply(log, net, im, fm)
+ element_statistics = single_element_statistics(
+ log, net, im, aligned_traces, variants_idx
+ )
+
+ transition_performance = {}
+ for el in element_statistics:
+ if type(el) is PetriNet.Transition and el.label is not None:
+ if (
+ "log_idx" in element_statistics[el]
+ and "performance" in element_statistics[el]
+ ):
+ if len(element_statistics[el]["performance"]) > 0:
+ transition_performance[str(el)] = {
+ "all_values": [],
+ "case_association": {},
+ "mean": 0.0,
+ "median": 0.0,
+ }
+ for i in range(len(element_statistics[el]["log_idx"])):
+ if (
+ not element_statistics[el]["log_idx"][i]
+ in transition_performance[str(el)][
+ "case_association"
+ ]
+ ):
+ transition_performance[str(el)][
+ "case_association"
+ ][element_statistics[el]["log_idx"][i]] = []
+ transition_performance[str(el)]["case_association"][
+ element_statistics[el]["log_idx"][i]
+ ].append(element_statistics[el]["performance"][i])
+ transition_performance[str(el)]["all_values"].append(
+ element_statistics[el]["performance"][i]
+ )
+ transition_performance[str(el)]["all_values"] = sorted(
+ transition_performance[str(el)]["all_values"]
+ )
+ if transition_performance[str(el)]["all_values"]:
+ transition_performance[str(el)]["mean"] = mean(
+ transition_performance[str(el)]["all_values"]
+ )
+ transition_performance[str(el)]["median"] = median(
+ transition_performance[str(el)]["all_values"]
+ )
+ return transition_performance
+
+
+def get_idx_exceeding_specified_acti_performance(
+ log, transition_performance, activity, lower_bound
+):
+ """
+ Get indexes of the cases exceeding the specified activity performance threshold
+
+ Parameters
+ ------------
+ log
+ Event log
+ transition_performance
+ Dictionary where each transition label is associated to performance measures
+ activity
+ Target activity (of the filter)
+ lower_bound
+ Lower bound (filter cases which have a duration of the activity exceeding)
+
+ Returns
+ ------------
+ idx
+ A list of indexes in the log
+ """
+ satisfying_indexes = sorted(
+ list(
+ set(
+ x
+ for x, y in transition_performance[activity][
+ "case_association"
+ ].items()
+ if max(y) >= lower_bound
+ )
+ )
+ )
+ return satisfying_indexes
+
+
+def filter_cases_exceeding_specified_acti_performance(
+ log, transition_performance, activity, lower_bound
+):
+ """
+ Filter cases exceeding the specified activity performance threshold
+
+ Parameters
+ ------------
+ log
+ Event log
+ transition_performance
+ Dictionary where each transition label is associated to performance measures
+ activity
+ Target activity (of the filter)
+ lower_bound
+ Lower bound (filter cases which have a duration of the activity exceeding)
+
+ Returns
+ ------------
+ filtered_log
+ Filtered log
+ """
+ satisfying_indexes = get_idx_exceeding_specified_acti_performance(
+ log, transition_performance, activity, lower_bound
+ )
+ new_log = EventLog(list(log[i] for i in satisfying_indexes))
+ return new_log
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/petri_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/petri_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a95db6a3167ea32db8d9575d3cd6134d4f29183
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/petri_utils.py
@@ -0,0 +1,707 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import random
+import time
+
+from typing import Optional, Set
+from copy import copy, deepcopy
+
+from pm4py.objects.log.obj import Trace, Event
+from pm4py.objects.petri_net import semantics, properties
+from pm4py.objects.petri_net.obj import (
+ PetriNet,
+ Marking,
+ ResetNet,
+ InhibitorNet,
+)
+from pm4py.objects.petri_net.saw_net.obj import StochasticArcWeightNet
+from pm4py.util import xes_constants as xes_util
+
+
+def is_sub_marking(sub_marking: Marking, marking: Marking) -> bool:
+ for p in sub_marking:
+ if p not in marking:
+ return False
+ elif marking[p] > sub_marking[p]:
+ return False
+ return True
+
+
+def place_set_as_marking(places) -> Marking:
+ m = Marking()
+ for p in places:
+ m[p] = 1
+ return m
+
+
+def get_arc_type(elem):
+ if properties.ARCTYPE in elem.properties:
+ return elem.properties[properties.ARCTYPE]
+ return None
+
+
+def pre_set(elem, arc_type=None) -> Set:
+ pre = set()
+ for a in elem.in_arcs:
+ if get_arc_type(a) == arc_type:
+ pre.add(a.source)
+ return pre
+
+
+def post_set(elem, arc_type=None) -> Set:
+ post = set()
+ for a in elem.out_arcs:
+ if get_arc_type(a) == arc_type:
+ post.add(a.target)
+ return post
+
+
+def remove_transition(net: PetriNet, trans: PetriNet.Transition) -> PetriNet:
+ """
+ Remove a transition from a Petri net
+
+ Parameters
+ ----------
+ net
+ Petri net
+ trans
+ Transition to remove
+
+ Returns
+ ----------
+ net
+ Petri net
+ """
+ if trans in net.transitions:
+ in_arcs = trans.in_arcs
+ for arc in in_arcs:
+ place = arc.source
+ place.out_arcs.remove(arc)
+ net.arcs.remove(arc)
+ out_arcs = trans.out_arcs
+ for arc in out_arcs:
+ place = arc.target
+ place.in_arcs.remove(arc)
+ net.arcs.remove(arc)
+ net.transitions.remove(trans)
+ return net
+
+
+def add_place(net: PetriNet, name=None) -> PetriNet.Place:
+ name = (
+ name
+ if name is not None
+ else "p_"
+ + str(len(net.places))
+ + "_"
+ + str(time.time())
+ + str(random.randint(0, 10000))
+ )
+ p = PetriNet.Place(name=name)
+ net.places.add(p)
+ return p
+
+
+def add_transition(
+ net: PetriNet, name=None, label=None
+) -> PetriNet.Transition:
+ name = (
+ name
+ if name is not None
+ else "t_"
+ + str(len(net.transitions))
+ + "_"
+ + str(time.time())
+ + str(random.randint(0, 10000))
+ )
+ t = PetriNet.Transition(name=name, label=label)
+ net.transitions.add(t)
+ return t
+
+
+def merge(trgt: Optional[PetriNet] = None, nets=None) -> PetriNet:
+ trgt = trgt if trgt is not None else PetriNet()
+ nets = nets if nets is not None else list()
+ for net in nets:
+ trgt.transitions.update(net.transitions)
+ trgt.places.update(net.places)
+ trgt.arcs.update(net.arcs)
+ return trgt
+
+
+def remove_place(net: PetriNet, place: PetriNet.Place) -> PetriNet:
+ """
+ Remove a place from a Petri net
+
+ Parameters
+ -------------
+ net
+ Petri net
+ place
+ Place to remove
+
+ Returns
+ -------------
+ net
+ Petri net
+ """
+ if place in net.places:
+ in_arcs = place.in_arcs
+ for arc in in_arcs:
+ trans = arc.source
+ trans.out_arcs.remove(arc)
+ net.arcs.remove(arc)
+ out_arcs = place.out_arcs
+ for arc in out_arcs:
+ trans = arc.target
+ trans.in_arcs.remove(arc)
+ net.arcs.remove(arc)
+ net.places.remove(place)
+ return net
+
+
+def add_arc_from_to(
+ fr, to, net: PetriNet, weight=1, type=None
+) -> PetriNet.Arc:
+ """
+ Adds an arc from a specific element to another element in some net. Assumes from and to are in the net!
+
+ Parameters
+ ----------
+ fr: transition/place from
+ to: transition/place to
+ net: net to use
+ weight: weight associated to the arc
+
+ Returns
+ -------
+ None
+ """
+ if type == properties.INHIBITOR_ARC:
+ if isinstance(net, InhibitorNet):
+ a = InhibitorNet.InhibitorArc(fr, to, weight)
+ a.properties[properties.ARCTYPE] = type
+ else:
+ raise Exception(
+ "trying to add an inhibitor arc on a traditional Petri net object."
+ )
+ elif type == properties.RESET_ARC:
+ if isinstance(net, ResetNet):
+ a = ResetNet.ResetArc(fr, to, weight)
+ a.properties[properties.ARCTYPE] = type
+ else:
+ raise Exception(
+ "trying to add a reset arc on a traditional Petri net object."
+ )
+ elif type == properties.STOCHASTIC_ARC:
+ if isinstance(net, StochasticArcWeightNet):
+ a = StochasticArcWeightNet.Arc(fr, to, weight)
+ # a.properties[properties.ARCTYPE] = type
+ else:
+ raise Exception(
+ "trying to add a stochastic arc on a traditional Petri net object."
+ )
+ else:
+ a = PetriNet.Arc(fr, to, weight)
+ net.arcs.add(a)
+ fr.out_arcs.add(a)
+ to.in_arcs.add(a)
+
+ return a
+
+
+def construct_trace_net(
+ trace,
+ trace_name_key=xes_util.DEFAULT_NAME_KEY,
+ activity_key=xes_util.DEFAULT_NAME_KEY,
+):
+ """
+ Creates a trace net, i.e. a trace in Petri net form.
+
+ Parameters
+ ----------
+ trace: :class:`list` input trace, assumed to be a list of events
+ trace_name_key: :class:`str` key of the attribute that defines the name of the trace
+ activity_key: :class:`str` key of the attribute of the events that defines the activity name
+
+ Returns
+ -------
+ tuple: :class:`tuple` of the net, initial marking and the final marking
+
+ """
+ net = PetriNet(
+ "trace net of %s" % trace.attributes[trace_name_key]
+ if trace_name_key in trace.attributes
+ else " "
+ )
+ place_map = {0: PetriNet.Place("p_0")}
+ net.places.add(place_map[0])
+ for i in range(0, len(trace)):
+ t = PetriNet.Transition(
+ "t_" + trace[i][activity_key] + "_" + str(i),
+ trace[i][activity_key],
+ )
+ # 16/02/2021: set the trace index as property of the transition of the
+ # trace net
+ t.properties[properties.TRACE_NET_TRANS_INDEX] = i
+ net.transitions.add(t)
+ place_map[i + 1] = PetriNet.Place("p_" + str(i + 1))
+ # 16/02/2021: set the place index as property of the place of the trace
+ # net
+ place_map[i + 1].properties[properties.TRACE_NET_PLACE_INDEX] = i + 1
+ net.places.add(place_map[i + 1])
+ add_arc_from_to(place_map[i], t, net)
+ add_arc_from_to(t, place_map[i + 1], net)
+ return net, Marking({place_map[0]: 1}), Marking({place_map[len(trace)]: 1})
+
+
+def construct_trace_net_cost_aware(
+ trace,
+ costs,
+ trace_name_key=xes_util.DEFAULT_NAME_KEY,
+ activity_key=xes_util.DEFAULT_NAME_KEY,
+):
+ """
+ Creates a trace net, i.e. a trace in Petri net form mapping specific costs to transitions.
+
+ Parameters
+ ----------
+ trace: :class:`list` input trace, assumed to be a list of events
+ costs: :class:`list` list of costs, length should be equal to the length of the input trace
+ trace_name_key: :class:`str` key of the attribute that defines the name of the trace
+ activity_key: :class:`str` key of the attribute of the events that defines the activity name
+
+ Returns
+ -------
+ tuple: :class:`tuple` of the net, initial marking, final marking and map of costs
+
+
+ """
+ net = PetriNet(
+ "trace net of %s" % trace.attributes[trace_name_key]
+ if trace_name_key in trace.attributes
+ else " "
+ )
+ place_map = {0: PetriNet.Place("p_0")}
+ net.places.add(place_map[0])
+ cost_map = dict()
+ for i in range(0, len(trace)):
+ t = PetriNet.Transition(
+ "t_" + trace[i][activity_key] + "_" + str(i),
+ trace[i][activity_key],
+ )
+ # 16/02/2021: set the trace index as property of the transition of the
+ # trace net
+ t.properties[properties.TRACE_NET_TRANS_INDEX] = i
+ cost_map[t] = costs[i]
+ net.transitions.add(t)
+ place_map[i + 1] = PetriNet.Place("p_" + str(i + 1))
+ # 16/02/2021: set the place index as property of the place of the trace
+ # net
+ place_map[i + 1].properties[properties.TRACE_NET_PLACE_INDEX] = i + 1
+ net.places.add(place_map[i + 1])
+ add_arc_from_to(place_map[i], t, net)
+ add_arc_from_to(t, place_map[i + 1], net)
+ return (
+ net,
+ Marking({place_map[0]: 1}),
+ Marking({place_map[len(trace)]: 1}),
+ cost_map,
+ )
+
+
+def acyclic_net_variants(
+ net, initial_marking, final_marking, activity_key=xes_util.DEFAULT_NAME_KEY
+):
+ """
+ Given an acyclic accepting Petri net, initial and final marking extracts a set of variants (in form of traces)
+ replayable on the net.
+ Warning: this function is based on a marking exploration. If the accepting Petri net contains loops, the method
+ will not work properly as it stops the search if a specific marking has already been encountered.
+
+ Parameters
+ ----------
+ :param net: An acyclic workflow net
+ :param initial_marking: The initial marking of the net.
+ :param final_marking: The final marking of the net.
+ :param activity_key: activity key to use
+
+ Returns
+ -------
+ :return: variants: :class:`list` Set of variants - in the form of Trace objects - obtainable executing the net
+
+ """
+ active = {(initial_marking, ())}
+ visited = set()
+ variants = set()
+ while active:
+ curr_marking, curr_partial_trace = active.pop()
+ curr_pair = (curr_marking, curr_partial_trace)
+ enabled_transitions = semantics.enabled_transitions(net, curr_marking)
+ for transition in enabled_transitions:
+ if transition.label is not None:
+ next_partial_trace = curr_partial_trace + (transition.label,)
+ else:
+ next_partial_trace = curr_partial_trace
+ next_marking = semantics.execute(transition, net, curr_marking)
+ next_pair = (next_marking, next_partial_trace)
+
+ if next_marking == final_marking:
+ variants.add(next_partial_trace)
+ else:
+ # If the next marking is not in visited, if the next
+ # marking+partial trace is different from the current
+ # one+partial trace
+ if next_pair not in visited and curr_pair != next_pair:
+ active.add(next_pair)
+ visited.add(curr_pair)
+ trace_variants = []
+ for variant in variants:
+ trace = Trace()
+ for activity_label in variant:
+ trace.append(Event({activity_key: activity_label}))
+ trace_variants.append(trace)
+ return trace_variants
+
+
+def get_transition_by_name(
+ net: PetriNet, transition_name
+) -> Optional[PetriNet.Transition]:
+ """
+ Get a transition by its name
+
+ Parameters
+ ------------
+ net
+ Petri net
+ transition_name
+ Transition name
+
+ Returns
+ ------------
+ transition
+ Transition object
+ """
+ for t in net.transitions:
+ if t.name == transition_name:
+ return t
+ return None
+
+
+def decorate_places_preset_trans(net: PetriNet):
+ """
+ Decorate places with information useful for the replay
+
+ Parameters
+ -------------
+ net
+ Petri net
+ """
+ for place in net.places:
+ place.ass_trans = set()
+
+ for trans in net.transitions:
+ for place in trans.sub_marking:
+ place.ass_trans.add(trans)
+
+
+def decorate_transitions_prepostset(net: PetriNet):
+ """
+ Decorate transitions with sub and addition markings
+
+ Parameters
+ -------------
+ net
+ Petri net
+ """
+ from pm4py.objects.petri_net.obj import Marking
+
+ for trans in net.transitions:
+ sub_marking = Marking()
+ add_marking = Marking()
+
+ for arc in trans.in_arcs:
+ sub_marking[arc.source] = arc.weight
+ add_marking[arc.source] = -arc.weight
+ for arc in trans.out_arcs:
+ if arc.target in add_marking:
+ add_marking[arc.target] = arc.weight + add_marking[arc.target]
+ else:
+ add_marking[arc.target] = arc.weight
+ trans.sub_marking = sub_marking
+ trans.add_marking = add_marking
+
+
+def get_places_shortest_path(
+ net,
+ place_to_populate,
+ current_place,
+ places_shortest_path,
+ actual_list,
+ rec_depth,
+ max_rec_depth,
+):
+ """
+ Get shortest path between places lead by hidden transitions
+
+ Parameters
+ ----------
+ net
+ Petri net
+ place_to_populate
+ Place that we are populating the shortest map of
+ current_place
+ Current visited place (must explore its transitions)
+ places_shortest_path
+ Current dictionary
+ actual_list
+ Actual list of transitions to enable
+ rec_depth
+ Recursion depth
+ max_rec_depth
+ Maximum recursion depth
+ """
+ if rec_depth > max_rec_depth:
+ return places_shortest_path
+ if place_to_populate not in places_shortest_path:
+ places_shortest_path[place_to_populate] = {}
+ for t in current_place.out_arcs:
+ if t.target.label is None:
+ for p2 in t.target.out_arcs:
+ if p2.target not in places_shortest_path[
+ place_to_populate
+ ] or len(actual_list) + 1 < len(
+ places_shortest_path[place_to_populate][p2.target]
+ ):
+ new_actual_list = copy(actual_list)
+ new_actual_list.append(t.target)
+ places_shortest_path[place_to_populate][p2.target] = copy(
+ new_actual_list
+ )
+ places_shortest_path = get_places_shortest_path(
+ net,
+ place_to_populate,
+ p2.target,
+ places_shortest_path,
+ new_actual_list,
+ rec_depth + 1,
+ max_rec_depth,
+ )
+ return places_shortest_path
+
+
+def get_places_shortest_path_by_hidden(net: PetriNet, max_rec_depth):
+ """
+ Get shortest path between places lead by hidden transitions
+
+ Parameters
+ ----------
+ net
+ Petri net
+ max_rec_depth
+ Maximum recursion depth
+ """
+ places_shortest_path = {}
+ for p in net.places:
+ places_shortest_path = get_places_shortest_path(
+ net, p, p, places_shortest_path, [], 0, max_rec_depth
+ )
+ return places_shortest_path
+
+
+def invert_spaths_dictionary(spaths):
+ """
+ Invert the shortest paths (between places) dictionary,
+ from target-source to source-target
+
+ Parameters
+ -------------
+ spaths
+ Shortest paths dictionary
+
+ Returns
+ -------------
+ inv_spaths
+ Inverted shortest paths dictionary
+ """
+ inv_spaths = {}
+ for target_place in spaths:
+ for source_place in spaths[target_place]:
+ if source_place not in inv_spaths:
+ inv_spaths[source_place] = {}
+ if target_place not in inv_spaths[source_place]:
+ inv_spaths[source_place][target_place] = set()
+ inv_spaths[source_place][target_place] = inv_spaths[source_place][
+ target_place
+ ].union(spaths[target_place][source_place])
+ return inv_spaths
+
+
+def remove_unconnected_components(net: PetriNet) -> PetriNet:
+ """
+ Remove unconnected components from a Petri net
+
+ Parameters
+ -----------
+ net
+ Petri net
+
+ Returns
+ -----------
+ net
+ Cleaned Petri net
+ """
+ changed_something = True
+ while changed_something:
+ changed_something = False
+ places = list(net.places)
+ for place in places:
+ if len(place.in_arcs) == 0 and len(place.out_arcs) == 0:
+ remove_place(net, place)
+ changed_something = True
+ transitions = list(net.transitions)
+ for trans in transitions:
+ if len(trans.in_arcs) == 0 or len(trans.out_arcs) == 0:
+ remove_transition(net, trans)
+ changed_something = True
+ return net
+
+
+def get_s_components_from_petri(
+ net,
+ im,
+ fm,
+ rec_depth=0,
+ curr_s_comp=None,
+ visited_places=None,
+ list_s_components=None,
+ max_rec_depth=6,
+):
+ """
+ Gets the S-components from a Petri net
+
+ Parameters
+ -------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ curr_s_comp
+ Current S component
+ visited_places
+ Visited places
+ list_s_components
+ List of S-components
+ max_rec_depth
+ Maximum recursion depth
+
+ Returns
+ --------------
+ s_components
+ List of S-components
+ """
+ if list_s_components is None:
+ list_s_components = []
+ if len(im) > 1 or len(fm) > 1:
+ return list_s_components
+ source = list(im.keys())[0]
+ if curr_s_comp is None:
+ curr_s_comp = [source]
+ if visited_places is None:
+ visited_places = []
+ something_changed = True
+ while something_changed and rec_depth < max_rec_depth:
+ something_changed = False
+ places_to_visit = sorted(
+ list(set(curr_s_comp[len(visited_places):])),
+ key=lambda x: len(x.out_arcs),
+ reverse=True,
+ )
+ for place_to_visit in places_to_visit:
+ visited_places.append(place_to_visit)
+ target_trans = sorted(
+ list(set([arc.target for arc in place_to_visit.out_arcs])),
+ key=lambda x: len(x.out_arcs),
+ )
+ for trans in target_trans:
+ visited_places_names = [x.name for x in visited_places]
+ target_trans_target = list(
+ set(
+ [
+ arc.target
+ for arc in trans.out_arcs
+ if arc.target.name not in visited_places_names
+ ]
+ )
+ )
+ if target_trans_target:
+ something_changed = True
+ if len(target_trans_target) == 1:
+ new_place = target_trans_target[0]
+ curr_s_comp.append(new_place)
+ else:
+ for new_place in target_trans_target:
+ [new_curr_s_comp, new_visited_places] = deepcopy(
+ [curr_s_comp, visited_places]
+ )
+ new_curr_s_comp.append(new_place)
+ list_s_components = get_s_components_from_petri(
+ net,
+ im,
+ fm,
+ rec_depth=rec_depth + 1,
+ curr_s_comp=new_curr_s_comp,
+ visited_places=new_visited_places,
+ list_s_components=list_s_components,
+ max_rec_depth=max_rec_depth,
+ )
+
+ curr_s_component = {place.name for place in curr_s_comp}
+ if curr_s_component not in list_s_components:
+ list_s_components.append(curr_s_component)
+
+ return list_s_components
+
+
+def remove_arc(net: PetriNet, arc: PetriNet.Arc) -> PetriNet:
+ """
+ Removes an arc from a Petri net
+
+ Parameters
+ ---------------
+ net
+ Petri net
+ arc
+ Arc of the Petri net
+
+ Returns
+ -------------
+ net
+ Petri net
+ """
+ net.arcs.remove(arc)
+ arc.source.out_arcs.remove(arc)
+ arc.target.in_arcs.remove(arc)
+
+ return net
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/projection.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/projection.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c84cef5f065cd4245b273bd9246fcac5e72cce9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/projection.py
@@ -0,0 +1,138 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import numpy as np
+
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to
+
+
+def project_net_on_place(place):
+ """
+ Project a Petri net on a place
+
+ Parameters
+ -------------
+ place
+ Place
+
+ Returns
+ -------------
+ net
+ (Place) net
+ im
+ Empty initial marking
+ fm
+ Empty final marking
+ """
+ place_net = PetriNet()
+ place_net_im = Marking()
+ place_net_fm = Marking()
+
+ input_trans = [arc.source for arc in place.in_arcs]
+ output_trans = [arc.target for arc in place.out_arcs]
+
+ if len(input_trans) == 0 or len(output_trans) == 0:
+ raise Exception("place projection not available on source/sink places")
+
+ input_trans_visible = [trans for trans in input_trans if trans.label]
+ output_trans_visible = [trans for trans in output_trans if trans.label]
+
+ if not len(input_trans) == len(input_trans_visible) or not len(
+ output_trans
+ ) == len(output_trans_visible):
+ raise Exception(
+ "place projection not available on places that have invisible transitions as preset/postset"
+ )
+
+ new_place = PetriNet.Place(place.name)
+ place_net.places.add(new_place)
+
+ for trans in input_trans:
+ new_trans = PetriNet.Transition(trans.name, trans.label)
+ place_net.transitions.add(new_trans)
+ add_arc_from_to(new_trans, new_place, place_net)
+
+ for trans in output_trans:
+ new_trans = PetriNet.Transition(trans.name, trans.label)
+ place_net.transitions.add(new_trans)
+ add_arc_from_to(new_place, new_trans, place_net)
+
+ return place_net, place_net_im, place_net_fm
+
+
+def project_net_on_matrix(net, activities, parameters=None):
+ """
+ Project a Petri net with:
+ - only visible transitions
+ - where each place preset/postset is disjoint
+ - with unique visible transitions
+ on a numeric matrix
+
+ Parameters
+ --------------
+ net
+ Petri net
+ activities
+ List of activities
+ parameters
+ Possible parameters of the algorithm
+ """
+ inv_trans_map = {}
+ for trans in net.transitions:
+ if not trans.label:
+ raise Exception(
+ "the project_net_on_matrix works only with Petri net that do not contain invisible transitions"
+ )
+ if trans.label in inv_trans_map:
+ raise Exception(
+ "the project_net_on_matrix works only with Petri net that contains unique visible transitions"
+ )
+ inv_trans_map[trans.label] = trans
+ places_matrix = []
+ for place in net.places:
+ place_repr = [0] * len(activities)
+ input_trans_labels = set([arc.source.label for arc in place.in_arcs])
+ output_trans_labels = set([arc.target.label for arc in place.out_arcs])
+ if len(input_trans_labels.intersection(output_trans_labels)) > 0:
+ raise Exception(
+ "place has a transition that belongs to both preset and postset"
+ )
+ for arc in place.in_arcs:
+ input_trans_label = arc.source.label
+ input_arc_weight = arc.weight
+ if input_trans_label in activities:
+ place_repr[activities.index(input_trans_label)] = (
+ -input_arc_weight
+ )
+ for arc in place.out_arcs:
+ output_trans_label = arc.target.label
+ output_arc_weight = arc.weight
+ if output_trans_label in activities:
+ place_repr[activities.index(output_trans_label)] = (
+ output_arc_weight
+ )
+ if min(place_repr) < 0 < max(place_repr):
+ places_matrix.append(place_repr)
+ if len(places_matrix) == 0:
+ raise Exception("no places numeric representation could be found")
+ places_matrix = np.transpose(np.asmatrix(places_matrix))
+ return places_matrix
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/reachability_graph.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/reachability_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d1303332d69e00370aff8b8e97b32753a481196
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/reachability_graph.py
@@ -0,0 +1,192 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import re
+
+from pm4py.objects import petri_net
+from pm4py.objects.transition_system.obj import TransitionSystem
+from pm4py.objects.petri_net.utils import align_utils
+from pm4py.objects.transition_system import obj as ts
+from pm4py.objects.transition_system import utils
+from pm4py.util import exec_utils
+from enum import Enum
+import time
+
+
+class Parameters(Enum):
+ MAX_ELAB_TIME = "max_elab_time"
+ PETRI_SEMANTICS = "petri_semantics"
+
+
+def staterep(name):
+ """
+ Creates a string representation for a state of a transition system.
+ Necessary because graphviz does not support symbols simulation than alphanimerics and '_'.
+ TODO: find a better representation.
+
+ Parameters
+ ----------
+ name: the name of a state
+
+ Returns
+ -------
+ Version of the name filtered of non-alphanumerical characters (except '_').
+ """
+ return re.sub(r"\W+", "", name)
+
+
+def marking_flow_petri(
+ net, im, return_eventually_enabled=False, parameters=None
+):
+ """
+ Construct the marking flow of a Petri net
+
+ Parameters
+ -----------------
+ net
+ Petri net
+ im
+ Initial marking
+ return_eventually_enabled
+ Return the eventually enabled (visible) transitions
+ """
+ if parameters is None:
+ parameters = {}
+
+ # set a maximum execution time of 1 day (it can be changed by providing
+ # the parameter)
+ max_exec_time = exec_utils.get_param_value(
+ Parameters.MAX_ELAB_TIME, parameters, 86400
+ )
+ semantics = exec_utils.get_param_value(
+ Parameters.PETRI_SEMANTICS,
+ parameters,
+ petri_net.semantics.ClassicSemantics(),
+ )
+
+ start_time = time.time()
+
+ incoming_transitions = {im: set()}
+ outgoing_transitions = {}
+ eventually_enabled = {}
+
+ active = [im]
+ while active:
+ if (time.time() - start_time) >= max_exec_time:
+ # interrupt the execution
+ return (
+ incoming_transitions,
+ outgoing_transitions,
+ eventually_enabled,
+ )
+ m = active.pop()
+ enabled_transitions = semantics.enabled_transitions(net, m)
+ if return_eventually_enabled:
+ eventually_enabled[m] = (
+ align_utils.get_visible_transitions_eventually_enabled_by_marking(
+ net, m))
+ outgoing_transitions[m] = {}
+ for t in enabled_transitions:
+ nm = semantics.weak_execute(t, net, m)
+ outgoing_transitions[m][t] = nm
+ if nm not in incoming_transitions:
+ incoming_transitions[nm] = set()
+ if nm not in active:
+ active.append(nm)
+ incoming_transitions[nm].add(t)
+
+ return incoming_transitions, outgoing_transitions, eventually_enabled
+
+
+def construct_reachability_graph_from_flow(
+ incoming_transitions,
+ outgoing_transitions,
+ use_trans_name=False,
+ parameters=None,
+):
+ """
+ Construct the reachability graph from the marking flow
+
+ Parameters
+ ----------------
+ incoming_transitions
+ Incoming transitions
+ outgoing_transitions
+ Outgoing transitions
+ use_trans_name
+ Use the transition name
+
+ Returns
+ ----------------
+ re_gr
+ Transition system that represents the reachability graph of the input Petri net.
+ """
+ if parameters is None:
+ parameters = {}
+
+ re_gr = ts.TransitionSystem()
+
+ map_states = {}
+ for s in incoming_transitions:
+ map_states[s] = ts.TransitionSystem.State(staterep(repr(s)))
+ re_gr.states.add(map_states[s])
+
+ for s1 in outgoing_transitions:
+ for t in outgoing_transitions[s1]:
+ s2 = outgoing_transitions[s1][t]
+ if use_trans_name:
+ utils.add_arc_from_to(
+ t.name, map_states[s1], map_states[s2], re_gr
+ )
+ else:
+ utils.add_arc_from_to(
+ repr(t), map_states[s1], map_states[s2], re_gr
+ )
+
+ return re_gr
+
+
+def construct_reachability_graph(
+ net, initial_marking, use_trans_name=False, parameters=None
+) -> TransitionSystem:
+ """
+ Creates a reachability graph of a certain Petri net.
+ DO NOT ATTEMPT WITH AN UNBOUNDED PETRI NET, EVER.
+
+ Parameters
+ ----------
+ net: Petri net
+ initial_marking: initial marking of the Petri net.
+
+ Returns
+ -------
+ re_gr: Transition system that represents the reachability graph of the input Petri net.
+ """
+ incoming_transitions, outgoing_transitions, eventually_enabled = (
+ marking_flow_petri(net, initial_marking, parameters=parameters)
+ )
+
+ return construct_reachability_graph_from_flow(
+ incoming_transitions,
+ outgoing_transitions,
+ use_trans_name=use_trans_name,
+ parameters=parameters,
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/reduction.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..94e11f50f4d453c5a953b752bcc21d92532f3987
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/reduction.py
@@ -0,0 +1,609 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.utils.petri_utils import (
+ remove_arc,
+ remove_transition,
+ remove_place,
+ add_arc_from_to,
+ pre_set,
+ post_set,
+ get_arc_type,
+)
+from pm4py.objects.petri_net.obj import PetriNet
+from pm4py.objects.petri_net import properties
+import itertools
+from itertools import combinations, chain
+
+
+######################################################################
+# NEW HELPER FUNCTIONS
+######################################################################
+
+def _has_only_this_transition_as_output(place, transition):
+ """
+ Checks if all arcs exiting the given place go to exactly this 'transition'
+ (i.e., place -> transition, no other transitions).
+ """
+ outgoing_transitions = {
+ arc.target for arc in place.out_arcs if isinstance(arc.target, PetriNet.Transition)
+ }
+ return outgoing_transitions == {transition}
+
+
+def _has_only_this_transition_as_input(place, transition):
+ """
+ Checks if all arcs entering the given place come from exactly this 'transition'
+ (i.e., transition -> place, no other transitions).
+ """
+ incoming_transitions = {
+ arc.source for arc in place.in_arcs if isinstance(arc.source, PetriNet.Transition)
+ }
+ return incoming_transitions == {transition}
+
+
+######################################################################
+# REFACTOR: SINGLE-ENTRY / SINGLE-EXIT REDUCTIONS
+######################################################################
+
+def reduce_single_entry_transitions(net):
+ """
+ Reduces the number of single-entry silent transitions in the Petri net
+ by merging them upward when the place feeding them does not feed any
+ other transition.
+
+ Parameters
+ ----------------
+ net
+ Petri net
+ """
+ cont = True
+ while cont:
+ cont = False
+ # Identify silent transitions with exactly 1 input place.
+ single_entry_transitions = [
+ t for t in net.transitions
+ if t.label is None and len(t.in_arcs) == 1
+ ]
+ for t in single_entry_transitions:
+ source_place = list(t.in_arcs)[0].source
+ # We check:
+ # 1) source_place has exactly 1 input transition
+ # 2) source_place is used *only* by 't' (i.e., no other transitions).
+ if (
+ len(source_place.in_arcs) == 1
+ and _has_only_this_transition_as_output(source_place, t)
+ ):
+ # We can merge out 't' and 'source_place'
+ source_transition = list(source_place.in_arcs)[0].source
+ target_places = [arc.target for arc in t.out_arcs]
+
+ remove_transition(net, t)
+ remove_place(net, source_place)
+
+ # Wire the old source transition directly to t's old targets
+ for p in target_places:
+ add_arc_from_to(source_transition, p, net)
+
+ cont = True
+ break
+ return net
+
+
+def reduce_single_exit_transitions(net):
+ """
+ Reduces the number of single-exit silent transitions in the Petri net
+ by merging them downward when the place receiving them does not receive
+ arcs from any other transition.
+
+ Parameters
+ --------------
+ net
+ Petri net
+ """
+ cont = True
+ while cont:
+ cont = False
+ # Identify silent transitions with exactly 1 output place.
+ single_exit_transitions = [
+ t for t in net.transitions
+ if t.label is None and len(t.out_arcs) == 1
+ ]
+ for t in single_exit_transitions:
+ target_place = list(t.out_arcs)[0].target
+ # We check:
+ # 1) target_place has exactly 1 output transition
+ # 2) target_place is used *only* by 't' (i.e., no other transitions).
+ if (
+ len(target_place.out_arcs) == 1
+ and _has_only_this_transition_as_input(target_place, t)
+ ):
+ target_transition = list(target_place.out_arcs)[0].target
+ source_places = [arc.source for arc in t.in_arcs]
+
+ remove_transition(net, t)
+ remove_place(net, target_place)
+
+ # Wire the old input places directly to t's old target transition
+ for p in source_places:
+ add_arc_from_to(p, target_transition, net)
+
+ cont = True
+ break
+ return net
+
+
+def apply_simple_reduction(net):
+ """
+ Apply a simple reduction to the Petri net by repeatedly merging
+ single-entry and single-exit silent transitions where possible.
+
+ Parameters
+ --------------
+ net
+ Petri net
+ """
+ changed = True
+ while changed:
+ old_t_count = len(net.transitions)
+ old_p_count = len(net.places)
+
+ reduce_single_entry_transitions(net)
+ reduce_single_exit_transitions(net)
+
+ new_t_count = len(net.transitions)
+ new_p_count = len(net.places)
+
+ # If the overall structure changed, keep iterating
+ changed = (new_t_count < old_t_count or new_p_count < old_p_count)
+
+ return net
+
+
+######################################################################
+# REMAINING REDUCTION FUNCTIONS (unchanged)
+######################################################################
+
+def apply_fst_rule(net):
+ """
+ Apply the Fusion of Series Transitions (FST) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ cont = True
+ while cont:
+ cont = False
+ for p, t, u in itertools.product(
+ net.places, net.transitions, net.transitions
+ ):
+ if (
+ (len(list(p.in_arcs)) == 1 and list(p.in_arcs)[0].source == t)
+ and (
+ len(list(p.out_arcs)) == 1
+ and list(p.out_arcs)[0].target == u
+ )
+ and (
+ len(list(u.in_arcs)) == 1
+ and list(u.in_arcs)[0].source == p
+ )
+ and (len(post_set(t).intersection(post_set(u))) == 0)
+ and (
+ set().union(
+ *[
+ post_set(place, properties.INHIBITOR_ARC)
+ for place in post_set(u)
+ ]
+ )
+ == post_set(p, properties.INHIBITOR_ARC)
+ )
+ and (
+ set().union(
+ *[
+ post_set(place, properties.RESET_ARC)
+ for place in post_set(u)
+ ]
+ )
+ == post_set(p, properties.RESET_ARC)
+ )
+ and (
+ len(pre_set(u, properties.RESET_ARC)) == 0
+ and len(pre_set(u, properties.INHIBITOR_ARC)) == 0
+ )
+ ):
+ if u.label is None:
+ remove_place(net, p)
+ for target in post_set(u):
+ add_arc_from_to(t, target, net)
+ remove_transition(net, u)
+ cont = True
+ break
+
+ return net
+
+
+def apply_fsp_rule(net, im=None, fm=None):
+ """
+ Apply the Fusion of Series Places (FSP) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ if im is None:
+ im = {}
+ if fm is None:
+ fm = {}
+ cont = True
+ while cont:
+ cont = False
+ for p, q, t in itertools.product(
+ net.places, net.places, net.transitions
+ ):
+ if (
+ t.label is None
+ ): # only silent transitions may be removed either way
+ if (
+ (len(t.in_arcs) == 1 and list(t.in_arcs)[0].source == p)
+ and (
+ len(t.out_arcs) == 1
+ and list(t.out_arcs)[0].target == q
+ )
+ and (len(post_set(p)) == 1 and list(post_set(p))[0] == t)
+ and (len(pre_set(p).intersection(pre_set(q))) == 0)
+ and (
+ post_set(p, properties.RESET_ARC)
+ == post_set(q, properties.RESET_ARC)
+ )
+ and (
+ post_set(p, properties.INHIBITOR_ARC)
+ == post_set(q, properties.INHIBITOR_ARC)
+ )
+ and (
+ len(pre_set(t, properties.RESET_ARC)) == 0
+ and len(pre_set(t, properties.INHIBITOR_ARC)) == 0
+ )
+ ):
+ # remove place p and transition t
+ remove_transition(net, t)
+ for source in pre_set(p):
+ add_arc_from_to(source, q, net)
+ remove_place(net, p)
+ if p in im:
+ del im[p]
+ im[q] = 1
+ cont = True
+ break
+
+ return net, im, fm
+
+
+def apply_fpt_rule(net):
+ """
+ Apply the Fusion of Parallel Transitions (FPT) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ cont = True
+ while cont:
+ cont = False
+ # only silent transitions are considered for parallel merging
+ silent_transitions = [
+ transition for transition in net.transitions
+ if transition.label is None
+ ]
+ for V in power_set(silent_transitions, 2):
+ condition = True
+ for x, y in itertools.product(V, V):
+ if x != y:
+ if not (
+ (pre_set(x) == pre_set(y))
+ and (post_set(x) == post_set(y))
+ and (
+ pre_set(x, properties.RESET_ARC)
+ == pre_set(y, properties.RESET_ARC)
+ )
+ and (
+ pre_set(x, properties.INHIBITOR_ARC)
+ == pre_set(y, properties.INHIBITOR_ARC)
+ )
+ ):
+ condition = False
+ break
+ # V is a valid candidate
+ if condition and len(V) > 1:
+ # remove transitions except the first one
+ for t in V[1:]:
+ remove_transition(net, t)
+ cont = True
+ break
+ return net
+
+
+def apply_fpp_rule(net, im=None):
+ """
+ Apply the Fusion of Parallel Places (FPP) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ if im is None:
+ im = {}
+ cont = True
+ while cont:
+ cont = False
+ for Q in power_set(net.places, 2):
+ condition = True
+ for x, y in itertools.product(Q, Q):
+ if x != y:
+ if not (
+ (pre_set(x) == pre_set(y))
+ and (post_set(x) == post_set(y))
+ and (
+ post_set(x, properties.RESET_ARC)
+ == post_set(y, properties.RESET_ARC)
+ )
+ and (
+ post_set(x, properties.INHIBITOR_ARC)
+ == post_set(y, properties.INHIBITOR_ARC)
+ )
+ ):
+ condition = False
+ break
+
+ for x in Q:
+ if x in im:
+ for y in Q:
+ if y in im and im[x] > im[y]:
+ if not (
+ len(post_set(x, properties.INHIBITOR_ARC)) == 0
+ ):
+ condition = False
+ break
+ else:
+ continue
+ break
+ # Q is a valid candidate
+ if condition and len(Q) > 1:
+ # remove places except the first one
+ for p in Q[1:]:
+ remove_place(net, p)
+ cont = True
+ break
+ return net
+
+
+def apply_elt_rule(net):
+ """
+ Apply the Elimination of Self-Loop Transitions (ELT) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ cont = True
+ while cont:
+ cont = False
+ for p, t in itertools.product(
+ net.places, [t for t in net.transitions if t.label is None]
+ ):
+ if (
+ (len(list(t.in_arcs)) == 1 and list(t.in_arcs)[0].source == p)
+ and (
+ len(list(t.out_arcs)) == 1
+ and list(t.out_arcs)[0].target == p
+ )
+ and (len(list(p.in_arcs)) >= 2)
+ and (
+ len(pre_set(t, properties.RESET_ARC)) == 0
+ and len(pre_set(t, properties.INHIBITOR_ARC)) == 0
+ )
+ ):
+ remove_transition(net, t)
+ cont = True
+ break
+
+ return net
+
+
+def apply_elp_rule(net, im=None):
+ """
+ Apply the Elimination of Self-Loop Places (ELP) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ if im is None:
+ im = {}
+ cont = True
+ while cont:
+ cont = False
+ for p in [place for place in net.places]:
+ if (
+ (
+ set([arc.target for arc in p.out_arcs]).issubset(
+ set([arc.source for arc in p.in_arcs])
+ )
+ )
+ and (p in im and im[p] >= 1)
+ and (
+ post_set(p, properties.RESET_ARC).union(
+ set([arc.target for arc in p.out_arcs])
+ )
+ == set([arc.source for arc in p.in_arcs])
+ )
+ and (len(post_set(p, properties.INHIBITOR_ARC)) == 0)
+ ):
+ remove_place(net, p)
+ cont = True
+ break
+
+ return net
+
+
+def apply_a_rule(net):
+ """
+ Apply the Abstraction (A) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ cont = True
+ while cont:
+ cont = False
+ for Q, U in itertools.product(
+ power_set(net.places, 1), power_set(net.transitions, 1)
+ ):
+ for s, t in itertools.product(
+ [s for s in net.places if s not in Q],
+ [
+ t
+ for t in net.transitions
+ if (t not in U) and (t.label is None)
+ ],
+ ):
+ if (
+ (
+ (pre_set(t) == {s})
+ and (post_set(s) == {t})
+ and (pre_set(s) == set(U))
+ and (post_set(t) == set(Q))
+ and (
+ len(
+ set(
+ itertools.product(pre_set(s), post_set(t))
+ ).intersection(
+ set(
+ [
+ (arc.source, arc.target)
+ for arc in net.arcs
+ if get_arc_type(arc) is None
+ ]
+ )
+ )
+ )
+ )
+ == 0
+ )
+ and (len(pre_set(t, properties.RESET_ARC)) == 0)
+ and (len(pre_set(t, properties.INHIBITOR_ARC)) == 0)
+ ):
+
+ # check conditions on Q
+ condition = True
+ for q in Q:
+ if not (
+ (
+ post_set(s, properties.RESET_ARC)
+ == post_set(q, properties.RESET_ARC)
+ )
+ and (
+ post_set(s, properties.INHIBITOR_ARC)
+ == post_set(q, properties.INHIBITOR_ARC)
+ )
+ ):
+ condition = False
+ break
+ # Q is a valid candidate
+ if condition:
+ for u in U:
+ for q in Q:
+ add_arc_from_to(u, q, net)
+ remove_place(net, s)
+ remove_transition(net, t)
+ cont = True
+ break
+ return net
+
+
+def apply_r_rule(net):
+ """
+ Apply the Reset Reduction (R) rule
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ cont = True
+ while cont:
+ cont = False
+ for p, t in itertools.product(net.places, net.transitions):
+ if p in pre_set(t, properties.RESET_ARC).intersection(
+ pre_set(t, properties.INHIBITOR_ARC)
+ ):
+ for arc in [arc for arc in net.arcs]:
+ if (
+ arc.source == p
+ and arc.target == t
+ and arc.arc_type == properties.RESET_ARC
+ ):
+ remove_arc(net, arc)
+ cont = True
+ break
+
+ return net
+
+
+def power_set(iterable, min=0):
+ s = list(iterable)
+ return chain.from_iterable(
+ combinations(s, r) for r in range(min, len(s) + 1)
+ )
+
+
+def apply_reset_inhibitor_net_reduction(net, im=None, fm=None):
+ """
+ Apply a thorough reduction to the Reset Inhibitor net
+
+ Parameters
+ --------------
+ net
+ Reset Inhibitor net
+ """
+ if im is None:
+ im = {}
+ if fm is None:
+ fm = {}
+ apply_fst_rule(net)
+ apply_fsp_rule(net, im, fm)
+ # (FPT) and (FPP) and (A) rules may be very expensive for large nets
+ # Uncomment them if needed:
+ # apply_fpt_rule(net)
+ # apply_fpp_rule(net, im)
+ # apply_a_rule(net)
+ apply_elt_rule(net)
+ apply_elp_rule(net, im)
+ apply_r_rule(net)
+ return net, im, fm
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/synchronous_product.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/synchronous_product.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c0bc2916433c1e4ed3feb49cd913ad97957d704
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/petri_net/utils/synchronous_product.py
@@ -0,0 +1,198 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.obj import PetriNet, Marking
+from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to
+from pm4py.objects.petri_net import properties
+
+
+def construct(pn1, im1, fm1, pn2, im2, fm2, skip):
+ """
+ Constructs the synchronous product net of two given Petri nets.
+
+
+ :param pn1: Petri net 1
+ :param im1: Initial marking of Petri net 1
+ :param fm1: Final marking of Petri net 1
+ :param pn2: Petri net 2
+ :param im2: Initial marking of Petri net 2
+ :param fm2: Final marking of Petri net 2
+ :param skip: Symbol to be used as skip
+
+ Returns
+ -------
+ :return: Synchronous product net and associated marking labels are of the form (a,>>)
+ """
+ sync_net = PetriNet(
+ "synchronous_product_net of %s and %s" % (pn1.name, pn2.name)
+ )
+ t1_map, p1_map = __copy_into(pn1, sync_net, True, skip)
+ t2_map, p2_map = __copy_into(pn2, sync_net, False, skip)
+
+ for t1 in pn1.transitions:
+ for t2 in pn2.transitions:
+ if t1.label == t2.label:
+ sync = PetriNet.Transition(
+ (t1.name, t2.name), (t1.label, t2.label)
+ )
+ sync_net.transitions.add(sync)
+ # copy the properties of the transitions inside the transition
+ # of the sync net
+ for p1 in t1.properties:
+ sync.properties[p1] = t1.properties[p1]
+ for p2 in t2.properties:
+ sync.properties[p2] = t2.properties[p2]
+ for a in t1.in_arcs:
+ add_arc_from_to(p1_map[a.source], sync, sync_net)
+ for a in t2.in_arcs:
+ add_arc_from_to(p2_map[a.source], sync, sync_net)
+ for a in t1.out_arcs:
+ add_arc_from_to(sync, p1_map[a.target], sync_net)
+ for a in t2.out_arcs:
+ add_arc_from_to(sync, p2_map[a.target], sync_net)
+
+ sync_im = Marking()
+ sync_fm = Marking()
+ for p in im1:
+ sync_im[p1_map[p]] = im1[p]
+ for p in im2:
+ sync_im[p2_map[p]] = im2[p]
+ for p in fm1:
+ sync_fm[p1_map[p]] = fm1[p]
+ for p in fm2:
+ sync_fm[p2_map[p]] = fm2[p]
+
+ # update 06/02/2021: to distinguish the sync nets that are output of this
+ # method, put a property in the sync net
+ sync_net.properties[properties.IS_SYNC_NET] = True
+
+ return sync_net, sync_im, sync_fm
+
+
+def construct_cost_aware(
+ pn1, im1, fm1, pn2, im2, fm2, skip, pn1_costs, pn2_costs, sync_costs
+):
+ """
+ Constructs the synchronous product net of two given Petri nets.
+
+
+ :param pn1: Petri net 1
+ :param im1: Initial marking of Petri net 1
+ :param fm1: Final marking of Petri net 1
+ :param pn2: Petri net 2
+ :param im2: Initial marking of Petri net 2
+ :param fm2: Final marking of Petri net 2
+ :param skip: Symbol to be used as skip
+ :param pn1_costs: dictionary mapping transitions of pn1 to corresponding costs
+ :param pn2_costs: dictionary mapping transitions of pn2 to corresponding costs
+ :param pn1_costs: dictionary mapping pairs of transitions in pn1 and pn2 to costs
+ :param sync_costs: Costs of sync moves
+
+ Returns
+ -------
+ :return: Synchronous product net and associated marking labels are of the form (a,>>)
+ """
+ sync_net = PetriNet(
+ "synchronous_product_net of %s and %s" % (pn1.name, pn2.name)
+ )
+ t1_map, p1_map = __copy_into(pn1, sync_net, True, skip)
+ t2_map, p2_map = __copy_into(pn2, sync_net, False, skip)
+ costs = dict()
+
+ for t1 in pn1.transitions:
+ costs[t1_map[t1]] = pn1_costs[t1]
+ for t2 in pn2.transitions:
+ costs[t2_map[t2]] = pn2_costs[t2]
+
+ for t1 in pn1.transitions:
+ for t2 in pn2.transitions:
+ if t1.label == t2.label:
+ sync = PetriNet.Transition(
+ (t1.name, t2.name), (t1.label, t2.label)
+ )
+ sync_net.transitions.add(sync)
+ costs[sync] = sync_costs[(t1, t2)]
+ # copy the properties of the transitions inside the transition
+ # of the sync net
+ for p1 in t1.properties:
+ sync.properties[p1] = t1.properties[p1]
+ for p2 in t2.properties:
+ sync.properties[p2] = t2.properties[p2]
+ for a in t1.in_arcs:
+ add_arc_from_to(p1_map[a.source], sync, sync_net)
+ for a in t2.in_arcs:
+ add_arc_from_to(p2_map[a.source], sync, sync_net)
+ for a in t1.out_arcs:
+ add_arc_from_to(sync, p1_map[a.target], sync_net)
+ for a in t2.out_arcs:
+ add_arc_from_to(sync, p2_map[a.target], sync_net)
+
+ sync_im = Marking()
+ sync_fm = Marking()
+ for p in im1:
+ sync_im[p1_map[p]] = im1[p]
+ for p in im2:
+ sync_im[p2_map[p]] = im2[p]
+ for p in fm1:
+ sync_fm[p1_map[p]] = fm1[p]
+ for p in fm2:
+ sync_fm[p2_map[p]] = fm2[p]
+
+ # update 06/02/2021: to distinguish the sync nets that are output of this
+ # method, put a property in the sync net
+ sync_net.properties[properties.IS_SYNC_NET] = True
+
+ return sync_net, sync_im, sync_fm, costs
+
+
+def __copy_into(source_net, target_net, upper, skip):
+ t_map = {}
+ p_map = {}
+ for t in source_net.transitions:
+ name = (t.name, skip) if upper else (skip, t.name)
+ label = (t.label, skip) if upper else (skip, t.label)
+ t_map[t] = PetriNet.Transition(name, label)
+ if properties.TRACE_NET_TRANS_INDEX in t.properties:
+ # 16/02/2021: copy the index property from the transition of the
+ # trace net
+ t_map[t].properties[properties.TRACE_NET_TRANS_INDEX] = (
+ t.properties[properties.TRACE_NET_TRANS_INDEX]
+ )
+ target_net.transitions.add(t_map[t])
+
+ for p in source_net.places:
+ name = (p.name, skip) if upper else (skip, p.name)
+ p_map[p] = PetriNet.Place(name)
+ if properties.TRACE_NET_PLACE_INDEX in p.properties:
+ # 16/02/2021: copy the index property from the place of the trace
+ # net
+ p_map[p].properties[properties.TRACE_NET_PLACE_INDEX] = (
+ p.properties[properties.TRACE_NET_PLACE_INDEX]
+ )
+ target_net.places.add(p_map[p])
+
+ for t in source_net.transitions:
+ for a in t.in_arcs:
+ add_arc_from_to(p_map[a.source], t_map[t], target_net)
+ for a in t.out_arcs:
+ add_arc_from_to(t_map[t], p_map[a.target], target_net)
+
+ return t_map, p_map
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/BinaryRelation.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/BinaryRelation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ac36ffbc6ec41af5c724c899566f8d81f8368a9
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/BinaryRelation.py
@@ -0,0 +1,224 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+import copy
+from itertools import product
+from typing import Hashable, TypeVar, List as TList, Set as TSet
+
+T = TypeVar("T", bound=Hashable)
+
+
+class BinaryRelation:
+
+ def __init__(self, nodes: TList[T]):
+ self._number_nodes = 0
+ self._set_nodes(nodes)
+ self._edges = [
+ [False for _ in range(self._number_nodes)]
+ for _ in range(self._number_nodes)
+ ]
+ self._start_nodes = None
+ self._end_nodes = None
+
+ def get_nodes(self) -> TList[T]:
+ return self._nodes
+
+ def _set_nodes(self, nodes: TList[T]) -> None:
+ self._nodes = nodes
+ self._map_node_to_id = {}
+ self._map_id_to_node = {}
+ n = 0
+ for node in self._nodes:
+ self._map_node_to_id[node] = n
+ self._map_id_to_node[n] = node
+ n = n + 1
+ self._number_nodes = n
+
+ def add_edge(self, source: T, target: T) -> None:
+ try:
+ i = self._map_node_to_id[source]
+ j = self._map_node_to_id[target]
+ except Exception:
+ raise Exception("Unable to add edge! Source or target not found!")
+ else:
+ self._edges[i][j] = True
+
+ def remove_edge(self, source: T, target: T) -> None:
+ try:
+ i = self._map_node_to_id[source]
+ j = self._map_node_to_id[target]
+ except Exception:
+ raise Exception(
+ "Unable to remove edge! Invalid source or target!"
+ )
+ else:
+ self._edges[i][j] = False
+
+ def remove_edge_without_violating_transitivity(
+ self, source: T, target: T
+ ) -> None:
+ try:
+ i = self._map_node_to_id[source]
+ j = self._map_node_to_id[target]
+ except Exception:
+ raise Exception(
+ "Unable to remove edge! Invalid source or target!"
+ )
+ else:
+ self._edges[i][j] = False
+ n = len(self.nodes)
+ changed = True
+ while changed:
+ changed = False
+ for i, j, k in product(range(n), range(n), range(n)):
+ if (
+ i != j
+ and j != k
+ and self._edges[i][j]
+ and self._edges[j][k]
+ and not self._edges[i][k]
+ ):
+ self._edges[j][k] = False
+ changed = True
+
+ def add_node(self, node: T) -> None:
+ if node not in self._nodes:
+ self._nodes.append(node)
+ n = self._number_nodes
+ self._map_node_to_id[node] = n
+ self._map_id_to_node[n] = node
+ new_edges = [[False for _ in range(n + 1)] for _ in range(n + 1)]
+ for i in range(n):
+ for j in range(n):
+ new_edges[i][j] = self._edges[i][j]
+
+ self._edges = new_edges
+ self._number_nodes = n + 1
+
+ def is_edge(self, source: T, target: T) -> bool:
+ try:
+ i = self._map_node_to_id[source]
+ j = self._map_node_to_id[target]
+ except Exception:
+ raise Exception(
+ "Unable to create edge! Invalid source or target!"
+ )
+ else:
+ return self._edges[i][j]
+
+ def is_edge_id(self, i: int, j: int) -> bool:
+ return self._edges[i][j]
+
+ def get_transitive_reduction(self) -> "BinaryRelation":
+ if not self.is_irreflexive():
+ raise ValueError(
+ "Cannot generate transitive reduction! Reflexivity detected!"
+ )
+ res = BinaryRelation(self.nodes)
+ res._edges = copy.deepcopy(self._edges)
+ n = len(self.nodes)
+ for i, j, k in product(range(n), range(n), range(n)):
+ if (
+ i != j
+ and j != k
+ and self._edges[i][j]
+ and self._edges[j][k]
+ and res._edges[i][k]
+ ):
+ res._edges[i][k] = False
+ return res
+
+ def add_transitive_edges(self) -> None:
+ n = len(self.nodes)
+ changed = True
+ while changed:
+ changed = False
+ for i, j, k in product(range(n), range(n), range(n)):
+ if (
+ i != j
+ and j != k
+ and self._edges[i][j]
+ and self._edges[j][k]
+ and not self.is_edge_id(i, k)
+ ):
+ self._edges[i][k] = True
+ changed = True
+
+ def is_strict_partial_order(self) -> bool:
+ return self.is_irreflexive() and self.is_transitive()
+
+ def get_start_nodes(self) -> TSet[T]:
+ res = set(self.nodes)
+ for i in range(len(self.nodes)):
+ for j in range(len(self.nodes)):
+ if self._edges[i][j]:
+ res.discard(self._map_id_to_node[j])
+ return res
+
+ def get_end_nodes(self) -> TSet[T]:
+ res = set(self.nodes)
+ for i in range(len(self.nodes)):
+ for j in range(len(self.nodes)):
+ if self._edges[i][j]:
+ res.discard(self._map_id_to_node[i])
+ return res
+
+ def is_irreflexive(self) -> bool:
+ n = len(self.nodes)
+ for i in range(n):
+ if self.is_edge_id(i, i):
+ return False
+ return True
+
+ def is_transitive(self) -> bool:
+ n = len(self.nodes)
+ for i, j, k in product(range(n), range(n), range(n)):
+ if (
+ self.is_edge_id(i, j)
+ and self.is_edge_id(j, k)
+ and not self.is_edge_id(i, k)
+ ):
+ return False
+ return True
+
+ def __repr__(self) -> str:
+ res = "(nodes = { "
+ for node in self._nodes:
+ res = res + node.__repr__() + ", "
+ res = res[:-2]
+ res = res + " }, order = { "
+ for node in self._nodes:
+ i = self._map_node_to_id[node]
+ for node2 in self._nodes:
+ j = self._map_node_to_id[node2]
+ if self._edges[i][j]:
+ res = (
+ res + node.__repr__() + "-->" + node2.__repr__() + ", "
+ )
+ res = res[:-2]
+ return res + " })"
+
+ nodes = property(get_nodes, _set_nodes)
+
+ @property
+ def edges(self):
+ return self._edges
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b884b6ac9883e87e99e12b45ce2d01f2996690d7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.powl import *
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/constants.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..db8e8b74e48bc375eff1385f9a65a070200a52ef
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/constants.py
@@ -0,0 +1,24 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+SILENT_TRANSITION_LABEL = "tau"
+STRICT_PARTIAL_ORDER_LABEL = "PO"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..29d3eb61b1fca90a0e7de467bcaa23863e973912
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/obj.py
@@ -0,0 +1,525 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.powl.BinaryRelation import BinaryRelation
+from pm4py.objects.powl.constants import STRICT_PARTIAL_ORDER_LABEL
+from pm4py.objects.process_tree.obj import ProcessTree, Operator
+from pm4py.util import hie_utils
+import sys
+from typing import List as TList, Optional, Union
+from abc import ABC, abstractmethod
+
+
+class POWL(ProcessTree, ABC):
+ def print(self) -> None:
+ print(self.to_string())
+
+ def simplify_using_frequent_transitions(self) -> "POWL":
+ return self
+
+ def simplify(self) -> "POWL":
+ return self
+
+ def validate_partial_orders(self):
+ if isinstance(self, StrictPartialOrder):
+ if not self.order.is_irreflexive():
+ raise Exception(
+ "The irreflexivity of the partial order is violated!"
+ )
+ if not self.order.is_transitive():
+ raise Exception(
+ "The transitivity of the partial order is violated!"
+ )
+ if hasattr(self, "children"):
+ for child in self.children:
+ child.validate_partial_orders()
+
+ @staticmethod
+ def model_description() -> str:
+ descr = """A partially ordered workflow language (POWL) is a partially ordered graph representation of a process, extended with control-flow operators for modeling choice and loop structures. There are four types of POWL models:
+- an activity (identified by its label, i.e., 'M' identifies the activity M). Silent activities with empty labels (tau labels) are also supported.
+- a choice of other POWL models (an exclusive choice between the sub-models A and B is identified by X ( A, B ) )
+- a loop node between two POWL models (a loop between the sub-models A and B is identified by * ( A, B ) and tells that you execute A, then you either exit the loop or execute B and then A again, this is repeated until you exit the loop).
+- a partial order over a set of POWL models. A partial order is a binary relation that is irreflexive, transitive, and asymmetric. A partial order sets an execution order between the sub-models (i.e., the target node cannot be executed before the source node is completed). Unconnected nodes in a partial order are considered to be concurrent. An example is PO=(nodes={ NODE1, NODE2 }, order={ })
+where NODE1 and NODE2 are independent and can be executed in parallel. Another example is PO=(nodes={ NODE1, NODE2 }, order={ NODE1-->NODE2 }) where NODE2 can only be executed after NODE1 is completed.
+
+A more advanced example: PO=(nodes={ NODE1, NODE2, NODE3, X ( NODE4, NODE5 ) }, order={ NODE1-->NODE2, NODE1-->X ( NODE4, NODE5 ), NODE2-->X ( NODE4, NODE5 ) }), in this case, NODE2 can be executed only after NODE1 is completed, while the choice between NODE4 and NODE5 needs to wait until both NODE1 and NODE2 are finalized.
+
+
+"""
+ return descr
+
+ @abstractmethod
+ def copy(self):
+ pass
+
+
+class Transition(POWL):
+ transition_id: int = 0
+
+ def __init__(self, label: Optional[str] = None) -> None:
+ super().__init__()
+ self._label = label
+ self._identifier = Transition.transition_id
+ Transition.transition_id = Transition.transition_id + 1
+
+ def copy(self):
+ return Transition(self._label)
+
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, Transition):
+ return (
+ self._label == other._label
+ and self._identifier == other._identifier
+ )
+ return False
+
+ def equal_content(self, other: object) -> bool:
+ if isinstance(other, Transition):
+ return self._label == other._label
+ return False
+
+ def __hash__(self) -> int:
+ return self._identifier
+
+ def __lt__(self, other: object) -> bool:
+ if isinstance(other, Transition):
+ if self.label and other.label and self.label < other.label:
+ return self.label < other.label
+ return self._identifier < other._identifier
+ elif isinstance(other, OperatorPOWL):
+ return True
+ elif isinstance(other, StrictPartialOrder):
+ return True
+ return NotImplemented
+
+
+class SilentTransition(Transition):
+ def __init__(self) -> None:
+ super().__init__(label=None)
+
+ def copy(self):
+ return SilentTransition()
+
+
+class FrequentTransition(Transition):
+ def __init__(
+ self, label, min_freq: Union[str, int], max_freq: Union[str, int]
+ ) -> None:
+ self.skippable = False
+ self.selfloop = False
+ if min_freq == 0:
+ self.skippable = True
+ if max_freq == "-":
+ self.selfloop = True
+ min_freq = "1"
+ self.activity = label
+ if self.skippable or self.selfloop:
+ label = (
+ str(label)
+ + "\n"
+ + "["
+ + str(min_freq)
+ + ","
+ + str(max_freq)
+ + "]"
+ )
+
+ super().__init__(label=label)
+
+
+class StrictPartialOrder(POWL):
+
+ def __init__(self, nodes: TList[POWL]) -> None:
+ super().__init__()
+ self.operator = Operator.PARTIALORDER
+ self._set_order(nodes)
+ self.additional_information = None
+
+ def copy(self):
+ copied_nodes = {n: n.copy() for n in self.order.nodes}
+ res = StrictPartialOrder(list(copied_nodes.values()))
+ for n1 in self.order.nodes:
+ for n2 in self.order.nodes:
+ if self.order.is_edge(n1, n2):
+ res.add_edge(copied_nodes[n1], copied_nodes[n2])
+ return res
+
+ def _set_order(self, nodes: TList[POWL]) -> None:
+ self.order = BinaryRelation(nodes)
+
+ def get_order(self) -> BinaryRelation:
+ return self.order
+
+ def _set_children(self, children: TList[POWL]) -> None:
+ self.order.nodes = children
+
+ def get_children(self) -> TList[POWL]:
+ return self.order.nodes
+
+ def to_string(self, level=0, indent=False, max_indent=sys.maxsize) -> str:
+ """
+ Represents a StrictPartialOrder as a string, avoiding infinite recursion.
+
+ Parameters
+ ----------
+ level : int
+ Current indentation level
+ indent : bool
+ Whether to indent the output
+ max_indent : int
+ Maximum indentation level
+
+ Returns
+ -------
+ str
+ String representation of the partial order
+ """
+ # Start with the partial order label
+ rep = f"{STRICT_PARTIAL_ORDER_LABEL}=(nodes={{"
+
+ # Represent the nodes (children)
+ nodes_str = []
+ for i, node in enumerate(self.order.nodes):
+ # Call to_string on each child with increased level, preventing recursive blow-up
+ node_str = node.to_string(level=level + 1, indent=False, max_indent=max_indent)
+ nodes_str.append(node_str)
+ rep += ", ".join(nodes_str)
+ rep += "}, order={"
+
+ # Represent the edges in the partial order
+ edges_str = []
+ for source in self.order.nodes:
+ for target in self.order.nodes:
+ if self.order.is_edge(source, target):
+ # Use a simplified representation for source and target to avoid recursion
+ source_str = source.label if source.label else f"id_{hash(source)}"
+ target_str = target.label if target.label else f"id_{hash(target)}"
+ edges_str.append(f"{source_str}-->{target_str}")
+ rep += ", ".join(edges_str)
+ rep += "})"
+
+ # Apply indentation if requested
+ if indent and level <= max_indent:
+ rep = "\n".join(hie_utils.indent_representation(rep, max_indent=max_indent))
+
+ return rep
+
+ def __repr__(self) -> str:
+ return self.to_string()
+
+ def __lt__(self, other: object) -> bool:
+ if isinstance(other, StrictPartialOrder):
+ return self.__repr__() < other.__repr__()
+ elif isinstance(other, OperatorPOWL):
+ return False
+ elif isinstance(other, Transition):
+ return False
+ return NotImplemented
+
+ partial_order = property(get_order, _set_order)
+ children = property(get_children, _set_children)
+
+ # def __eq__(self, other):
+ # if not isinstance(other, StrictPartialOrder):
+ # return False
+ #
+ # ordered_nodes_1 = sorted(list(self.order.nodes))
+ # ordered_nodes_2 = sorted(list(other.order.nodes))
+ # if len(ordered_nodes_1) != len(ordered_nodes_2):
+ # return False
+ # for i in range(len(ordered_nodes_1)):
+ # source_1 = ordered_nodes_1[i]
+ # source_2 = ordered_nodes_2[i]
+ # if not source_1.__eq__(source_2):
+ # return False
+ # for j in range(len(ordered_nodes_1)):
+ # target_1 = ordered_nodes_1[j]
+ # target_2 = ordered_nodes_2[j]
+ # if self.order.is_edge(source_1, target_1) and not other.order.is_edge(source_2, target_2):
+ # return False
+ # if not self.order.is_edge(source_1, target_1) and other.order.is_edge(source_2, target_2):
+ # return False
+ # return True
+
+ def equal_content(self, other: object) -> bool:
+ if not isinstance(other, StrictPartialOrder):
+ return False
+
+ ordered_nodes_1 = sorted(list(self.order.nodes))
+ ordered_nodes_2 = sorted(list(other.order.nodes))
+ if len(ordered_nodes_1) != len(ordered_nodes_2):
+ return False
+ for i in range(len(ordered_nodes_1)):
+ source_1 = ordered_nodes_1[i]
+ source_2 = ordered_nodes_2[i]
+ if not source_1.equal_content(source_2):
+ return False
+ for j in range(len(ordered_nodes_1)):
+ target_1 = ordered_nodes_1[j]
+ target_2 = ordered_nodes_2[j]
+ if self.order.is_edge(
+ source_1, target_1
+ ) and not other.order.is_edge(source_2, target_2):
+ return False
+ if not self.order.is_edge(
+ source_1, target_1
+ ) and other.order.is_edge(source_2, target_2):
+ return False
+ return True
+
+ def simplify_using_frequent_transitions(self) -> "StrictPartialOrder":
+ new_nodes = {
+ node: node.simplify_using_frequent_transitions()
+ for node in self.children
+ }
+ res = StrictPartialOrder(list(new_nodes.values()))
+ for node_1 in self.children:
+ for node_2 in self.children:
+ if self.partial_order.is_edge(node_1, node_2):
+ res.partial_order.add_edge(
+ new_nodes[node_1], new_nodes[node_2]
+ )
+
+ return res
+
+ def simplify(self) -> "StrictPartialOrder":
+ simplified_nodes = {}
+ sub_nodes = {}
+ start_nodes = {}
+ end_nodes = {}
+
+ def connected(node):
+ for node2 in self.children:
+ if self.partial_order.is_edge(
+ node, node2
+ ) or self.partial_order.is_edge(node2, node):
+ return True
+ return False
+
+ for node_1 in self.children:
+ simplified_node = node_1.simplify()
+ if isinstance(simplified_node, StrictPartialOrder):
+
+ if not connected(node_1):
+ sub_nodes[node_1] = simplified_node
+ else:
+ s_nodes = simplified_node.order.get_start_nodes()
+ e_nodes = simplified_node.order.get_end_nodes()
+ if len(s_nodes) == 1 and len(e_nodes) == 1:
+ sub_nodes[node_1] = simplified_node
+ start_nodes[node_1] = list(s_nodes)[0]
+ end_nodes[node_1] = list(e_nodes)[0]
+ else:
+ simplified_nodes[node_1] = simplified_node
+ else:
+ simplified_nodes[node_1] = simplified_node
+
+ new_nodes = list(simplified_nodes.values())
+ for po, simplified_po in sub_nodes.items():
+ new_nodes = new_nodes + list(simplified_po.children)
+ res = StrictPartialOrder(new_nodes)
+ for node_1 in self.children:
+ for node_2 in self.children:
+ if self.partial_order.is_edge(node_1, node_2):
+ if (
+ node_1 in simplified_nodes.keys()
+ and node_2 in simplified_nodes.keys()
+ ):
+ res.partial_order.add_edge(
+ simplified_nodes[node_1], simplified_nodes[node_2]
+ )
+ elif node_1 in simplified_nodes.keys():
+ res.partial_order.add_edge(
+ simplified_nodes[node_1], start_nodes[node_2]
+ )
+ elif node_2 in simplified_nodes.keys():
+ res.partial_order.add_edge(
+ end_nodes[node_1], simplified_nodes[node_2]
+ )
+ else:
+ res.partial_order.add_edge(
+ end_nodes[node_1], start_nodes[node_2]
+ )
+ for po, simplified_po in sub_nodes.items():
+ for node_1 in simplified_po.children:
+ for node_2 in simplified_po.children:
+ if simplified_po.partial_order.is_edge(node_1, node_2):
+ res.partial_order.add_edge(node_1, node_2)
+ return res
+
+ def add_edge(self, source, target):
+ return self.order.add_edge(source, target)
+
+
+class Sequence(StrictPartialOrder):
+
+ def __init__(self, nodes: TList[POWL]) -> None:
+ super().__init__(nodes)
+ for i in range(len(nodes)):
+ for j in range(i + 1, len(nodes)):
+ self.partial_order.add_edge(nodes[i], nodes[j])
+
+
+class OperatorPOWL(POWL):
+ def __init__(self, operator: Operator, children: TList[POWL]) -> None:
+ if operator is Operator.XOR:
+ if len(children) < 2:
+ raise Exception(
+ "Cannot create a choice of less than 2 submodels!"
+ )
+ elif operator is Operator.LOOP:
+ if len(children) != 2:
+ raise Exception("Only loops of length 2 are supported!")
+ else:
+ raise Exception("Unsupported Operator!")
+ super().__init__()
+ self.operator = operator
+ self.children = children
+
+ def copy(self):
+ copied_nodes = [n.copy() for n in self.children]
+ return OperatorPOWL(self.operator, copied_nodes)
+
+ def __lt__(self, other: object) -> bool:
+ if isinstance(other, OperatorPOWL):
+ return self.__repr__() < other.__repr__()
+ elif isinstance(other, Transition):
+ return False
+ elif isinstance(other, StrictPartialOrder):
+ return True
+ return NotImplemented
+
+ def equal_content(self, other: object) -> bool:
+ if not isinstance(other, OperatorPOWL):
+ return False
+
+ if self.operator != other.operator:
+ return False
+
+ ordered_nodes_1 = sorted(list(self.children))
+ ordered_nodes_2 = sorted(list(other.children))
+ if len(ordered_nodes_1) != len(ordered_nodes_2):
+ return False
+ for i in range(len(ordered_nodes_1)):
+ node_1 = ordered_nodes_1[i]
+ node_2 = ordered_nodes_2[i]
+ if not node_1.equal_content(node_2):
+ return False
+ return True
+
+ def simplify_using_frequent_transitions(self) -> POWL:
+ if self.operator is Operator.XOR and len(self.children) == 2:
+ child_0 = self.children[0]
+ child_1 = self.children[1]
+ if isinstance(child_0, Transition) and isinstance(
+ child_1, SilentTransition
+ ):
+ return FrequentTransition(
+ label=child_0.label, min_freq=0, max_freq=1
+ )
+ elif isinstance(child_1, Transition) and isinstance(
+ child_0, SilentTransition
+ ):
+ return FrequentTransition(
+ label=child_1.label, min_freq=0, max_freq=1
+ )
+
+ if self.operator is Operator.LOOP and len(self.children) == 2:
+ child_0 = self.children[0]
+ child_1 = self.children[1]
+ if isinstance(child_0, Transition) and isinstance(
+ child_1, SilentTransition
+ ):
+ return FrequentTransition(
+ label=child_0.label, min_freq=1, max_freq="-"
+ )
+ elif isinstance(child_1, Transition) and isinstance(
+ child_0, SilentTransition
+ ):
+ return FrequentTransition(
+ label=child_1.label, min_freq=0, max_freq="-"
+ )
+
+ return OperatorPOWL(
+ self.operator,
+ [
+ child.simplify_using_frequent_transitions()
+ for child in self.children
+ ],
+ )
+
+ def simplify(self) -> "OperatorPOWL":
+ if self.operator is Operator.XOR and len(self.children) == 2:
+ child_0 = self.children[0]
+ child_1 = self.children[1]
+
+ def merge_with_children(child0, child1):
+ if (
+ isinstance(child0, SilentTransition)
+ and isinstance(child1, OperatorPOWL)
+ and child1.operator is Operator.LOOP
+ ):
+ if isinstance(child1.children[0], SilentTransition):
+ return OperatorPOWL(
+ Operator.LOOP,
+ [n.simplify() for n in child1.children],
+ )
+ elif isinstance(child1.children[1], SilentTransition):
+ return OperatorPOWL(
+ Operator.LOOP,
+ list(
+ reversed(
+ [n.simplify() for n in child1.children]
+ )
+ ),
+ )
+
+ return None
+
+ res = merge_with_children(child_0, child_1)
+ if res is not None:
+ return res
+
+ res = merge_with_children(child_1, child_0)
+ if res is not None:
+ return res
+
+ if self.operator is Operator.XOR:
+ new_children = []
+ for child in self.children:
+ s_child = child.simplify()
+ if (
+ isinstance(s_child, OperatorPOWL)
+ and s_child.operator is Operator.XOR
+ ):
+ for node in s_child.children:
+ new_children.append(node.simplify())
+ else:
+ new_children.append(s_child)
+ return OperatorPOWL(
+ Operator.XOR, [child for child in new_children]
+ )
+ else:
+ return OperatorPOWL(
+ self.operator, [child.simplify() for child in self.children]
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/parser.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..159d99471963d049796f8a9d535ebd4256828f22
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/parser.py
@@ -0,0 +1,143 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.powl.obj import (
+ POWL,
+ OperatorPOWL,
+ StrictPartialOrder,
+ SilentTransition,
+ Transition,
+)
+from pm4py.objects.process_tree.obj import Operator as PTOperator
+from pm4py.util import hie_utils
+import re
+
+
+def parse_powl_model_string(powl_string, level=0) -> POWL:
+ """
+ Parse a POWL model from a string representation of the process model
+ (with the same format as the __repr__ and __str__ methods of the POWL model)
+
+ Minimum Viable Example:
+
+ from pm4py.objects.powl.parser import parse_powl_model_string
+
+ powl_model = parse_powl_model_string('PO=(nodes={ NODE1, NODE2, NODE3 }, order={ NODE1-->NODE2 }')
+ print(powl_model)
+
+
+ Parameters
+ ------------------
+ powl_string
+ POWL model expressed as a string (__repr__ of the POWL model)
+
+ Returns
+ ------------------
+ powl_model
+ POWL model
+ """
+ powl_string = (
+ powl_string.replace("\n", "")
+ .replace("\r", "")
+ .replace("\t", "")
+ .strip()
+ )
+ max_indent = 1
+ if powl_string.startswith("PO=") or powl_string.startswith("PO("):
+ max_indent = 2
+ if powl_string.startswith("'"):
+ max_indent = 0
+
+ indented_str_list = hie_utils.indent_representation(
+ powl_string, max_indent=max_indent
+ )
+
+ indented_str_list = [x.strip() for x in indented_str_list]
+ indented_str_list = [
+ x[:-1] if x and x[-1] == "," else x for x in indented_str_list
+ ]
+ PO = None
+ nodes = []
+
+ if indented_str_list:
+ if indented_str_list[0].startswith("PO=") or indented_str_list[
+ 0
+ ].startswith("PO("):
+ nodes_dict = {}
+
+ # read the nodes of the POWL
+ i = 2
+ while i < len(indented_str_list):
+ if indented_str_list[i] == "}":
+ break
+ N = parse_powl_model_string(indented_str_list[i], level + 1)
+ nodes_dict[indented_str_list[i]] = N
+ nodes.append(N)
+ i = i + 1
+
+ pattern = "(" + "|".join(map(re.escape, list(nodes_dict))) + ")"
+
+ PO = StrictPartialOrder(nodes=nodes)
+
+ # reads the edges of the POWL
+ i = i + 2
+ while i < len(indented_str_list):
+ if indented_str_list[i] == "}":
+ break
+
+ split_list = [
+ x for x in re.split(pattern, indented_str_list[i]) if x
+ ]
+
+ if len(split_list) == 3:
+ PO.order.add_edge(
+ nodes_dict[split_list[0]], nodes_dict[split_list[2]]
+ )
+
+ i = i + 1
+
+ elif indented_str_list[0].startswith("X"):
+ i = 1
+ while i < len(indented_str_list):
+ if indented_str_list[i] == ")":
+ break
+ N = parse_powl_model_string(indented_str_list[i], level + 1)
+ nodes.append(N)
+ i = i + 1
+ PO = OperatorPOWL(PTOperator.XOR, nodes)
+ elif indented_str_list[0].startswith("*"):
+ i = 1
+ while i < len(indented_str_list):
+ if indented_str_list[i] == ")":
+ break
+ N = parse_powl_model_string(indented_str_list[i], level + 1)
+ nodes.append(N)
+ i = i + 1
+ PO = OperatorPOWL(PTOperator.LOOP, nodes)
+ elif indented_str_list[0].startswith("tau"):
+ PO = SilentTransition()
+ else:
+ label = indented_str_list[0]
+ if label.startswith("'"):
+ label = label[1:-1]
+ PO = Transition(label=label)
+
+ return PO
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/utils/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/utils/label_replacing.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/utils/label_replacing.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5dbd980096b67cbd56737490aa596aa6bf0f72a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/powl/utils/label_replacing.py
@@ -0,0 +1,55 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.powl.obj import POWL
+from typing import Optional, Dict, Any
+from copy import deepcopy
+
+
+def apply(powl: POWL, string_dictio: Dict[str, str], rec_depth=0, parameters: Optional[Dict[Any, Any]] = None) -> POWL:
+ """
+ Replaces the labels in the given POWL object using the provided dictionary.
+
+ Parameters
+ ---------------
+ powl
+ POWL
+ string_dictio
+ Correspondence dictionary (old labels -> new labels)
+
+ Returns
+ ----------------
+ revised_powl
+ Revised POWL
+ """
+ if parameters is None:
+ parameters = {}
+
+ if rec_depth == 0:
+ powl = deepcopy(powl)
+
+ if powl.label is not None and powl.label in string_dictio:
+ powl.label = string_dictio[powl.label]
+
+ for child in powl.children:
+ apply(child, string_dictio, rec_depth=rec_depth+1, parameters=parameters)
+
+ return powl
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f104f6e72ea919bd3eed1998c51d9400084f2b5a
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/__init__.py
@@ -0,0 +1,29 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.process_tree import obj, semantics, state, utils
+ import importlib.util
+
+ if importlib.util.find_spec("lxml"):
+ from pm4py.objects.process_tree import importer, exporter
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..27fa1cbdf7143d5262f33fdd2d3b4d2148c7d9a2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree.exporter import variants, exporter
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/exporter.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..235467250c176099b92fff1f7b5af06ee04981e4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/exporter.py
@@ -0,0 +1,76 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree.exporter.variants import ptml
+from pm4py.util import exec_utils
+from enum import Enum
+
+
+class Variants(Enum):
+ PTML = ptml
+
+
+DEFAULT_VARIANT = Variants.PTML
+
+
+def apply(tree, output_path, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Exports the process tree to a file
+
+ Parameters
+ ----------------
+ tree
+ Process tree
+ output_path
+ Output path
+ variant
+ Variant of the algorithm:
+ - Variants.PTML
+ parameters
+ Parameters
+ """
+ return exec_utils.get_variant(variant).apply(
+ tree, output_path, parameters=parameters
+ )
+
+
+def serialize(tree, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Serializes the process tree into a binary string
+
+ Parameters
+ ----------------
+ tree
+ Process tree
+ variant
+ Variant of the algorithm:
+ - Variants.PTML
+ parameters
+ Parameters
+
+ Returns
+ ---------------
+ serialization
+ Serialized string
+ """
+ return exec_utils.get_variant(variant).export_tree_as_string(
+ tree, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a37032dc906471c614e7673ca52669674851528e
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree.exporter.variants import ptml
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/variants/ptml.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/variants/ptml.py
new file mode 100644
index 0000000000000000000000000000000000000000..58fb5ffc7803279280671ecd114254ccdbabec19
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/exporter/variants/ptml.py
@@ -0,0 +1,205 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+import uuid
+
+from lxml import etree
+
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.objects.process_tree.obj import Operator
+from pm4py.util import constants, exec_utils
+from enum import Enum
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def get_list_nodes_from_tree(tree, parameters=None):
+ """
+ Gets the list of nodes from a process tree
+
+ Parameters
+ ---------------
+ tree
+ Process tree
+ parameters
+ Parameters
+
+ Returns
+ ---------------
+ list_nodes
+ List of nodes of the process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ list_nodes = []
+ to_visit = [tree]
+
+ while len(to_visit) > 0:
+ node = to_visit.pop(0)
+ for child in node.children:
+ to_visit.append(child)
+ list_nodes.append(node)
+
+ return list_nodes
+
+
+def export_ptree_tree(tree, parameters=None):
+ """
+ Exports the XML tree from a process tree
+
+ Parameters
+ -----------------
+ tree
+ Process tree
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -----------------
+ xml_tree
+ XML tree object
+ """
+ tree = copy.deepcopy(tree)
+ if parameters is None:
+ parameters = {}
+
+ nodes = get_list_nodes_from_tree(tree, parameters=parameters)
+ nodes_dict = {(id(x), x): str(uuid.uuid4()) for x in nodes}
+
+ # make sure that in the exporting, loops have 3 children
+ # (for ProM compatibility)
+ # just add a skip as third child
+ for node in nodes:
+ if node.operator == Operator.LOOP and len(node.children) < 3:
+ third_children = ProcessTree(operator=None, label=None)
+ third_children.parent = node
+ node.children.append(third_children)
+ nodes_dict[(id(third_children), third_children)] = str(
+ uuid.uuid4()
+ )
+
+ # repeat twice (structure has changed)
+ nodes = get_list_nodes_from_tree(tree, parameters=parameters)
+ nodes_dict = {(id(x), x): str(uuid.uuid4()) for x in nodes}
+
+ root = etree.Element("ptml")
+ processtree = etree.SubElement(root, "processTree")
+ processtree.set("name", str(uuid.uuid4()))
+ processtree.set("root", nodes_dict[(id(tree), tree)])
+ processtree.set("id", str(uuid.uuid4()))
+
+ for node in nodes:
+ nk = nodes_dict[(id(node), node)]
+ child = None
+ if node.operator is None:
+ if node.label is None:
+ child = etree.SubElement(processtree, "automaticTask")
+ child.set("name", "")
+ else:
+ child = etree.SubElement(processtree, "manualTask")
+ child.set("name", node.label)
+ else:
+ if node.operator is Operator.SEQUENCE:
+ child = etree.SubElement(processtree, "sequence")
+ elif node.operator is Operator.XOR:
+ child = etree.SubElement(processtree, "xor")
+ elif node.operator is Operator.PARALLEL:
+ child = etree.SubElement(processtree, "and")
+ elif node.operator is Operator.OR:
+ child = etree.SubElement(processtree, "or")
+ elif node.operator is Operator.LOOP:
+ child = etree.SubElement(processtree, "xorLoop")
+ child.set("name", "")
+ child.set("id", nk)
+
+ for node in nodes:
+ if not node == tree:
+ child = etree.SubElement(processtree, "parentsNode")
+ child.set("id", str(uuid.uuid4()))
+ child.set("sourceId", nodes_dict[(id(node.parent), node.parent)])
+ child.set("targetId", nodes_dict[(id(node), node)])
+
+ tree = etree.ElementTree(root)
+ return tree
+
+
+def export_tree_as_string(tree, parameters=None):
+ """
+ Exports a process tree as a string
+
+ Parameters
+ ---------------
+ tree
+ Process tree
+ parameters
+ Parameters
+
+ Returns
+ ---------------
+ stri
+ XML string describing the process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ # gets the XML tree
+ tree = export_ptree_tree(tree, parameters=parameters)
+
+ return etree.tostring(tree, xml_declaration=True, encoding=encoding)
+
+
+def apply(tree, output_path, parameters=None):
+ """
+ Exports the process tree to a XML (.PTML) file
+
+ Parameters
+ ----------------
+ tree
+ Process tree
+ output_path
+ Output path
+ parameters
+ Parameters
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ # gets the XML tree
+ tree = export_ptree_tree(tree, parameters=parameters)
+
+ # exports the tree to a file
+ F = open(output_path, "wb")
+ tree.write(F, pretty_print=True, xml_declaration=True, encoding=encoding)
+ F.close()
+
+ return tree
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d5f1581f4be3eff5d6d5457162fcac6acda1f2c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree.importer import variants, importer
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/importer.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae94ba7de10882c6c1480e61202fa0fd04debe6
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/importer.py
@@ -0,0 +1,80 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+from pm4py.objects.process_tree.importer.variants import ptml
+from pm4py.util import exec_utils
+
+
+class Variants(Enum):
+ PTML = ptml
+
+
+DEFAULT_VARIANT = Variants.PTML
+
+
+def apply(file_path, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Imports a process tree from the specified path
+
+ Parameters
+ ---------------
+ path
+ Path
+ variant
+ Variant of the algorithm, possible values:
+ - Variants.PTML
+ parameters
+ Possible parameters (version specific)
+
+ Returns
+ ---------------
+ tree
+ Process tree
+ """
+ return exec_utils.get_variant(variant).apply(
+ file_path, parameters=parameters
+ )
+
+
+def deserialize(tree_string, variant=DEFAULT_VARIANT, parameters=None):
+ """
+ Deserialize a text/binary string representing a process tree in the PTML format
+
+ Parameters
+ ----------
+ tree_string
+ Process tree expressed as PTML string
+ variant
+ Variant of the algorithm, possible values:
+ - Variants.PTML
+ parameters
+ Other parameters of the algorithm
+
+ Returns
+ ----------
+ tree
+ Process tree
+ """
+ return exec_utils.get_variant(variant).import_tree_from_string(
+ tree_string, parameters=parameters
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e4cca24f8657c93c6ae6c222ff8b56d6192d199
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/variants/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree.importer.variants import ptml
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/variants/ptml.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/variants/ptml.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf7d40176e27d7c5d92b8791d636201978a23bd3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/importer/variants/ptml.py
@@ -0,0 +1,186 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from lxml import etree, objectify
+
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.objects.process_tree.obj import Operator
+from pm4py.objects.process_tree.utils.generic import tree_sort
+from pm4py.util import constants, exec_utils
+from enum import Enum
+
+
+class Parameters(Enum):
+ ENCODING = "encoding"
+
+
+def apply(path, parameters=None):
+ """
+ Imports a PTML file from the specified path
+
+ Parameters
+ ---------------
+ path
+ Path
+ parameters
+ Possible parameters
+
+ Returns
+ ---------------
+ tree
+ Process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, None
+ )
+
+ parser = etree.XMLParser(remove_comments=True, encoding=encoding)
+
+ F = open(path, "rb")
+ xml_tree = objectify.parse(F, parser=parser)
+ F.close()
+
+ root = xml_tree.getroot()
+
+ return import_tree_from_xml_object(root, parameters=parameters)
+
+
+def import_tree_from_string(tree_string, parameters=None):
+ """
+ Imports a PTML file from a (binary) string
+
+ Parameters
+ ---------------
+ tree_string
+ String representing the process tree
+ parameters
+ Possible parameters
+
+ Returns
+ ---------------
+ tree
+ Process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ encoding = exec_utils.get_param_value(
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
+ )
+
+ if type(tree_string) is str:
+ tree_string = tree_string.encode(encoding)
+
+ parser = etree.XMLParser(remove_comments=True)
+ root = objectify.fromstring(tree_string, parser=parser)
+
+ return import_tree_from_xml_object(root, parameters=parameters)
+
+
+def import_tree_from_xml_object(root, parameters=None):
+ """
+ Imports a process tree from the XML object
+
+ Parameters
+ ---------------
+ root
+ Root of the XML object
+ parameters
+ Possible parameters
+
+ Returns
+ ---------------
+ tree
+ Process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ nodes = {}
+
+ for c0 in root:
+ root = c0.get("root")
+ for child in c0:
+ tag = child.tag
+ id = child.get("id")
+ name = child.get("name")
+ sourceId = child.get("sourceId")
+ targetId = child.get("targetId")
+ if name is not None:
+ # node
+ if tag == "and":
+ operator = Operator.PARALLEL
+ label = None
+ elif tag == "sequence":
+ operator = Operator.SEQUENCE
+ label = None
+ elif tag == "xor":
+ operator = Operator.XOR
+ label = None
+ elif tag == "xorLoop":
+ operator = Operator.LOOP
+ label = None
+ elif tag == "or":
+ operator = Operator.OR
+ label = None
+ elif tag == "manualTask":
+ operator = None
+ label = name
+ elif tag == "automaticTask":
+ operator = None
+ label = None
+ else:
+ raise Exception("unknown tag: " + tag)
+ tree = ProcessTree(operator=operator, label=label)
+ nodes[id] = tree
+ else:
+ nodes[sourceId].children.append(nodes[targetId])
+ nodes[targetId].parent = nodes[sourceId]
+
+ # make sure that .PTML files having loops with 3 children are imported
+ # into the PM4Py process tree structure
+ # we want loops to have two children
+ for node in nodes.values():
+ if node.operator == Operator.LOOP and len(node.children) == 3:
+ if not (
+ node.children[2].operator is None
+ and node.children[2].label is None
+ ):
+ parent_node = node.parent
+ new_parent_node = ProcessTree(
+ operator=Operator.SEQUENCE, label=None
+ )
+ node.parent = new_parent_node
+ new_parent_node.children.append(node)
+ node.children[2].parent = new_parent_node
+ new_parent_node.children.append(node.children[2])
+ if parent_node is not None:
+ new_parent_node.parent = parent_node
+ del parent_node.children[parent_node.children.index(node)]
+ parent_node.children.append(new_parent_node)
+ del node.children[2]
+
+ root = nodes[root]
+ tree_sort(root)
+ return root
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f01a765dae66cbb70244c9f9891de3a48c206d0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/obj.py
@@ -0,0 +1,283 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+from pm4py.util import hie_utils
+import sys
+
+
+class Operator(Enum):
+ # sequence operator
+ SEQUENCE = "->"
+ # exclusive choice operator
+ XOR = "X"
+ # parallel operator
+ PARALLEL = "+"
+ # loop operator
+ LOOP = "*"
+ # or operator
+ OR = "O"
+ # interleaving operator
+ INTERLEAVING = "<>"
+ # partially-ordered operator
+ PARTIALORDER = "PO"
+
+ def __str__(self):
+ """
+ Provides a string representation of the current operator
+
+ Returns
+ -----------
+ stri
+ String representation of the process tree
+ """
+ return self.value
+
+ def __repr__(self):
+ """
+ Provides a string representation of the current operator
+
+ Returns
+ -----------
+ stri
+ String representation of the process tree
+ """
+ return self.value
+
+
+class ProcessTree(object):
+
+ class OperatorState(Enum):
+ ENABLED = "enabled"
+ OPEN = "open"
+ CLOSED = "closed"
+ FUTURE = "future"
+
+ def __init__(self, operator=None, parent=None, children=None, label=None):
+ """
+ Constructor
+
+ Parameters
+ ------------
+ operator
+ Operator (of the current node) of the process tree
+ parent
+ Parent node (of the current node)
+ children
+ List of children of the current node
+ label
+ Label (of the current node)
+ """
+ self._operator = operator
+ self._parent = parent
+ self._children = list() if children is None else children
+ self._label = label
+ self._properties = {}
+
+ def __hash__(self):
+ if self.label is not None:
+ return hash(self.label)
+ elif len(self.children) == 0:
+ return 37
+ else:
+ h = 1337
+ for i in range(len(self.children)):
+ h += 41 * i * hash(self.children[i])
+ if self.operator == Operator.SEQUENCE:
+ h = h * 13
+ elif self.operator == Operator.XOR:
+ h = h * 17
+ elif self.operator == Operator.OR:
+ h = h * 23
+ elif self.operator == Operator.PARALLEL:
+ h = h * 29
+ elif self.operator == Operator.LOOP:
+ h = h * 37
+ elif self.operator == Operator.INTERLEAVING:
+ h = h * 41
+ elif self.operator == Operator.PARTIALORDER:
+ h = h * 43
+ return h % 268435456
+
+ def _set_operator(self, operator):
+ self._operator = operator
+
+ def _set_parent(self, parent):
+ self._parent = parent
+
+ def _set_label(self, label):
+ self._label = label
+
+ def _set_children(self, children):
+ self._children = children
+
+ def _get_children(self):
+ return self._children
+
+ def _get_parent(self):
+ return self._parent
+
+ def _get_operator(self):
+ return self._operator
+
+ def _get_label(self):
+ return self._label
+
+ def __eq__(self, other):
+ if isinstance(other, ProcessTree):
+ if self.label is not None:
+ return True if other.label == self.label else False
+ elif len(self.children) == 0:
+ return other.label is None and len(other.children) == 0
+ else:
+ if self.operator == other.operator:
+ if len(self.children) != len(other.children):
+ return False
+ else:
+ for i in range(len(self.children)):
+ if self.children[i] != other.children[i]:
+ return False
+ return True
+ else:
+ return False
+ return False
+
+ def to_string(self, level=0, indent=False, max_indent=sys.maxsize):
+ """
+ Represents a process tree model as a string.
+
+ Parameters
+ -----------------
+ indent
+ Enable the indentation of the resulting string
+ max_indent
+ Maximum level of indentation
+ """
+ if self.operator is not None:
+ rep = str(self._operator) + "( "
+ for i in range(0, len(self._children)):
+ child = self._children[i]
+ if len(child.children) == 0:
+ if child.label is not None:
+ rep += (
+ "'" + child.to_string(level=level + 1) + "'" + ", "
+ if i < len(self._children) - 1
+ else "'" + child.to_string(level=level + 1) + "'"
+ )
+ else:
+ rep += (
+ child.to_string(level=level + 1) + ", "
+ if i < len(self._children) - 1
+ else child.to_string(level=level + 1)
+ )
+ else:
+ rep += (
+ child.to_string(level=level + 1) + ", "
+ if i < len(self._children) - 1
+ else child.to_string(level=level + 1)
+ )
+ stru = rep + " )"
+ if level == 0 and indent:
+ stru = "\n".join(
+ hie_utils.indent_representation(
+ stru, max_indent=max_indent
+ )
+ )
+ return stru
+ elif self.label is not None:
+ return self.label
+ else:
+ return "tau"
+
+ def __repr__(self):
+ """
+ Returns a string representation of the process tree
+
+ Returns
+ ------------
+ stri
+ String representation of the process tree
+ """
+ return self.to_string()
+
+ def __str__(self):
+ """
+ Returns a string representation of the process tree
+
+ Returns
+ ------------
+ stri
+ String representation of the process tree
+ """
+ return self.to_string()
+
+ @staticmethod
+ def model_description() -> str:
+ descr = """A process tree is a hierarchical process model.
+The following operators are defined for process trees:
+-> ( A, B ) tells that the process tree A should be executed before the process tree B
+X ( A, B ) tells that there is an exclusive choice between executing the process tree A or the process tree B
++ ( A, B ) tells that A and B are executed in true concurrency.
+* ( A, B ) is a loop. So the process tree A is executed, then either you exit the loop, or you execute B and then A again (this can happen several times until the loop is exited).
+the leafs of a process tree are either activities (denoted by 'X' where X is the name of the activity) or silent steps (indicated by tau).
+An example process tree follows:
++ ( 'A', -> ( 'B', 'C' ) )
+tells that you should execute B before executing C. In true concurrency, you can execute A. So the possible traces are A->B->C, B->A->C, B->C->A.
+"""
+ return descr
+
+ def _get_root(self):
+ root = self
+ while root._get_parent() is not None:
+ root = root._get_parent()
+ return root
+
+ def _get_leaves(self):
+ root = self._get_root()
+ leaves = [root]
+ if root._get_children() != list():
+ leaves = root._get_children()
+ change_of_leaves = True
+ while change_of_leaves:
+ leaves_to_replace = list()
+ new_leaves = list()
+ for leaf in leaves:
+ if leaf._get_children() != list():
+ leaves_to_replace.append(leaf)
+ else:
+ new_leaves.append(leaf)
+ if leaves_to_replace != list():
+ for leaf in leaves_to_replace:
+ for el in leaf.children:
+ new_leaves.append(el)
+ leaves = new_leaves
+ else:
+ change_of_leaves = False
+ return leaves
+
+ def _print_tree(self):
+ root = self._get_root()
+ print(root)
+
+ parent = property(_get_parent, _set_parent)
+ children = property(_get_children, _set_children)
+ operator = property(_get_operator, _set_operator)
+ label = property(_get_label, _set_label)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/semantics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/semantics.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9bb502a60bcaa9ca77a7099613d3614007ed7a0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/semantics.py
@@ -0,0 +1,314 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import random
+
+from pm4py.objects.log.obj import EventLog, Trace, Event
+from pm4py.util import xes_constants as xes
+from pm4py.objects.process_tree import obj as pt_opt
+from pm4py.objects.process_tree import state as pt_st
+from pm4py.objects.process_tree.utils import generic as pt_util
+from pm4py.objects.process_tree.obj import ProcessTree
+
+import datetime
+from copy import deepcopy
+
+
+class GenerationTree(ProcessTree):
+ # extend the parent class to replace the __eq__ and __hash__ method
+ def __init__(self, tree):
+ i = 0
+ while i < len(tree.children):
+ tree.children[i] = GenerationTree(tree.children[i])
+ tree.children[i].parent = self
+ i = i + 1
+ ProcessTree.__init__(
+ self,
+ operator=tree.operator,
+ parent=tree.parent,
+ children=tree.children,
+ label=tree.label,
+ )
+
+ def __eq__(self, other):
+ # method that is different from default one (different taus must give
+ # different ID in log generation!!!!)
+ return id(self) == id(other)
+
+ def __hash__(self):
+ return id(self)
+
+
+def generate_log(pt0, no_traces=100):
+ """
+ Generate a log out of a process tree
+
+ Parameters
+ ------------
+ pt
+ Process tree
+ no_traces
+ Number of traces contained in the process tree
+
+ Returns
+ ------------
+ log
+ Trace log object
+ """
+ pt = deepcopy(pt0)
+ # different taus must give different ID in log generation!!!!
+ # so we cannot use the default process tree class
+ # we use this different one!
+ pt = GenerationTree(pt)
+ log = EventLog()
+
+ # assigns to each event an increased timestamp from 1970
+ curr_timestamp = 10000000
+
+ for i in range(no_traces):
+ ex_seq = execute(pt)
+ ex_seq_labels = pt_util.project_execution_sequence_to_labels(ex_seq)
+ trace = Trace()
+ trace.attributes[xes.DEFAULT_NAME_KEY] = str(i)
+ for label in ex_seq_labels:
+ event = Event()
+ event[xes.DEFAULT_NAME_KEY] = label
+ event[xes.DEFAULT_TIMESTAMP_KEY] = datetime.datetime.fromtimestamp(
+ curr_timestamp
+ )
+
+ trace.append(event)
+
+ curr_timestamp = curr_timestamp + 1
+
+ log.append(trace)
+
+ return log
+
+
+def execute(pt):
+ """
+ Execute the process tree, returning an execution sequence
+
+ Parameters
+ -----------
+ pt
+ Process tree
+
+ Returns
+ -----------
+ exec_sequence
+ Execution sequence on the process tree
+ """
+ enabled, open, closed = set(), set(), set()
+ enabled.add(pt)
+ # populate_closed(pt.children, closed)
+ execution_sequence = list()
+ while len(enabled) > 0:
+ execute_enabled(enabled, open, closed, execution_sequence)
+ return execution_sequence
+
+
+def populate_closed(nodes, closed):
+ """
+ Populate all closed nodes of a process tree
+
+ Parameters
+ ------------
+ nodes
+ Considered nodes of the process tree
+ closed
+ Closed nodes
+ """
+ closed |= set(nodes)
+ for node in nodes:
+ populate_closed(node.children, closed)
+
+
+def execute_enabled(enabled, open, closed, execution_sequence=None):
+ """
+ Execute an enabled node of the process tree
+
+ Parameters
+ -----------
+ enabled
+ Enabled nodes
+ open
+ Open nodes
+ closed
+ Closed nodes
+ execution_sequence
+ Execution sequence
+
+ Returns
+ -----------
+ execution_sequence
+ Execution sequence
+ """
+ execution_sequence = (
+ list() if execution_sequence is None else execution_sequence
+ )
+ vertex = random.sample(list(enabled), 1)[0]
+ enabled.remove(vertex)
+ open.add(vertex)
+ execution_sequence.append((vertex, pt_st.State.OPEN))
+ if len(vertex.children) > 0:
+ if vertex.operator is pt_opt.Operator.LOOP:
+ while len(vertex.children) < 3:
+ vertex.children.append(ProcessTree(parent=vertex))
+ if (
+ vertex.operator is pt_opt.Operator.SEQUENCE
+ or vertex.operator is pt_opt.Operator.LOOP
+ ):
+ c = vertex.children[0]
+ enabled.add(c)
+ execution_sequence.append((c, pt_st.State.ENABLED))
+ elif vertex.operator is pt_opt.Operator.PARALLEL:
+ enabled |= set(vertex.children)
+ for x in vertex.children:
+ if x in closed:
+ closed.remove(x)
+ map(
+ lambda c: execution_sequence.append((c, pt_st.State.ENABLED)),
+ vertex.children,
+ )
+ elif vertex.operator is pt_opt.Operator.XOR:
+ vc = vertex.children
+ c = vc[random.randint(0, len(vc) - 1)]
+ enabled.add(c)
+ execution_sequence.append((c, pt_st.State.ENABLED))
+ elif vertex.operator is pt_opt.Operator.OR:
+ some_children = [
+ c for c in vertex.children if random.random() < 0.5
+ ]
+ enabled |= set(some_children)
+ for x in some_children:
+ if x in closed:
+ closed.remove(x)
+ map(
+ lambda c: execution_sequence.append((c, pt_st.State.ENABLED)),
+ some_children,
+ )
+ elif vertex.operator is pt_opt.Operator.INTERLEAVING:
+ random.shuffle(vertex.children)
+ c = vertex.children[0]
+ enabled.add(c)
+ execution_sequence.append((c, pt_st.State.ENABLED))
+ else:
+ close(vertex, enabled, open, closed, execution_sequence)
+ return execution_sequence
+
+
+def close(vertex, enabled, open, closed, execution_sequence):
+ """
+ Close a given vertex of the process tree
+
+ Parameters
+ ------------
+ vertex
+ Vertex to be closed
+ enabled
+ Set of enabled nodes
+ open
+ Set of open nodes
+ closed
+ Set of closed nodes
+ execution_sequence
+ Execution sequence on the process tree
+ """
+ open.remove(vertex)
+ closed.add(vertex)
+ execution_sequence.append((vertex, pt_st.State.CLOSED))
+ process_closed(vertex, enabled, open, closed, execution_sequence)
+
+
+def process_closed(closed_node, enabled, open, closed, execution_sequence):
+ """
+ Process a closed node, deciding further operations
+
+ Parameters
+ -------------
+ closed_node
+ Node that shall be closed
+ enabled
+ Set of enabled nodes
+ open
+ Set of open nodes
+ closed
+ Set of closed nodes
+ execution_sequence
+ Execution sequence on the process tree
+ """
+ vertex = closed_node.parent
+ if vertex is not None and vertex in open:
+ if should_close(vertex, closed, closed_node):
+ close(vertex, enabled, open, closed, execution_sequence)
+ else:
+ enable = None
+ if (
+ vertex.operator is pt_opt.Operator.SEQUENCE
+ or vertex.operator is pt_opt.Operator.INTERLEAVING
+ ):
+ enable = vertex.children[
+ vertex.children.index(closed_node) + 1
+ ]
+ elif vertex.operator is pt_opt.Operator.LOOP:
+ enable = (
+ vertex.children[random.randint(1, 2)]
+ if vertex.children.index(closed_node) == 0
+ else vertex.children[0]
+ )
+ if enable is not None:
+ enabled.add(enable)
+ execution_sequence.append((enable, pt_st.State.ENABLED))
+
+
+def should_close(vertex, closed, child):
+ """
+ Decides if a parent vertex shall be closed based on
+ the processed child
+
+ Parameters
+ ------------
+ vertex
+ Vertex of the process tree
+ closed
+ Set of closed nodes
+ child
+ Processed child
+
+ Returns
+ ------------
+ boolean
+ Boolean value (the vertex shall be closed)
+ """
+ if vertex.children is None:
+ return True
+ elif (
+ vertex.operator is pt_opt.Operator.LOOP
+ or vertex.operator is pt_opt.Operator.SEQUENCE
+ or vertex.operator is pt_opt.Operator.INTERLEAVING
+ ):
+ return vertex.children.index(child) == len(vertex.children) - 1
+ elif vertex.operator is pt_opt.Operator.XOR:
+ return True
+ else:
+ return set(vertex.children) <= closed
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/state.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/state.py
new file mode 100644
index 0000000000000000000000000000000000000000..34ada1525a7e048150ddad14bde703a901c3e2bb
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/state.py
@@ -0,0 +1,31 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from enum import Enum
+
+
+class State(Enum):
+ # closed state
+ CLOSED = 1
+ # enabled state
+ ENABLED = 2
+ # open state
+ OPEN = 3
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/bottomup.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/bottomup.py
new file mode 100644
index 0000000000000000000000000000000000000000..88a28ca592b04f38844162bb0914fe08a8e75db7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/bottomup.py
@@ -0,0 +1,262 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import math
+
+from pm4py.objects.process_tree.obj import Operator
+
+
+def get_max_trace_length(tree, parameters=None):
+ """
+ Get the maximum length of a trace allowed by the process tree
+ (can be infty)
+
+ Parameters
+ ---------------
+ tree
+ Process tree
+ parameters
+ Possible parameters of the algorithm:
+ - "avoid_loops" => if True, avoid to visit loops
+
+ Returns
+ --------------
+ max_trace_length
+ The maximum length of a trace
+ """
+ if parameters is None:
+ parameters = {}
+
+ avoid_loops = parameters.get("avoid_loops", False)
+
+ bottomup = get_bottomup_nodes(tree, parameters=parameters)
+ max_length_dict = {}
+ for i in range(len(bottomup)):
+ get_max_length_dict(bottomup[i], max_length_dict, len(bottomup), avoid_loops)
+
+ return max_length_dict[tree]
+
+
+def get_min_trace_length(tree, parameters=None):
+ """
+ Get the minimum length of a trace allowed by the process tree
+
+ Parameters
+ ---------------
+ tree
+ Process tree
+ parameters
+ Possible parameters of the algorithm
+
+ Returns
+ --------------
+ min_trace_length
+ The minimum length of a trace
+ """
+ if parameters is None:
+ parameters = {}
+
+ bottomup = get_bottomup_nodes(tree, parameters=parameters)
+ min_length_dict = {}
+ for i in range(len(bottomup)):
+ get_min_length_dict(bottomup[i], min_length_dict)
+
+ return min_length_dict[tree]
+
+
+def get_max_rem_dict(tree, parameters=None):
+ """
+ Gets for each node of the tree the maximum number of activities
+ that are inserted to 'complete' a trace of the overall tree
+
+ Parameters
+ ----------------
+ tree
+ Process tree
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ---------------
+ max_rem_dict
+ Dictionary described in the docstring
+ """
+ if parameters is None:
+ parameters = {}
+
+ bottomup = get_bottomup_nodes(tree, parameters=parameters)
+ max_length_dict = {}
+ for i in range(len(bottomup)):
+ get_max_length_dict(bottomup[i], max_length_dict, len(bottomup))
+
+ max_rem_dict = {}
+ for i in range(len(bottomup)):
+ max_rem_dict[bottomup[i]] = (
+ max_length_dict[tree] - max_length_dict[bottomup[i]]
+ )
+
+ return max_rem_dict
+
+
+def get_min_rem_dict(tree, parameters=None):
+ """
+ Gets for each node of the tree the minimum number of activities
+ that are inserted to 'complete' a trace of the overall tree
+
+ Parameters
+ ----------------
+ tree
+ Process tree
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ ---------------
+ min_rem_dict
+ Dictionary described in the docstring
+ """
+ if parameters is None:
+ parameters = {}
+
+ bottomup = get_bottomup_nodes(tree, parameters=parameters)
+ min_length_dict = {}
+ for i in range(len(bottomup)):
+ get_min_length_dict(bottomup[i], min_length_dict)
+
+ min_rem_dict = {}
+ for i in range(len(bottomup)):
+ min_rem_dict[bottomup[i]] = (
+ min_length_dict[tree] - min_length_dict[bottomup[i]]
+ )
+
+ return min_rem_dict
+
+
+def get_max_length_dict(node, max_length_dict, num_nodes, avoid_loops=False):
+ """
+ Populates, given the nodes of a tree in a bottom-up order, the maximum length dictionary
+ (every trace generated from that point of the tree has at most length N)
+
+ Parameters
+ ---------------
+ node
+ Node
+ max_length_dict
+ Dictionary that is populated in-place
+ num_nodes
+ Number of nodes in the process tree
+ avoid_loops
+ Avoid to visit loops
+ """
+ if len(node.children) == 0:
+ if node.label is None:
+ max_length_dict[node] = 0
+ else:
+ max_length_dict[node] = 1
+ elif node.operator == Operator.XOR:
+ max_length_dict[node] = max(max_length_dict[x] for x in node.children)
+ elif (
+ node.operator == Operator.PARALLEL
+ or node.operator == Operator.SEQUENCE
+ or node.operator == Operator.OR
+ ):
+ max_length_dict[node] = sum(max_length_dict[x] for x in node.children)
+ elif node.operator == Operator.LOOP:
+ if avoid_loops:
+ children = list(node.children)
+ max_length_dict[node] = max_length_dict[children[0]]
+ else:
+ max_length_dict[node] = sum(max_length_dict[x] for x in node.children) + 2 ** (
+ 48 - math.ceil(math.log(num_nodes) / math.log(2)))
+
+
+def get_min_length_dict(node, min_length_dict):
+ """
+ Populates, given the nodes of a tree in a bottom-up order, the minimum length dictionary
+ (every trace generated from that point of the tree has at least length N)
+
+ Parameters
+ ---------------
+ node
+ Node
+ min_length_dict
+ Dictionary that is populated in-place
+ """
+ if len(node.children) == 0:
+ if node.label is None:
+ min_length_dict[node] = 0
+ else:
+ min_length_dict[node] = 1
+ elif node.operator == Operator.XOR:
+ min_length_dict[node] = min(min_length_dict[x] for x in node.children)
+ elif (
+ node.operator == Operator.PARALLEL
+ or node.operator == Operator.SEQUENCE
+ or node.operator == Operator.OR
+ ):
+ min_length_dict[node] = sum(min_length_dict[x] for x in node.children)
+ elif node.operator == Operator.LOOP:
+ min_length_dict[node] = min_length_dict[node.children[0]]
+
+
+def get_bottomup_nodes(tree, parameters=None):
+ """
+ Gets the nodes of a tree in a bottomup order (leafs come first, the master node comes after)
+
+ Parameters
+ --------------
+ tree
+ Process tree
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ bottomup_nodes
+ Nodes of the tree in a bottomup order
+ """
+ if parameters is None:
+ parameters = {}
+
+ to_visit = [tree]
+ all_nodes = set()
+ while len(to_visit) > 0:
+ n = to_visit.pop(0)
+ all_nodes.add(n)
+ for child in n.children:
+ to_visit.append(child)
+ # starts to visit the tree from the leafs
+ bottomup = [x for x in all_nodes if len(x.children) == 0]
+ # then add iteratively the parent
+ i = 0
+ while i < len(bottomup):
+ parent = bottomup[i].parent
+ if parent is not None and parent not in bottomup:
+ is_ok = True
+ for child in parent.children:
+ if child not in bottomup:
+ is_ok = False
+ break
+ if is_ok:
+ bottomup.append(parent)
+ i = i + 1
+
+ return bottomup
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/generic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/generic.py
new file mode 100644
index 0000000000000000000000000000000000000000..15bb9b3282d4efe784b74615515151de232d1455
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/generic.py
@@ -0,0 +1,546 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import copy
+import hashlib
+from typing import Optional, List, Dict, Tuple
+
+from pm4py.objects.process_tree import obj as pt
+from pm4py.objects.process_tree import obj as pt_op
+from pm4py.objects.process_tree import state as pt_st
+from pm4py.objects.process_tree.obj import ProcessTree
+from pm4py.util import constants
+
+
+def fold(tree):
+ """
+ This method reduces a process tree by merging nodes of the form N(N(a,b),c) into N(a,b,c), i.e., where
+ N = || or X. For example X(X(a,b),c) == X(a,b,c).
+ Furthermore, meaningless parts, e.g., internal nodes without children, or, operators with one child are removed
+ as well.
+
+ :param tree:
+ :return:
+ """
+ tree = copy.deepcopy(tree)
+ tree = _fold(tree)
+ root = tree
+ while root.parent is None and len(tree.children) == 1:
+ root = tree.children[0]
+ root.parent = None
+ tree.children.clear()
+ del tree
+ tree = root
+
+ tree_str = str(tree)
+ tree = reduce_tau_leafs(tree)
+ tau_leafs_red_tree_str = str(tree)
+
+ if len(tau_leafs_red_tree_str) != len(tree_str):
+ tree = fold(tree)
+ tree_str = str(tree)
+
+ tree2 = _fold(tree)
+ tree2_str = str(tree2)
+
+ if len(tree2_str) != len(tree_str):
+ tree = fold(tree2)
+
+ return tree
+
+
+def _fold(tree):
+ tree = reduce_tau_leafs(tree)
+
+ if len(tree.children) > 0:
+ tree.children = list(map(lambda c: _fold(c), tree.children))
+ tree.children = list(filter(lambda c: c is not None, tree.children))
+
+ if len(tree.children) == 0:
+ tree.parent = None
+ tree.children = None
+ return None
+ elif len(tree.children) == 1:
+ child = tree.children[0]
+ child.parent = tree.parent
+ tree.parent = None
+ tree.children = None
+ return child
+
+ if tree.operator in [pt_op.Operator.SEQUENCE, pt_op.Operator.PARALLEL]:
+ i = 0
+ while i < len(tree.children):
+ child = tree.children[i]
+ if child.operator is None and child.label is None:
+ del tree.children[i]
+ continue
+ i = i + 1
+ if len(tree.children) == 0:
+ tree.operator = None
+
+ if tree.operator in [
+ pt_op.Operator.SEQUENCE,
+ pt_op.Operator.XOR,
+ pt_op.Operator.PARALLEL,
+ ]:
+ chlds = [c for c in tree.children]
+ for c in chlds:
+ if c.operator == tree.operator:
+ i = tree.children.index(c)
+ tree.children[i:i] = c.children
+ for cc in c.children:
+ cc.parent = tree
+ tree.children.remove(c)
+ c.children.clear()
+ c.parent = None
+ return tree
+
+
+def reduce_tau_leafs(tree):
+ """
+ This method reduces tau leaves that are not meaningful. For example tree ->(a,\tau,b) is reduced to ->(a,b).
+ In some cases this results in constructs such as ->(a), i.e., a sequence with a single child. Such constructs
+ are not further reduced.
+
+ :param tree:
+ :return:
+ """
+ if len(tree.children) > 0:
+ for c in tree.children:
+ reduce_tau_leafs(c)
+ silents = 0
+ for c in tree.children:
+ if is_tau_leaf(c):
+ silents += 1
+ if silents > 0:
+ if len(tree.children) == silents:
+ # all children are tau, keep one (might be folded later)
+ if tree.operator in [
+ pt_op.Operator.SEQUENCE,
+ pt_op.Operator.PARALLEL,
+ pt_op.Operator.XOR,
+ pt_op.Operator.OR,
+ ]:
+ # remove all but one, later reductions might need the fact
+ # that skipping is possible
+ while silents > 1:
+ cc = tree.children
+ for c in cc:
+ if is_tau_leaf(c):
+ c.parent = None
+ tree.children.remove(c)
+ silents -= 1
+ break
+ elif (
+ tree.operator == pt_op.Operator.LOOP
+ and len(tree.children) == 2
+ ):
+ # remove all loop is redundant
+ cc = tree.children
+ for c in cc:
+ if is_tau_leaf(c):
+ c.parent = None
+ tree.children.remove(c)
+ else:
+ # at least one non-tau child
+ if tree.operator in [
+ pt_op.Operator.SEQUENCE,
+ pt_op.Operator.PARALLEL,
+ ]:
+ # remove all, they are redundant for these operators
+ cc = tree.children
+ for c in cc:
+ if is_tau_leaf(c):
+ c.parent = None
+ tree.children.remove(c)
+ elif tree.operator in [pt_op.Operator.XOR, pt_op.Operator.OR]:
+ # keep one, we should be able to skip
+ while silents > 1:
+ cc = tree.children
+ for c in cc:
+ if is_tau_leaf(c):
+ c.parent = None
+ tree.children.remove(c)
+ silents -= 1
+ break
+ return tree
+
+
+def is_tau_leaf(tree):
+ return is_leaf(tree) and tree.label is None
+
+
+def is_leaf(tree):
+ return (
+ tree.children is None or len(tree.children) == 0
+ ) and tree.operator is None
+
+
+def project_execution_sequence_to_leafs(execution_sequence):
+ """
+ Project an execution sequence to the set of leafs
+ of the tree.
+
+ Parameters
+ ------------
+ execution_sequence
+ Execution sequence on the process tree
+
+ Returns
+ ------------
+ list_leafs
+ Leafs nodes of the process tree
+ """
+ return list(
+ map(
+ lambda x: x[0],
+ filter(
+ lambda x: (
+ x[1] is pt_st.State.OPEN and len(x[0].children) == 0
+ ),
+ execution_sequence,
+ ),
+ )
+ )
+
+
+def project_execution_sequence_to_labels(execution_sequence):
+ """
+ Project an execution sequence to a set of labels
+
+ Parameters
+ ------------
+ execution_sequence
+ Execution sequence on the process tree
+
+ Returns
+ ------------
+ list_labels
+ List of labels contained in the process tree
+ """
+ return list(
+ map(
+ lambda x: x.label,
+ filter(
+ lambda x: x.label is not None,
+ project_execution_sequence_to_leafs(execution_sequence),
+ ),
+ )
+ )
+
+
+def parse(string_rep):
+ """
+ Parse a string provided by the user to a process tree
+ (initialization method)
+
+ Parameters
+ ------------
+ string_rep
+ String representation of the process tree
+
+ Returns
+ ------------
+ node
+ Process tree object
+ """
+ depth_cache = dict()
+ depth = 0
+ return parse_recursive(string_rep, depth_cache, depth)
+
+
+def parse_recursive(string_rep, depth_cache, depth):
+ """
+ Parse a string provided by the user to a process tree
+ (recursive method)
+
+ Parameters
+ ------------
+ string_rep
+ String representation of the process tree
+ depth_cache
+ Depth cache of the algorithm
+ depth
+ Current step depth
+
+ Returns
+ -----------
+ node
+ Process tree object
+ """
+ string_rep = string_rep.strip().replace("\r", "").replace("\n", " ")
+ node = None
+ operator = None
+ if string_rep.startswith(pt_op.Operator.LOOP.value):
+ operator = pt_op.Operator.LOOP
+ string_rep = string_rep[len(pt_op.Operator.LOOP.value):]
+ elif string_rep.startswith(pt_op.Operator.PARALLEL.value):
+ operator = pt_op.Operator.PARALLEL
+ string_rep = string_rep[len(pt_op.Operator.PARALLEL.value):]
+ elif string_rep.startswith(pt_op.Operator.XOR.value):
+ operator = pt_op.Operator.XOR
+ string_rep = string_rep[len(pt_op.Operator.XOR.value):]
+ elif string_rep.startswith(pt_op.Operator.OR.value):
+ operator = pt_op.Operator.OR
+ string_rep = string_rep[len(pt_op.Operator.OR.value):]
+ elif string_rep.startswith(pt_op.Operator.SEQUENCE.value):
+ operator = pt_op.Operator.SEQUENCE
+ string_rep = string_rep[len(pt_op.Operator.SEQUENCE.value):]
+ elif string_rep.startswith(pt_op.Operator.INTERLEAVING.value):
+ operator = pt_op.Operator.INTERLEAVING
+ string_rep = string_rep[len(pt_op.Operator.INTERLEAVING.value):]
+ if operator is not None:
+ parent = None if depth == 0 else depth_cache[depth - 1]
+ node = pt.ProcessTree(operator=operator, parent=parent)
+ depth_cache[depth] = node
+ if parent is not None:
+ parent.children.append(node)
+ depth += 1
+ string_rep = string_rep.strip()
+ assert string_rep[0] == "("
+ parse_recursive(string_rep[1:], depth_cache, depth)
+ else:
+ label = None
+ if string_rep.startswith("'"):
+ string_rep = string_rep[1:]
+ escape_ext = string_rep.find("'")
+ label = string_rep[0:escape_ext]
+ string_rep = string_rep[escape_ext + 1:]
+ else:
+ assert (
+ string_rep.startswith("tau")
+ or string_rep.startswith("τ")
+ or string_rep.startswith("\u03c4")
+ )
+ if string_rep.startswith("tau"):
+ string_rep = string_rep[len("tau"):]
+ elif string_rep.startswith("τ"):
+ string_rep = string_rep[len("τ"):]
+ elif string_rep.startswith("\u03c4"):
+ string_rep = string_rep[len("\u03c4"):]
+ parent = None if depth == 0 else depth_cache[depth - 1]
+ node = pt.ProcessTree(operator=operator, parent=parent, label=label)
+ if parent is not None:
+ parent.children.append(node)
+
+ while string_rep.strip().startswith(")"):
+ depth -= 1
+ string_rep = (string_rep.strip())[1:]
+ if len(string_rep.strip()) > 0:
+ parse_recursive((string_rep.strip())[1:], depth_cache, depth)
+ return node
+
+
+def tree_sort(tree):
+ """
+ Sort a tree in such way that the order of the nodes
+ in AND/XOR children is always the same.
+ This is a recursive function
+
+ Parameters
+ --------------
+ tree
+ Process tree
+ """
+ tree.labels_hash_sum = 0
+ for child in tree.children:
+ tree_sort(child)
+ tree.labels_hash_sum += child.labels_hash_sum
+ if tree.label is not None:
+ # this assures that among different executions, the same string gets
+ # always the same hash
+ this_hash = int(
+ hashlib.md5(
+ str(tree.label).encode(constants.DEFAULT_ENCODING)
+ ).hexdigest(),
+ 16,
+ )
+ tree.labels_hash_sum += this_hash
+ if (
+ tree.operator is pt_op.Operator.PARALLEL
+ or tree.operator is pt_op.Operator.XOR
+ ):
+ tree.children = sorted(tree.children, key=lambda x: x.labels_hash_sum)
+
+
+def structurally_language_equal(tree1, tree2):
+ """
+ this function checks if two given process trees are structurally equal, modulo, shuffling of children (if allowed),
+ i.e., in the parallel, or and xor operators, the order does not matter.
+
+ :param tree1:
+ :param tree2:
+ :return:
+ """
+ if tree1.label is not None:
+ return True if tree2.label == tree1.label else False
+ elif len(tree1.children) == 0:
+ return tree2.label is None and len(tree2.children) == 0
+ else:
+ if tree1.operator == tree2.operator:
+ if len(tree1.children) != len(tree2.children):
+ return False
+ if tree1.operator in [
+ pt_op.Operator.SEQUENCE,
+ pt_op.Operator.LOOP,
+ ]:
+ for i in range(len(tree1.children)):
+ if not structurally_language_equal(
+ tree1.children[i], tree2.children[i]
+ ):
+ return False
+ return True
+ elif tree1.operator in [
+ pt_op.Operator.PARALLEL,
+ pt_op.Operator.XOR,
+ pt_op.Operator.OR,
+ ]:
+ matches = list(range(len(tree1.children)))
+ for i in range(len(tree1.children)):
+ mm = [m for m in matches]
+ for j in mm:
+ if structurally_language_equal(
+ tree1.children[i], tree2.children[j]
+ ):
+ matches.remove(j)
+ break
+ return True if len(matches) == 0 else False
+ else:
+ return False
+
+
+def get_process_tree_height(pt: ProcessTree) -> int:
+ """
+ calculates from the given node the max height downwards
+ :param pt: process tree node
+ :return: height
+ """
+ if is_leaf(pt):
+ return 1
+ else:
+ return 1 + max([get_process_tree_height(x) for x in pt.children])
+
+
+def process_tree_to_binary_process_tree(tree: ProcessTree) -> ProcessTree:
+ if len(tree.children) > 2:
+ left_tree = tree.children[0]
+
+ right_tree_op = tree.operator
+ if tree.operator == pt_op.Operator.LOOP:
+ right_tree_op = pt_op.Operator.XOR
+
+ right_tree = ProcessTree(
+ operator=right_tree_op, parent=tree, children=tree.children[1:]
+ )
+ for child in right_tree.children:
+ child.parent = right_tree
+
+ tree.children = [left_tree, right_tree]
+
+ for child in tree.children:
+ process_tree_to_binary_process_tree(child)
+
+ return tree
+
+
+def common_ancestor(t1: ProcessTree, t2: ProcessTree) -> Optional[ProcessTree]:
+ parents = set()
+ parent = t1.parent
+ while parent is not None:
+ parents.add(parent)
+ parent = parent.parent
+ parent = t2.parent
+ while parent is not None:
+ if parent in parents:
+ return parent
+ parent = parent.parent
+ return None
+
+
+def get_ancestors_until(
+ t: ProcessTree, until: ProcessTree, include_until: bool = True
+) -> Optional[List[ProcessTree]]:
+ ancestors = list()
+ if t == until:
+ return ancestors
+ parent = t.parent
+ while parent != until:
+ ancestors.append(parent)
+ parent = parent.parent
+ if parent is None:
+ return None
+ if include_until:
+ ancestors.append(until)
+ return ancestors
+
+
+def get_leaves(t: ProcessTree, leaves=None):
+ leaves = leaves if leaves is not None else set()
+ if len(t.children) == 0:
+ leaves.add(t)
+ else:
+ for c in t.children:
+ leaves = get_leaves(c, leaves)
+ return leaves
+
+
+def get_leaves_as_tuples(t: ProcessTree, leaves=None):
+ leaves = leaves if leaves is not None else set()
+ if len(t.children) == 0:
+ leaves.add((id(t), t))
+ else:
+ for c in t.children:
+ leaves = get_leaves_as_tuples(c, leaves)
+ return leaves
+
+
+def is_operator(tree: ProcessTree, operator: pt_op.Operator) -> bool:
+ return (
+ tree is not None
+ and tree.operator is not None
+ and tree.operator == operator
+ )
+
+
+def is_any_operator_of(
+ tree: ProcessTree, operators: List[pt_op.Operator]
+) -> bool:
+ return (
+ tree is not None
+ and tree.operator is not None
+ and tree.operator in operators
+ )
+
+
+def is_in_state(
+ tree: ProcessTree,
+ target_state: ProcessTree.OperatorState,
+ tree_state: Dict[Tuple[int, ProcessTree], ProcessTree.OperatorState],
+) -> bool:
+ return (
+ tree is not None
+ and (id(tree), tree) in tree_state
+ and tree_state[(id(tree), tree)] == target_state
+ )
+
+
+def is_root(tree: ProcessTree) -> bool:
+ return tree.parent is None
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/label_replacing.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/label_replacing.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2cb955b63dccb2760a3458449c3cab3a3c7fedf
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/label_replacing.py
@@ -0,0 +1,55 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree.obj import ProcessTree
+from typing import Optional, Dict, Any
+from copy import deepcopy
+
+
+def apply(process_tree: ProcessTree, string_dictio: Dict[str, str], rec_depth=0, parameters: Optional[Dict[Any, Any]] = None) -> ProcessTree:
+ """
+ Replaces the labels in the given process tree using the provided dictionary.
+
+ Parameters
+ -----------------
+ process_tree
+ Process tree
+ string_dictio
+ Correspondence dictionary (old labels -> new labels)
+
+ Returns
+ -----------------
+ revised_tree
+ Revised process tree
+ """
+ if parameters is None:
+ parameters = {}
+
+ if rec_depth == 0:
+ process_tree = deepcopy(process_tree)
+
+ if process_tree.label is not None and process_tree.label in string_dictio:
+ process_tree.label = string_dictio[process_tree.label]
+
+ for child in process_tree.children:
+ apply(child, string_dictio, rec_depth=rec_depth+1, parameters=parameters)
+
+ return process_tree
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/regex.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/regex.py
new file mode 100644
index 0000000000000000000000000000000000000000..9306676fb8d6c33902aa4099ee1d8b07db02896d
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/regex.py
@@ -0,0 +1,108 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.process_tree import obj as pt_operator
+from pm4py.util.regex import SharedObj, get_new_char
+
+from pm4py.util import constants
+import warnings
+
+if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn("The regex package will be removed in a future release.")
+
+
+def pt_to_regex(tree, rec_depth=0, shared_obj=None, parameters=None):
+ """
+ Transforms a process tree to a regular expression
+
+ NB: The conversion is not yet working with trees containing an AND and/or an OR operator!
+
+ Parameters
+ ------------
+ tree
+ Process tree
+ parameters
+ Possible parameters of the algorithm
+ """
+ if parameters is None:
+ parameters = {}
+
+ if shared_obj is None:
+ shared_obj = SharedObj()
+
+ stru = ""
+
+ if tree.operator is not None:
+ contains_tau = (
+ len(
+ list(
+ child
+ for child in tree.children
+ if child.operator is None and child.label is None
+ )
+ )
+ > 0
+ )
+ children_rep = []
+ for child in tree.children:
+ rep, shared_obj = pt_to_regex(
+ child,
+ rec_depth=rec_depth + 1,
+ shared_obj=shared_obj,
+ parameters=parameters,
+ )
+ children_rep.append(rep)
+ if tree.operator == pt_operator.Operator.SEQUENCE:
+ children_rep = [x for x in children_rep if x is not None]
+ stru = "(" + "".join(children_rep) + ")"
+ elif tree.operator == pt_operator.Operator.XOR:
+ children_rep = [x for x in children_rep if x is not None]
+ stru = "(" + "|".join(children_rep) + ")"
+ if contains_tau:
+ stru = "(" + stru + "?)"
+ elif tree.operator == pt_operator.Operator.LOOP:
+ children_rep = [x for x in children_rep if x is not None]
+ if len(children_rep) == 1:
+ stru = "(" + children_rep[0] + ")+"
+ else:
+ stru = "(" + "".join(children_rep) + ")*" + children_rep[0]
+ elif tree.operator == pt_operator.Operator.PARALLEL:
+ raise Exception(
+ "the conversion is not yet working with trees containing an AND and/or an OR operator!"
+ )
+ elif tree.operator == pt_operator.Operator.OR:
+ raise Exception(
+ "the conversion is not yet working with trees containing an AND and/or an OR operator!"
+ )
+
+ elif tree.label is not None:
+ if tree.label not in shared_obj.mapping_dictio:
+ get_new_char(tree.label, shared_obj)
+ stru = shared_obj.mapping_dictio[tree.label]
+ elif tree.label is None:
+ return None, shared_obj
+
+ if rec_depth == 0:
+ ret = "^" + stru + "$", shared_obj.mapping_dictio
+ # print(ret)
+ return ret
+
+ return stru, shared_obj
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/struct_similarity.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/struct_similarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d7a2ac0e4116a5085d13a2e7a7faa62896c92ad
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/process_tree/utils/struct_similarity.py
@@ -0,0 +1,168 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import math
+from collections import Counter
+from typing import Tuple, List, Dict
+
+import numpy as np
+from pm4py.objects.process_tree import obj as pt
+
+###############################################################################
+# 1 ⸺ Feature extraction
+###############################################################################
+
+# Order is fixed so vector positions stay comparable
+FEATURES: List[str] = [
+ # global size / complexity
+ "n_nodes", # all nodes (operators + activities)
+ "n_edges", # = n_nodes - 1 in a tree
+ "depth", # max root-to-leaf distance
+ "avg_branching", # mean #children of operator nodes
+ # connector counts by type (splits in trees)
+ "parallel_splits",
+ "xor_splits",
+ "or_splits",
+ "loop_splits",
+ # joins and structuredness are implied by the tree
+ "joins", # = #splits (1-to-1 in block-structured models)
+ "structuredness" # always 1 for a process tree
+]
+
+
+def _traverse(node: pt.ProcessTree,
+ depth: int,
+ c: Counter,
+ depths: List[int]) -> None:
+ """DFS that collects counts and path depths."""
+ c["n_nodes"] += 1
+ depths.append(depth)
+ if node.operator is not None: # operator (AND / XOR / …)
+ name = node.operator.name.lower()
+ c[f"{name}_splits"] += 1
+ c["n_splits"] += 1
+ c["sum_branching"] += len(node.children)
+ for child in node.children:
+ _traverse(child, depth + 1, c, depths)
+
+
+def features_from_process_tree(tree: pt.ProcessTree) -> np.ndarray:
+ """
+ Parameters
+ ----------
+ tree : pm4py.objects.process_tree.obj.ProcessTree
+
+ Returns
+ -------
+ numpy.ndarray (len = 10)
+ Components in the order defined by FEATURES.
+ """
+ c = Counter()
+ depths: List[int] = []
+ _traverse(tree, 1, c, depths)
+
+ n_nodes = c["n_nodes"]
+ n_edges = n_nodes - 1 # property of trees
+ depth = max(depths)
+ n_ops = c["n_splits"]
+ avg_br = (c["sum_branching"] / n_ops) if n_ops else 0.0
+
+ vec = np.array([
+ n_nodes,
+ n_edges,
+ depth,
+ avg_br,
+ c["parallel_splits"],
+ c["xor_splits"],
+ c["or_splits"],
+ c["loop_splits"],
+ n_ops, # joins (one join per split in a tree)
+ 1.0 # structuredness
+ ], dtype=float)
+
+ return vec
+
+
+###############################################################################
+# 2 ⸺ Distance / similarity measure (Dijkman structural metric)
+###############################################################################
+
+def _normalise(v1: np.ndarray, v2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
+ """
+ Scales each dimension to [0,1] across the two vectors
+ (exactly what Dijkman et al. do to make features commensurable).
+ """
+ max_vals = np.maximum(v1, v2)
+ max_vals[max_vals == 0] = 1.0 # avoid division-by-zero
+ return v1 / max_vals, v2 / max_vals
+
+
+def structural_distance(tree1: pt.ProcessTree,
+ tree2: pt.ProcessTree,
+ weights: Dict[str, float] = None) -> float:
+ """
+ Euclidean distance of the normalised feature vectors.
+ `weights` lets you emphasise certain dimensions (defaults = 1).
+ """
+ v1 = features_from_process_tree(tree1)
+ v2 = features_from_process_tree(tree2)
+
+ v1n, v2n = _normalise(v1, v2)
+
+ if weights:
+ w = np.array([weights.get(f, 1.0) for f in FEATURES])
+ v1n *= w
+ v2n *= w
+
+ return float(np.linalg.norm(v1n - v2n))
+
+
+###############################################################################
+# 3 ⸺ Convenience similarity (1 – normalised distance)
+###############################################################################
+
+def structural_similarity(tree1: pt.ProcessTree,
+ tree2: pt.ProcessTree,
+ weights: Dict[str, float] = None) -> float:
+ """
+ Computes the structural similarity between two process trees, following an approach similar to:
+
+ Yan, Z., Dijkman, R., & Grefen, P. (2012). Fast business process similarity search.
+ Distributed and Parallel Databases, 30(2), 105–144.
+ (https://doi.org/10.1007/s10619-012-7089-z)
+
+ Parameters
+ ---------------
+ tree1
+ First process tree
+ tree2
+ Second process tree
+ weights
+ Weights of each feature
+
+ Returns
+ ---------------
+ sim_metric
+ Similarity metric
+ """
+ dist = structural_distance(tree1, tree2, weights)
+ # maximum possible distance after normalisation is √len(FEATURES)
+ return 1.0 - dist / math.sqrt(len(FEATURES))
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..59381f28ca426b7262ad24a542303cb229548908
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/__init__.py
@@ -0,0 +1,33 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.random_variables import (
+ constant0,
+ normal,
+ uniform,
+ exponential,
+ random_variable,
+ lognormal,
+ gamma,
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/basic_structure.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/basic_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..efe6d23045233c487c5cbc755d1f27c4ba486270
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/basic_structure.py
@@ -0,0 +1,162 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+class BasicStructureRandomVariable(object):
+ def __init__(self):
+ """
+ Constructor
+ """
+ self.priority = 0
+ self.weight = 0
+
+ def get_weight(self):
+ """
+ Getter of weight
+
+ Returns
+ ----------
+ weight : float
+ Weight of the transition
+ """
+ return self.weight
+
+ def set_weight(self, weight):
+ """
+ Setter of weight variable
+
+ Parameters
+ -----------
+ weight : float
+ Weight of the transition
+ """
+ self.weight = weight
+
+ def get_priority(self):
+ """
+ Getter of the priority
+
+ Returns
+ -----------
+ priority
+ Priority of the transition
+ """
+ return self.priority
+
+ def set_priority(self, priority):
+ """
+ Setter of the priority variable
+
+ Parameters
+ ------------
+ priority
+ Priority of the transition
+ """
+ self.priority = priority
+
+ def get_transition_type(self):
+ """
+ Get the type of transition associated to the current distribution
+
+ Returns
+ -----------
+ transition_type
+ String representing the type of the transition
+ """
+ return "TIMED"
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "NORMAL"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ return "UNDEFINED"
+
+ def __str__(self):
+ """
+ Returns a representation of the current object
+
+ Returns
+ ----------
+ repr
+ Representation of the current object
+ """
+ return (
+ self.get_distribution_type()
+ + " "
+ + self.get_distribution_parameters()
+ )
+
+ def __repr__(self):
+ """
+ Returns a representation of the current object
+
+ Returns
+ ----------
+ repr
+ Representation of the current object
+ """
+ return (
+ self.get_distribution_type()
+ + " "
+ + self.get_distribution_parameters()
+ )
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ return None
+
+ def get_values(self, no_values=400):
+ """
+ Get some random values following the distribution
+
+ Parameters
+ -----------
+ no_values
+ Number of values to return
+
+ Returns
+ ----------
+ values
+ Values extracted according to the probability distribution
+ """
+ return [self.get_value() for i in range(no_values)]
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/constant0/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/constant0/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3105853951a3c0ad6ecca4c8720496d52f4ed560
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/constant0/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.random_variables.constant0 import random_variable
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/constant0/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/constant0/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..459db0b296699ad7147116b172329572844c79d5
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/constant0/random_variable.py
@@ -0,0 +1,134 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import sys
+
+from pm4py.objects.random_variables.uniform.random_variable import Uniform
+
+
+class Constant0(Uniform):
+ """
+ Describes a constant0-equal-to-0 random variable
+ """
+
+ def __init__(self):
+ """
+ Constructor
+
+ Parameters
+ ----------
+ value
+ Constant value of the distribution
+ """
+ Uniform.__init__(self, loc=0, scale=0)
+ self.priority = 1
+
+ def read_from_string(self, distribution_parameters):
+ """
+ Initialize distribution parameters from string
+
+ Parameters
+ -----------
+ distribution_parameters
+ Current distribution parameters as exported on the Petri net
+ """
+ return None
+
+ def get_transition_type(self):
+ """
+ Get the type of transition associated to the current distribution
+
+ Returns
+ -----------
+ transition_type
+ String representing the type of the transition
+ """
+ return "IMMEDIATE"
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "IMMEDIATE"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ return "UNDEFINED"
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ return 0
+
+ def get_values(self, no_values=400):
+ """
+ Get some random values following the distribution
+
+ Parameters
+ -----------
+ no_values
+ Number of values to return
+
+ Returns
+ ----------
+ values
+ Values extracted according to the probability distribution
+ """
+ return [self.get_value() for i in range(no_values)]
+
+ def calculate_loglikelihood(self, values, tol=0.0001):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+ tol
+ Tolerance about float values (consider them 0?)
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ values_0 = [x for x in values if abs(x) < tol]
+ if len(values) == len(values_0):
+ return sys.float_info.max
+ return -sys.float_info.max
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/deterministic/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/deterministic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/deterministic/__init__.py
@@ -0,0 +1,21 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/deterministic/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/deterministic/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d6d2ca01b2de27395aadec2b41842d417d190d0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/deterministic/random_variable.py
@@ -0,0 +1,137 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import sys
+
+from pm4py.objects.random_variables.basic_structure import (
+ BasicStructureRandomVariable,
+)
+
+
+class Deterministic(BasicStructureRandomVariable):
+ """
+ Describes a deterministic random variable
+ """
+
+ def __init__(self, value=0):
+ """
+ Constructor
+
+ Parameters
+ ----------
+ value
+ Constant value of the distribution
+ """
+ BasicStructureRandomVariable.__init__(self)
+ self.value = value
+ self.priority = 1
+
+ def read_from_string(self, distribution_parameters):
+ """
+ Initialize distribution parameters from string
+
+ Parameters
+ -----------
+ distribution_parameters
+ Current distribution parameters as exported on the Petri net
+ """
+ self.value = distribution_parameters
+
+ def get_transition_type(self):
+ """
+ Get the type of transition associated to the current distribution
+
+ Returns
+ -----------
+ transition_type
+ String representing the type of the transition
+ """
+ return "DETERMINISTIC"
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "DETERMINISTIC"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ return str(self.value)
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ return self.value
+
+ def get_values(self, no_values=400):
+ """
+ Get some random values following the distribution
+
+ Parameters
+ -----------
+ no_values
+ Number of values to return
+
+ Returns
+ ----------
+ values
+ Values extracted according to the probability distribution
+ """
+ return [self.get_value() for i in range(no_values)]
+
+ def calculate_loglikelihood(self, values, tol=0.0001):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+ tol
+ Tolerance about float values (consider them 0?)
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ values_0 = [x for x in values if abs(x - self.value) < tol]
+ if len(values) == len(values_0):
+ return sys.float_info.max
+ return -sys.float_info.max
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/exponential/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/exponential/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..37d699e8b39f0945f30ab502ff5271e8d8a7718c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/exponential/__init__.py
@@ -0,0 +1,24 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.random_variables.exponential.random_variable import (
+ Exponential,
+)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/exponential/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/exponential/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a5ed69e0afa7452cc640ee1d79391facaeaecdd
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/exponential/random_variable.py
@@ -0,0 +1,136 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import sys
+
+import numpy as np
+
+from pm4py.objects.random_variables.basic_structure import (
+ BasicStructureRandomVariable,
+)
+
+
+class Exponential(BasicStructureRandomVariable):
+ """
+ Describes a normal variable
+ """
+
+ def __init__(self, loc=1, scale=1):
+ """
+ Constructor
+
+ Parameters
+ -----------
+ loc
+ Loc of the distribution (see docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html)
+ scale
+ Scale of the distribution
+ """
+ self.loc = loc
+ self.scale = scale
+ self.priority = 0
+ BasicStructureRandomVariable.__init__(self)
+
+ def read_from_string(self, distribution_parameters):
+ """
+ Initialize distribution parameters from string
+
+ Parameters
+ -----------
+ distribution_parameters
+ Current distribution parameters as exported on the Petri net
+ """
+ self.loc = 0
+ self.scale = 1.0 / float(distribution_parameters)
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "EXPONENTIAL"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ if self.scale > 0:
+ return str(1.0 / float(self.scale))
+ return "UNDEFINED"
+
+ def calculate_loglikelihood(self, values):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ from scipy.stats import expon
+
+ if len(values) > 1:
+ somma = 0
+ for value in values:
+ somma = somma + np.log(expon.pdf(value, self.loc, self.scale))
+ return somma
+ return -sys.float_info.max
+
+ def calculate_parameters(self, values):
+ """
+ Calculate parameters of the current distribution
+
+ Parameters
+ -----------
+ values
+ Empirical values to work on
+ """
+ from scipy.stats import expon
+
+ if len(values) > 1:
+ self.loc, self.scale = expon.fit(values, floc=0)
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ from scipy.stats import expon
+
+ return expon.rvs(self.loc, self.scale)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/gamma/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/gamma/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7ab2ff6a7ead0500b9f23953fea9a51ae01c9af
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/gamma/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.random_variables.gamma import random_variable
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/gamma/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/gamma/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f5437d8913e1a295d4abfdea5c9e25bf7e38da3
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/gamma/random_variable.py
@@ -0,0 +1,138 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import sys
+
+import numpy as np
+
+from pm4py.objects.random_variables.basic_structure import (
+ BasicStructureRandomVariable,
+)
+from pm4py.util import constants
+import warnings
+
+
+class Gamma(BasicStructureRandomVariable):
+ """
+ Describes a normal variable
+ """
+
+ def __init__(self, a=1, loc=0, scale=1):
+ """
+ Constructor
+ """
+ self.a = a
+ self.loc = loc
+ self.scale = scale
+ BasicStructureRandomVariable.__init__(self)
+
+ def read_from_string(self, distribution_parameters):
+ """
+ Initialize distribution parameters from string
+
+ Parameters
+ -----------
+ distribution_parameters
+ Current distribution parameters as exported on the Petri net
+ """
+ self.a = float(distribution_parameters.split(";")[0])
+ self.loc = float(distribution_parameters.split(";")[1])
+ self.scale = float(distribution_parameters.split(";")[2])
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "GAMMA"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ return str(self.a) + ";" + str(self.loc) + ";" + str(self.scale)
+
+ def calculate_loglikelihood(self, values):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ from scipy.stats import gamma
+
+ if len(values) > 1:
+ somma = 0
+ for value in values:
+ somma = somma + np.log(
+ gamma.pdf(value, self.a, self.loc, self.scale)
+ )
+ return somma
+ return -sys.float_info.max
+
+ def calculate_parameters(self, values):
+ """
+ Calculate parameters of the current distribution
+
+ Parameters
+ -----------
+ values
+ Empirical values to work on
+ """
+ from scipy.stats import gamma
+
+ if len(values) > 1:
+ try:
+ self.a, self.loc, self.scale = gamma.fit(values)
+ except BaseException:
+ if constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "Gamma fitting: Optimization converged to parameters that are outside the range allowed by the distribution"
+ )
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ from scipy.stats import gamma
+
+ return gamma.rvs(self.a, self.loc, self.scale)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/lognormal/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/lognormal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..522eeb7a140c595ca77778a5b31bbe273e62e38f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/lognormal/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.random_variables.lognormal import random_variable
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/lognormal/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/lognormal/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..8aa18d7dee0322237b7d6fb66671b77f3c8586b0
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/lognormal/random_variable.py
@@ -0,0 +1,130 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import sys
+
+import numpy as np
+
+from pm4py.objects.random_variables.basic_structure import (
+ BasicStructureRandomVariable,
+)
+
+
+class LogNormal(BasicStructureRandomVariable):
+ """
+ Describes a normal variable
+ """
+
+ def __init__(self, s=1, loc=0, scale=1):
+ """
+ Constructor
+ """
+ self.s = s
+ self.loc = loc
+ self.scale = scale
+ BasicStructureRandomVariable.__init__(self)
+
+ def read_from_string(self, distribution_parameters):
+ """
+ Initialize distribution parameters from string
+
+ Parameters
+ -----------
+ distribution_parameters
+ Current distribution parameters as exported on the Petri net
+ """
+ self.s = float(distribution_parameters.split(";")[0])
+ self.loc = float(distribution_parameters.split(";")[1])
+ self.scale = float(distribution_parameters.split(";")[2])
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "LOGNORMAL"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ return str(self.s) + ";" + str(self.loc) + ";" + str(self.scale)
+
+ def calculate_loglikelihood(self, values):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ from scipy.stats import lognorm
+
+ if len(values) > 1:
+ somma = 0
+ for value in values:
+ somma = somma + np.log(
+ lognorm.pdf(value, self.s, self.loc, self.scale)
+ )
+ return somma
+ return -sys.float_info.max
+
+ def calculate_parameters(self, values):
+ """
+ Calculate parameters of the current distribution
+
+ Parameters
+ -----------
+ values
+ Empirical values to work on
+ """
+ from scipy.stats import lognorm
+
+ if len(values) > 1:
+ self.s, self.loc, self.scale = lognorm.fit(values)
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ from scipy.stats import lognorm
+
+ return lognorm.rvs(self.s, self.loc, self.scale)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/normal/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/normal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..15dc94497ba544b6dfff05b485591678427ca2f2
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/normal/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.random_variables.normal import random_variable
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/normal/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/normal/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b296fcbf54fcb843c957db4364ad1765cf53c8f
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/normal/random_variable.py
@@ -0,0 +1,134 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import sys
+
+import numpy as np
+
+from pm4py.objects.random_variables.basic_structure import (
+ BasicStructureRandomVariable,
+)
+
+
+class Normal(BasicStructureRandomVariable):
+ """
+ Describes a normal variable
+ """
+
+ def __init__(self, mu=0, sigma=1):
+ """
+ Constructor
+
+ Parameters
+ -----------
+ mu
+ Average of the normal distribution
+ sigma
+ Standard deviation of the normal distribution
+ """
+ self.mu = mu
+ self.sigma = sigma
+ self.priority = 0
+ BasicStructureRandomVariable.__init__(self)
+
+ def read_from_string(self, distribution_parameters):
+ """
+ Initialize distribution parameters from string
+
+ Parameters
+ -----------
+ distribution_parameters
+ Current distribution parameters as exported on the Petri net
+ """
+ self.mu = distribution_parameters.split(";")[0]
+ self.sigma = distribution_parameters.split(";")[1]
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "NORMAL"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ return str(self.mu) + ";" + str(self.sigma)
+
+ def calculate_loglikelihood(self, values):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ from scipy.stats import norm
+
+ if len(values) > 1:
+ somma = 0
+ for value in values:
+ somma = somma + np.log(norm.pdf(value, self.mu, self.sigma))
+ return somma
+ return -sys.float_info.max
+
+ def calculate_parameters(self, values):
+ """
+ Calculate parameters of the current distribution
+
+ Parameters
+ -----------
+ values
+ Empirical values to work on
+ """
+ from scipy.stats import norm
+
+ if len(values) > 1:
+ self.mu, self.sigma = norm.fit(values)
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ from scipy.stats import norm
+
+ return norm.rvs(self.mu, self.sigma)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..977532c0e974bf802f67dbdc61e67c97914222ef
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/random_variable.py
@@ -0,0 +1,310 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import numpy as np
+
+from pm4py.objects.random_variables.constant0.random_variable import Constant0
+from pm4py.objects.random_variables.deterministic.random_variable import (
+ Deterministic,
+)
+from pm4py.objects.random_variables.exponential.random_variable import (
+ Exponential,
+)
+from pm4py.objects.random_variables.normal.random_variable import Normal
+from pm4py.objects.random_variables.uniform.random_variable import Uniform
+from pm4py.objects.random_variables.lognormal.random_variable import LogNormal
+from pm4py.objects.random_variables.gamma.random_variable import Gamma
+
+
+class RandomVariable(object):
+ def __init__(self):
+ self.random_variable = None
+
+ def read_from_string(self, distribution_type, distribution_parameters):
+ """
+ Read the random variable from string
+
+ Parameters
+ -----------
+ distribution_type
+ Distribution type
+ distribution_parameters
+ Distribution parameters splitted by ;
+ """
+ if distribution_type == "NORMAL":
+ self.random_variable = Normal()
+ self.random_variable.read_from_string(distribution_parameters)
+ elif distribution_type == "UNIFORM":
+ self.random_variable = Uniform()
+ self.random_variable.read_from_string(distribution_parameters)
+ elif distribution_type == "EXPONENTIAL":
+ self.random_variable = Exponential()
+ self.random_variable.read_from_string(distribution_parameters)
+ elif distribution_type == "LOGNORMAL":
+ self.random_variable = LogNormal()
+ self.random_variable.read_from_string(distribution_parameters)
+ elif distribution_type == "GAMMA":
+ self.random_variable = Gamma()
+ self.random_variable.read_from_string(distribution_parameters)
+ elif distribution_type == "DETERMINISTIC":
+ self.random_variable = Deterministic()
+ self.random_variable.read_from_string(distribution_parameters)
+ elif distribution_type == "IMMEDIATE":
+ self.random_variable = Constant0()
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ if self.random_variable is not None:
+ return self.random_variable.get_distribution_type()
+
+ def get_transition_type(self):
+ """
+ Get the type of transition associated to the current distribution
+
+ Returns
+ -----------
+ transition_type
+ String representing the type of the transition
+ """
+ if self.random_variable is not None:
+ return self.random_variable.get_transition_type()
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ if self.random_variable is not None:
+ return self.random_variable.get_distribution_parameters()
+
+ def calculate_loglikelihood(self, values):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ if self.random_variable is not None:
+ return self.random_variable.calculate_loglikelihood(values)
+
+ def calculate_parameters(
+ self, values, parameters=None, force_distribution=None
+ ):
+ """
+ Calculate parameters of the current distribution
+
+ Parameters
+ -----------
+ values
+ Empirical values to work on
+ parameters
+ Possible parameters of the algorithm
+ force_distribution
+ If provided, distribution to force usage (e.g. EXPONENTIAL)
+
+ """
+
+ if parameters is None:
+ parameters = {}
+
+ debug_mode = parameters["debug"] if "debug" in parameters else False
+
+ if self.random_variable is not None:
+ self.random_variable.calculate_parameters(values)
+ else:
+ norm = Normal()
+ unif = Uniform()
+ expon = Exponential()
+ constant = Constant0()
+ lognormal = LogNormal()
+ gamma = Gamma()
+
+ if (
+ not force_distribution
+ or not force_distribution == "EXPONENTIAL"
+ ):
+ likelihoods = list()
+ likelihoods.append(
+ [constant, constant.calculate_loglikelihood(values)]
+ )
+ if (
+ force_distribution == "NORMAL"
+ or force_distribution is None
+ ):
+ norm.calculate_parameters(values)
+ likelihoods.append(
+ [norm, norm.calculate_loglikelihood(values)]
+ )
+ if (
+ force_distribution == "UNIFORM"
+ or force_distribution is None
+ ):
+ unif.calculate_parameters(values)
+ likelihoods.append(
+ [unif, unif.calculate_loglikelihood(values)]
+ )
+ if (
+ force_distribution == "EXPONENTIAL"
+ or force_distribution is None
+ ):
+ expon.calculate_parameters(values)
+ likelihoods.append(
+ [expon, expon.calculate_loglikelihood(values)]
+ )
+ likelihoods = [x for x in likelihoods if str(x[1]) != "nan"]
+ likelihoods = sorted(
+ likelihoods, key=lambda x: x[1], reverse=True
+ )
+
+ if debug_mode:
+ print("likelihoods = ", likelihoods)
+
+ self.random_variable = likelihoods[0][0]
+ else:
+ avg_values = np.average(values)
+ if values and avg_values > 0.00000:
+ expon.scale = avg_values
+ self.random_variable = expon
+ else:
+ self.random_variable = constant
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ if self.random_variable is not None:
+ return self.random_variable.get_value()
+
+ def get_values(self, no_values=400):
+ """
+ Get some random values following the distribution
+
+ Parameters
+ -----------
+ no_values
+ Number of values to return
+
+ Returns
+ ----------
+ values
+ Values extracted according to the probability distribution
+ """
+ if self.random_variable is not None:
+ return self.random_variable.get_values(no_values=no_values)
+
+ def get_weight(self):
+ """
+ Getter of weight
+
+ Returns
+ ----------
+ weight : float
+ Weight of the transition
+ """
+ if self.random_variable is not None:
+ return self.random_variable.get_weight()
+
+ def set_weight(self, weight):
+ """
+ Setter of the weight
+
+ Parameters
+ -----------
+ weight : float
+ Weight of the transition
+ """
+ if self.random_variable is not None:
+ self.random_variable.set_weight(weight)
+
+ def get_priority(self):
+ """
+ Getter of the priority
+
+ Returns
+ -----------
+ priority
+ Priority of the transition
+ """
+ if self.random_variable is not None:
+ return self.random_variable.get_priority()
+
+ def set_priority(self, priority):
+ """
+ Setter of the priority variable
+
+ Parameters
+ ------------
+ priority
+ Priority of the transition
+ """
+ if self.random_variable is not None:
+ self.random_variable.set_priority(priority)
+
+ def __str__(self):
+ """
+ Returns a representation of the current object
+
+ Returns
+ ----------
+ repr
+ Representation of the current object
+ """
+ if self.random_variable is not None:
+ return str(self.random_variable)
+ else:
+ return "UNINITIALIZED"
+
+ def __repr__(self):
+ """
+ Returns a representation of the current object
+
+ Returns
+ ----------
+ repr
+ Representation of the current object
+ """
+ if self.random_variable is not None:
+ return repr(self.random_variable)
+ else:
+ return "UNINITIALIZED"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/uniform/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/uniform/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd33b5064c4282ca96a153c27ffa87e50cd444dd
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/uniform/__init__.py
@@ -0,0 +1,22 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.random_variables.uniform import random_variable
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/uniform/random_variable.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/uniform/random_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..1789d49693632e8282ab2f54a9c8b6e4f2163139
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/random_variables/uniform/random_variable.py
@@ -0,0 +1,136 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+import sys
+
+import numpy as np
+
+from pm4py.objects.random_variables.basic_structure import (
+ BasicStructureRandomVariable,
+)
+
+
+class Uniform(BasicStructureRandomVariable):
+ """
+ Describes an uniform variable
+ """
+
+ def __init__(self, loc=0, scale=1):
+ """
+ Constructor
+
+ Parameters
+ -----------
+ loc
+ Start of the interval
+ scale
+ Scale of the interval
+ """
+ self.loc = loc
+ self.scale = scale
+ self.priority = 0
+ BasicStructureRandomVariable.__init__(self)
+
+ def read_from_string(self, distribution_parameters):
+ """
+ Initialize distribution parameters from string
+
+ Parameters
+ -----------
+ distribution_parameters
+ Current distribution parameters as exported on the Petri net
+ """
+ self.loc = distribution_parameters.split(";")[0]
+ self.scale = distribution_parameters.split(";")[1]
+
+ def get_distribution_type(self):
+ """
+ Get current distribution type
+
+ Returns
+ -----------
+ distribution_type
+ String representing the distribution type
+ """
+ return "UNIFORM"
+
+ def get_distribution_parameters(self):
+ """
+ Get a string representing distribution parameters
+
+ Returns
+ -----------
+ distribution_parameters
+ String representing distribution parameters
+ """
+ return str(self.loc) + ";" + str(self.scale)
+
+ def calculate_loglikelihood(self, values):
+ """
+ Calculate log likelihood
+
+ Parameters
+ ------------
+ values
+ Empirical values to work on
+
+ Returns
+ ------------
+ likelihood
+ Log likelihood that the values follows the distribution
+ """
+ from scipy.stats import uniform
+
+ if len(values) > 0:
+ somma = 0
+ for value in values:
+ somma = somma + np.log(
+ uniform.pdf(value, self.loc, self.scale)
+ )
+ return somma
+ return -sys.float_info.max
+
+ def calculate_parameters(self, values):
+ """
+ Calculate parameters of the current distribution
+
+ Parameters
+ -----------
+ values
+ Empirical values to work on
+ """
+ from scipy.stats import uniform
+
+ if len(values) > 0:
+ self.loc, self.scale = uniform.fit(values)
+
+ def get_value(self):
+ """
+ Get a random value following the distribution
+
+ Returns
+ -----------
+ value
+ Value obtained following the distribution
+ """
+ from scipy.stats import uniform
+
+ return uniform.rvs(self.loc, self.scale)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8bc880f26129e7152aaf161e3187464ef5e086c
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/__init__.py
@@ -0,0 +1,32 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.stochastic_petri import tangible_reachability, utils
+
+ import warnings
+
+ if pm4_constants.SHOW_INTERNAL_WARNINGS:
+ warnings.warn(
+ "The stochastic_petri package will be removed in a future release."
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/ctmc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/ctmc.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbfc8f3964cd6dd9695bbbb6802d8e25d8c91bdf
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/ctmc.py
@@ -0,0 +1,434 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from collections import Counter
+
+import numpy as np
+
+from pm4py.objects.petri_net.utils.reachability_graph import (
+ construct_reachability_graph,
+)
+from pm4py.objects.stochastic_petri import tangible_reachability
+from pm4py.objects.conversion.dfg import converter as dfg_converter
+from pm4py.objects.random_variables import exponential, random_variable
+
+
+def get_corr_hex(num):
+ """
+ Gets correspondence between a number
+ and an hexadecimal string
+
+ Parameters
+ -------------
+ num
+ Number
+
+ Returns
+ -------------
+ hex_string
+ Hexadecimal string
+ """
+ if num < 10:
+ return str(int(num))
+ elif num < 11:
+ return "A"
+ elif num < 12:
+ return "B"
+ elif num < 13:
+ return "C"
+ elif num < 14:
+ return "D"
+ elif num < 15:
+ return "E"
+ elif num < 16:
+ return "F"
+
+
+def get_color_from_probabilities(prob_dictionary):
+ """
+ Returns colors from a dictionary of probabilities
+
+ Parameters
+ -------------
+ prob_dictionary
+ Dictionary of probabilities
+
+ Returns
+ -------------
+ color_dictionary
+ Dictionary of colors
+ """
+ color_dictionary = {}
+
+ for state in prob_dictionary:
+ value = prob_dictionary[state]
+ whiteness = int(255.0 * (1.0 - value))
+ w1 = whiteness / 16
+ w2 = whiteness % 16
+ c1 = get_corr_hex(w1)
+ c2 = get_corr_hex(w2)
+ color_dictionary[state] = "#FF" + c1 + c2 + c1 + c2
+
+ return color_dictionary
+
+
+def get_tangible_reachability_and_q_matrix_from_dfg_performance(
+ dfg_performance, invisible_firing_rate=1000.0, parameters=None
+):
+ """
+ Get the tangible reachability graph and the Q matrix from the performance DFG
+
+ Parameters
+ -------------
+ dfg_performance
+ Performance DFG
+ invisible_firing_rate
+ Firing rate for invisible transitions
+ parameters
+ Parameters
+
+ Returns
+ -------------
+ reachab_graph
+ Reachability graph
+ tangible_reach_graph
+ Tangible reachability graph
+ stochastic_info
+ Stochastic information
+ q_matrix
+ Q-matrix from the tangible reachability graph
+ """
+ if parameters is None:
+ parameters = {}
+ net, im, fm = dfg_converter.apply(dfg_performance, parameters=parameters)
+ stochastic_map = {}
+ for tr in net.transitions:
+ if tr.label is None:
+ rv = random_variable.RandomVariable()
+ exp = exponential.Exponential()
+ exp.scale = 1 / invisible_firing_rate
+ rv.random_variable = exp
+ stochastic_map[tr] = rv
+ else:
+ input_arc = list(tr.in_arcs)[0]
+ output_arc = list(tr.out_arcs)[0]
+ rv = random_variable.RandomVariable()
+ el = (input_arc.source.name, output_arc.target.name)
+ scale = 0
+ if el in dfg_performance:
+ scale = dfg_performance[el]
+ if scale == 0:
+ scale = 1 / invisible_firing_rate
+ exp = exponential.Exponential()
+ exp.scale = scale
+ rv.random_variable = exp
+ stochastic_map[tr] = rv
+ tang_reach_graph = construct_reachability_graph(
+ net, im, use_trans_name=True
+ )
+ q_matrix = get_q_matrix_from_tangible_exponential(
+ tang_reach_graph, stochastic_map
+ )
+ return tang_reach_graph, tang_reach_graph, stochastic_map, q_matrix
+
+
+def get_tangible_reachability_and_q_matrix_from_log_net(
+ log, net, im, fm, parameters=None
+):
+ """
+ Gets the tangible reachability graph from a log and an accepting Petri net
+
+ Parameters
+ ---------------
+ log
+ Event log
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+
+ Returns
+ ------------
+ reachab_graph
+ Reachability graph
+ tangible_reach_graph
+ Tangible reachability graph
+ stochastic_info
+ Stochastic information
+ q_matrix
+ Q-matrix from the tangible reachability graph
+ """
+ if parameters is None:
+ parameters = {}
+ reachability_graph, tangible_reachability_graph, stochastic_info = (
+ tangible_reachability.get_tangible_reachability_from_log_net_im_fm(
+ log, net, im, fm, parameters=parameters
+ )
+ )
+ # gets the Q matrix assuming exponential distributions
+ q_matrix = get_q_matrix_from_tangible_exponential(
+ tangible_reachability_graph, stochastic_info
+ )
+ return (
+ reachability_graph,
+ tangible_reachability_graph,
+ stochastic_info,
+ q_matrix,
+ )
+
+
+def transient_analysis_from_petri_net_and_smap(
+ net, im, s_map, delay, parameters=None
+):
+ """
+ Gets the transient analysis from a Petri net, a stochastic map and a delay
+
+ Parameters
+ -------------
+ log
+ Event log
+ delay
+ Time delay
+ parameters
+ Parameters of the algorithm
+
+ Returns
+ -------------
+ transient_result
+ Transient analysis result
+ """
+ if parameters is None:
+ parameters = {}
+ # gets the reachability graph from the Petri net
+ reachab_graph = construct_reachability_graph(net, im)
+ states_reachable_from_start = set()
+ for trans in reachab_graph.transitions:
+ if str(trans.from_state) == "start1":
+ states_reachable_from_start.add(trans.to_state)
+ # get the tangible reachability graph from the reachability graph and the
+ # stochastic map
+ tang_reach_graph = (
+ tangible_reachability.get_tangible_reachability_from_reachability(
+ reachab_graph, s_map
+ )
+ )
+ # gets the Q matrix assuming exponential distributions
+ q_matrix = get_q_matrix_from_tangible_exponential(tang_reach_graph, s_map)
+ states = sorted(list(tang_reach_graph.states), key=lambda x: x.name)
+ states_vector = np.zeros((1, len(states)))
+
+ for state in states_reachable_from_start:
+ states_vector[0, states.index(state)] = 1.0 / len(
+ states_reachable_from_start
+ )
+
+ probabilities = (
+ transient_analysis_from_tangible_q_matrix_and_states_vector(
+ tang_reach_graph, q_matrix, states_vector, delay
+ )
+ )
+
+ color_dictionary = get_color_from_probabilities(probabilities)
+
+ return tang_reach_graph, probabilities, color_dictionary
+
+
+def get_q_matrix_from_tangible_exponential(
+ tangible_reach_graph, stochastic_info
+):
+ """
+ Gets Q matrix from tangible reachability graph and stochastic map where the
+ distribution type has been forced to be exponential
+
+ Parameters
+ -----------
+ tangible_reach_graph
+ Tangible reachability graph
+ stochastic_info
+ Stochastic map for each transition
+
+ Returns
+ -----------
+ q_matrix
+ Q-matrix from the tangible reachability graph
+ """
+ stochastic_info_name = {}
+ for s in stochastic_info:
+ stochastic_info_name[s.name] = stochastic_info[s]
+
+ states = sorted(list(tangible_reach_graph.states), key=lambda x: x.name)
+ no_states = len(states)
+ q_matrix = np.zeros((no_states, no_states))
+
+ for i in range(no_states):
+ sum_lambda = 0.0
+ for trans in states[i].outgoing:
+ target_state = trans.to_state
+ target_state_index = states.index(target_state)
+ if not target_state_index == i:
+ sinfo = stochastic_info_name[trans.name]
+ lambda_value = 1.0 / float(sinfo.random_variable.scale)
+ sum_lambda = sum_lambda + lambda_value
+ q_matrix[i, target_state_index] = (
+ q_matrix[i, target_state_index] + lambda_value
+ )
+ q_matrix[i, i] = -sum_lambda
+
+ return q_matrix
+
+
+def transient_analysis_from_tangible_q_matrix_and_single_state(
+ tangible_reach_graph, q_matrix, source_state, time_diff
+):
+ """
+ Do transient analysis from tangible reachability graph, Q matrix and a single state to start from
+
+ Parameters
+ -----------
+ tangible_reach_graph
+ Tangible reachability graph
+ q_matrix
+ Q matrix
+ source_state
+ Source state to consider
+ time_diff
+ Time interval we want to investigate
+
+ Returns
+ -----------
+ transient_result
+ Transient analysis result
+ """
+ states = sorted(list(tangible_reach_graph.states), key=lambda x: x.name)
+ state_index = states.index(source_state)
+
+ states_vector = np.zeros((1, len(states)))
+ states_vector[0, state_index] = 1
+
+ return transient_analysis_from_tangible_q_matrix_and_states_vector(
+ tangible_reach_graph, q_matrix, states_vector, time_diff
+ )
+
+
+def transient_analysis_from_tangible_q_matrix_and_states_vector(
+ tangible_reach_graph, q_matrix, states_vector, time_diff
+):
+ """
+ Do transient analysis from tangible reachability graph, Q matrix and a vector of probability of states
+
+ Parameters
+ ------------
+ tangible_reach_graph
+ Tangible reachability graph
+ q_matrix
+ Q matrix
+ states_vector
+ Vector of states probabilities to start from
+ time_diff
+ Time interval we want to investigate
+
+ Returns
+ -----------
+ transient_result
+ Transient analysis result
+ """
+ from scipy.linalg import expm
+
+ transient_result = Counter()
+ states = sorted(list(tangible_reach_graph.states), key=lambda x: x.name)
+
+ ht_matrix = expm(q_matrix * time_diff)
+
+ res = np.matmul(states_vector, ht_matrix)
+ # normalize to 1 the vector of probabilities
+ res = res / np.sum(res)
+
+ for i in range(len(states)):
+ transient_result[states[i]] = res[0, i]
+
+ return transient_result
+
+
+def nullspace(a_matrix, atol=1e-13, rtol=0):
+ """Compute an approximate basis for the nullspace of A.
+
+ The algorithm used by this function is based on the singular value
+ decomposition of `A`.
+
+ Parameters
+ ----------
+ a_matrix : ndarray
+ A should be at most 2-D. A 1-D array with length k will be treated
+ as a 2-D with shape (1, k)
+ atol : float
+ The absolute tolerance for a zero singular value. Singular values
+ smaller than `atol` are considered to be zero.
+ rtol : float
+ The relative tolerance. Singular values less than rtol*smax are
+ considered to be zero, where smax is the largest singular value.
+
+ If both `atol` and `rtol` are positive, the combined tolerance is the
+ maximum of the two; that is::
+ tol = max(atol, rtol * smax)
+ Singular values smaller than `tol` are considered to be zero.
+
+ Returns
+ ------------
+ ns : ndarray
+ If `A` is an array with shape (m, k), then `ns` will be an array
+ with shape (k, n), where n is the estimated dimension of the
+ nullspace of `A`. The columns of `ns` are a basis for the
+ nullspace; each element in numpy.dot(A, ns) will be approximately
+ zero.
+ """
+ from numpy.linalg import svd
+
+ a_matrix = np.atleast_2d(a_matrix)
+ u, s, vh = svd(a_matrix)
+ tol = max(atol, rtol * s[0])
+ nnz = (s >= tol).sum()
+ ns = vh[nnz:].conj().T
+ return ns
+
+
+def perform_steadystate(q_matrix, tangible_reach_graph):
+ """
+ Performs steady state analysis given the
+ :param q_matrix:
+ :return:
+ """
+ transient_result = Counter()
+ states = sorted(list(tangible_reach_graph.states), key=lambda x: x.name)
+ q_matrix_trans = np.matrix.transpose(q_matrix)
+ if nullspace(q_matrix_trans).shape[1] > 0:
+ M = np.matrix.transpose(nullspace(q_matrix_trans))
+ vec = np.zeros(M.shape[1])
+ for i in range(M.shape[0]):
+ v = np.matmul(M[i], q_matrix_trans)
+ val = np.sum(v) / np.sum(M[i])
+ vec = vec + val * M[i]
+ vec = vec / np.sum(vec)
+ for i in range(len(states)):
+ transient_result[states[i]] = vec[i]
+ return vec
+ return transient_result
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/tangible_reachability.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/tangible_reachability.py
new file mode 100644
index 0000000000000000000000000000000000000000..6230dbd77d3003da613fa719ae5f7b8b926ddf61
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/tangible_reachability.py
@@ -0,0 +1,158 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.petri_net.utils.reachability_graph import (
+ construct_reachability_graph,
+)
+from pm4py.objects.conversion.log import converter as log_converter
+
+
+def get_tangible_reachability_from_log_net_im_fm(
+ log, net, im, fm, parameters=None
+):
+ """
+ Gets the tangible reachability graph from a log and an accepting Petri net
+
+ Parameters
+ ---------------
+ log
+ Event log
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+
+ Returns
+ ------------
+ reachab_graph
+ Reachability graph
+ tangible_reach_graph
+ Tangible reachability graph
+ stochastic_info
+ Stochastic information
+ """
+ if parameters is None:
+ parameters = {}
+
+ from pm4py.algo.simulation.montecarlo.utils import replay
+
+ stochastic_info = replay.get_map_from_log_and_net(
+ log_converter.apply(
+ log,
+ variant=log_converter.Variants.TO_EVENT_LOG,
+ parameters=parameters,
+ ),
+ net,
+ im,
+ fm,
+ parameters=parameters,
+ )
+
+ reachability_graph, tangible_reachability_graph = (
+ get_tangible_reachability_from_net_im_sinfo(
+ net, im, stochastic_info, parameters=parameters
+ )
+ )
+
+ return reachability_graph, tangible_reachability_graph, stochastic_info
+
+
+def get_tangible_reachability_from_net_im_sinfo(
+ net, im, stochastic_info, parameters=None
+):
+ """
+ Gets the tangible reacahbility graph from a Petri net, an initial marking and a stochastic map
+
+ Parameters
+ -------------
+ net
+ Petri net
+ im
+ Initial marking
+ fm
+ Final marking
+ stochastic_info
+ Stochastic information
+
+ Returns
+ ------------
+ reachab_graph
+ Reachability graph
+ tangible_reach_graph
+ Tangible reachability graph
+ """
+ if parameters is None:
+ parameters = {}
+ reachab_graph = construct_reachability_graph(net, im, use_trans_name=True)
+ tang_reach_graph = get_tangible_reachability_from_reachability(
+ reachab_graph, stochastic_info
+ )
+
+ return reachab_graph, tang_reach_graph
+
+
+def get_tangible_reachability_from_reachability(reach_graph, stochastic_info):
+ """
+ Gets the tangible reachability graph from the reachability graph and the stochastic transition map
+
+ Parameters
+ ------------
+ reach_graph
+ Reachability graph
+ stochastic_info
+ Stochastic information
+
+ Returns
+ ------------
+ tangible_reach_graph
+ Tangible reachability graph
+ """
+ timed_transitions = []
+ for trans in stochastic_info.keys():
+ random_variable = stochastic_info[trans]
+ transition_type = random_variable.get_transition_type()
+ if transition_type == "TIMED":
+ timed_transitions.append(trans.name)
+ states_reach = list(reach_graph.states)
+ for s in states_reach:
+ state_outgoing_trans = list(s.outgoing)
+ state_ingoing_trans = list(s.incoming)
+ timed_trans_outgoing = [
+ x for x in state_outgoing_trans if x.name in timed_transitions
+ ]
+ if not len(state_outgoing_trans) == len(timed_trans_outgoing):
+ for t in state_outgoing_trans:
+ reach_graph.transitions.remove(t)
+ t.from_state.outgoing.remove(t)
+ t.to_state.incoming.remove(t)
+ for t in state_ingoing_trans:
+ reach_graph.transitions.remove(t)
+ t.from_state.outgoing.remove(t)
+ t.to_state.incoming.remove(t)
+ reach_graph.states.remove(s)
+ states_reach = list(reach_graph.states)
+ for s in states_reach:
+ if len(s.incoming) == 0 and len(s.outgoing) == 0:
+ reach_graph.states.remove(s)
+
+ return reach_graph
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..af28d24d50cb9fd06eb5a7a825c5586686706981
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/stochastic_petri/utils.py
@@ -0,0 +1,53 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from numpy.random import choice
+
+
+def pick_transition(et, smap):
+ """
+ Pick a transition in a set of transitions based on the weights
+ specified by the stochastic map
+
+ Parameters
+ --------------
+ et
+ Enabled transitions
+ smap
+ Stochastic map
+
+ Returns
+ --------------
+ trans
+ Transition chosen according to the weights
+ """
+ wmap = {ct: smap[ct].get_weight() if ct in smap else 1.0 for ct in et}
+ wmap_sv = sum(wmap.values())
+ list_of_candidates = []
+ probability_distribution = []
+ for ct in wmap:
+ list_of_candidates.append(ct)
+ if wmap_sv == 0:
+ probability_distribution.append(1.0 / float(len(wmap)))
+ else:
+ probability_distribution.append(wmap[ct] / wmap_sv)
+ ct = list(choice(et, 1, p=probability_distribution))[0]
+ return ct
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d32341aa2f4dec4cffba067ee23097bfbaef08c7
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.transition_system import obj, utils, constants
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/constants.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b14cb7027f99ff4d9c85a7521d438502f508984
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/constants.py
@@ -0,0 +1,24 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+INGOING_EVENTS = "ingoing_events"
+OUTGOING_EVENTS = "outgoing_events"
+EVENTS = "events"
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..8db7ffcaacf0f015362c67e067adbc4b9aa6ac5b
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/obj.py
@@ -0,0 +1,166 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.transition_system import constants
+
+
+class TransitionSystem(object):
+ class State(object):
+ def __init__(self, name, incoming=None, outgoing=None, data=None):
+ self.__name = name
+ self.__incoming = set() if incoming is None else incoming
+ self.__outgoing = set() if outgoing is None else outgoing
+ self.__data = (
+ {constants.INGOING_EVENTS: [], constants.OUTGOING_EVENTS: []}
+ if data is None
+ else data
+ )
+
+ def __get_name(self):
+ return self.__name
+
+ def __set_name(self, name):
+ self.__name = name
+
+ def __get_outgoing(self):
+ return self.__outgoing
+
+ def __set_outgoing(self, outgoing):
+ self.__outgoing = outgoing
+
+ def __get_incoming(self):
+ return self.__incoming
+
+ def __set_incoming(self, incoming):
+ self.__incoming = incoming
+
+ def __get_data(self):
+ return self.__data
+
+ def __set_data(self, data):
+ self.__data = data
+
+ def __repr__(self):
+ return str(self.name)
+
+ def __eq__(self, other):
+ if isinstance(other, TransitionSystem.State):
+ return self.__name == other.__name
+ return False
+
+ def __hash__(self):
+ return hash(str(self.__name))
+
+ name = property(__get_name, __set_name)
+ incoming = property(__get_incoming, __set_incoming)
+ outgoing = property(__get_outgoing, __set_outgoing)
+ data = property(__get_data, __set_data)
+
+ class Transition(object):
+
+ def __init__(self, name, from_state, to_state, data=None):
+ self.__name = name
+ self.__from_state = from_state
+ self.__to_state = to_state
+ self.__data = {constants.EVENTS: []} if data is None else data
+
+ def __get_name(self):
+ return self.__name
+
+ def __get_to_state(self):
+ return self.__to_state
+
+ def __set_to_state(self, to_state):
+ self.__to_state = to_state
+
+ def __get_from_state(self):
+ return self.__from_state
+
+ def __set_from_state(self, from_state):
+ self.__from_state = from_state
+
+ def __get_data(self):
+ return self.__data
+
+ def __set_data(self, data):
+ self.__data = data
+
+ def __repr__(self):
+ return str(self.name)
+
+ def __eq__(self, other):
+ if isinstance(other, TransitionSystem.Transition):
+ return (
+ self.__name == other.__name
+ and self.__from_state == other.__from_state
+ and self.__to_state == other.__to_state
+ )
+ return False
+
+ def __hash__(self):
+ return hash((str(self.__name), self.__from_state, self.__to_state))
+
+ name = property(__get_name)
+ from_state = property(__get_from_state, __set_from_state)
+ to_state = property(__get_to_state, __set_to_state)
+ data = property(__get_data, __set_data)
+
+ def __init__(self, name=None, states=None, transitions=None):
+ self.__name = "" if name is None else name
+ self.__states = set() if states is None else states
+ self.__transitions = set() if transitions is None else transitions
+
+ def __get_name(self):
+ return self.__name
+
+ def __set_name(self, name):
+ self.__name = name
+
+ def __get_states(self):
+ return self.__states
+
+ def __get_transitions(self):
+ return self.__transitions
+
+ def __set_transitions(self, transitions):
+ self.__transitions = transitions
+
+ def __eq__(self, other):
+ if isinstance(other, TransitionSystem):
+ return (
+ self.__name == other.__name
+ and self.__states == other.__states
+ and self.__transitions == other.__transitions
+ )
+ return False
+
+ def __hash__(self):
+ return hash(
+ (
+ str(self.__name),
+ frozenset(self.__states),
+ frozenset(self.__transitions),
+ )
+ )
+
+ name = property(__get_name, __set_name)
+ states = property(__get_states)
+ transitions = property(__get_transitions, __set_transitions)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ff2e8c47843bb4cfdbe5c30216467efaf253fd1
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/transition_system/utils.py
@@ -0,0 +1,134 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.objects.transition_system import obj
+
+
+def add_arc_from_to(name, fr, to, ts, data=None):
+ """
+ Adds a transition from a state to another state in some transition system.
+ Assumes from and to are in the transition system!
+
+ Parameters
+ ----------
+ name: name of the transition
+ fr: state from
+ to: state to
+ ts: transition system to use
+ data: data associated to the Transition System
+
+ Returns
+ -------
+ None
+ """
+ tran = obj.TransitionSystem.Transition(name, fr, to, data)
+ ts.transitions.add(tran)
+ fr.outgoing.add(tran)
+ to.incoming.add(tran)
+
+
+def remove_arc_from_to(name, fr, to, ts):
+ """
+ Removes a transition with a specific name from a state to another state in some transition system.
+ Assumes from and to are in the transition system!
+
+ Parameters
+ ----------
+ name: name of the transition
+ fr: state from
+ to: state to
+ ts: transition system to use
+
+ Returns
+ -------
+ None
+ """
+ ts.transitions = [t for t in ts.transitions if t.name != name]
+ fr.outgoing = [t for t in fr.outgoing if t.name != name]
+ to.incoming = [t for t in to.incoming if t.name != name]
+
+
+def remove_all_arcs_from_to(fr, to, ts):
+ """
+ Removes all transitions from a state to another state in some transition system.
+ Assumes from and to are in the transition system!
+
+ Parameters
+ ----------
+ fr: state from
+ to: state to
+ ts: transition system to use
+
+ Returns
+ -------
+ None
+ """
+ names_transitions_to_delete = [
+ t.name for t in ts.transitions if t in fr.outgoing and t in to.incoming
+ ]
+ ts.transitions = set(
+ [
+ t
+ for t in ts.transitions
+ if t.name not in names_transitions_to_delete
+ ]
+ )
+ fr.outgoing = set(
+ [t for t in fr.outgoing if t.name not in names_transitions_to_delete]
+ )
+ to.incoming = set(
+ [t for t in to.incoming if t.name not in names_transitions_to_delete]
+ )
+
+
+def transitive_reduction(ts):
+ """
+ Computes the transitive reduction of an acyclic transition system.
+ Assumes the transition system in input to be acyclic.
+
+ Parameters
+ ----------
+ ts: acyclic transition system to use
+
+ Returns
+ -------
+ None
+ """
+
+ def check(this_state, this_child, this_done):
+ if this_child not in this_done:
+ child_children = [
+ tr.to_state
+ for tr in ts.transitions
+ if tr in this_child.outgoing
+ ]
+ for child_child in child_children:
+ remove_all_arcs_from_to(this_state, child_child, ts)
+ check(this_state, child_child, this_done)
+ this_done.add(this_child)
+
+ for state in ts.states:
+ done = set()
+ children = [
+ tr.to_state for tr in ts.transitions if tr in state.outgoing
+ ]
+ for child in children:
+ check(state, child, done)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/trie/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/trie/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e47e8ca779b484008334b6ed5108d035e87a4cfd
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/trie/__init__.py
@@ -0,0 +1,25 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+from pm4py.util import constants as pm4_constants
+
+if pm4_constants.ENABLE_INTERNAL_IMPORTS:
+ from pm4py.objects.trie import obj
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/trie/obj.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/trie/obj.py
new file mode 100644
index 0000000000000000000000000000000000000000..55c4711f173bf21d1c2a4ea658b0177478de3449
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/trie/obj.py
@@ -0,0 +1,111 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+class Trie(object):
+
+ def __init__(
+ self, label=None, parent=None, children=None, final=False, depth=0
+ ):
+ self._label = label
+ self._parent = parent
+ self._children = children if children is not None else list()
+ self._final = final
+ self._depth = depth
+
+ def _set_parent(self, parent):
+ self._parent = parent
+
+ def _set_label(self, label):
+ self._label = label
+
+ def _set_children(self, children):
+ self._children = children
+
+ def _set_final(self, final):
+ self._final = final
+
+ def _get_children(self):
+ return self._children
+
+ def _get_final(self):
+ return self._final
+
+ def _get_parent(self):
+ return self._parent
+
+ def _get_label(self):
+ return self._label
+
+ def _set_depth(self, depth):
+ self._depth = depth
+
+ def _get_depth(self):
+ return self._depth
+
+ parent = property(_get_parent, _set_parent)
+ children = property(_get_children, _set_children)
+ label = property(_get_label, _set_label)
+ final = property(_get_final, _set_final)
+ depth = property(_get_depth, _set_depth)
+
+ def repr_trie(self, indent_level=0):
+ stri = []
+
+ if self.label:
+ stri.append("\t" * indent_level + self.label)
+ indent_level += 1
+ for child in self.children:
+ stri.append(child.repr_trie(indent_level=indent_level))
+ if self.final:
+ stri.append("\t" * indent_level + "-- END --")
+
+ return "\n".join(stri)
+
+ def __repr__(self):
+ return self.repr_trie()
+
+ def __str__(self):
+ return self.repr_trie()
+
+ def __eq__(self, other):
+ if not isinstance(other, Trie):
+ return False
+ if self._label != other._label:
+ return False
+ if self._final != other._final:
+ return False
+ this_children = sorted(self._children, key=lambda x: x._label)
+ other_children = sorted(other._children, key=lambda x: x._label)
+ if len(this_children) != len(other_children):
+ return False
+ for i in range(len(this_children)):
+ if this_children[i] != other_children[i]:
+ return False
+ return True
+
+ def __hash__(self):
+ return hash(
+ (
+ self._label,
+ self._final,
+ tuple(sorted(self._children, key=lambda x: x._label)),
+ )
+ )
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ocel.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ocel.py
new file mode 100644
index 0000000000000000000000000000000000000000..79711400202fed352f0fa2d5f4316485b632a655
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ocel.py
@@ -0,0 +1,1073 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+The ``pm4py.ocel`` module contains the object-centric process mining features offered in ``pm4py``.
+"""
+
+from typing import List, Dict, Collection, Any, Optional, Set, Tuple
+
+import pandas as pd
+import numpy as np
+
+from pm4py.objects.ocel.obj import OCEL
+from pm4py.objects.ocel import constants as ocel_constants
+from pm4py.objects.ocpn.obj import OCPetriNet
+from pm4py.util import constants, pandas_utils
+import sys
+import random
+import time
+
+
+def ocel_get_object_types(ocel: OCEL) -> List[str]:
+ """
+ Returns the list of object types contained in the object-centric event log
+ (e.g., ["order", "item", "delivery"]).
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: List of object types.
+ :rtype: List[str]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ object_types = pm4py.ocel_get_object_types(ocel)
+ """
+ return pandas_utils.format_unique(
+ ocel.objects[ocel.object_type_column].unique()
+ )
+
+
+def ocel_get_attribute_names(ocel: OCEL) -> List[str]:
+ """
+ Returns the list of attributes at the event and object levels of an object-centric event log
+ (e.g., ["cost", "amount", "name"]).
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: List of attribute names.
+ :rtype: List[str]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ attribute_names = pm4py.ocel_get_attribute_names(ocel)
+ """
+ from pm4py.objects.ocel.util import attributes_names
+
+ return attributes_names.get_attribute_names(ocel)
+
+
+def ocel_flattening(ocel: OCEL, object_type: str) -> pd.DataFrame:
+ """
+ Flattens the object-centric event log to a traditional event log based on a chosen object type.
+ In the flattened log, the objects of the specified type are treated as cases, and each case
+ contains the set of events related to that object.
+ The flattened log follows the XES notations for case identifier, activity, and timestamp. Specifically:
+ - "case:concept:name" is used for the case ID.
+ - "concept:name" is used for the activity.
+ - "time:timestamp" is used for the timestamp.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param object_type: The object type to use as cases.
+ :type object_type: str
+ :return: Flattened traditional event log.
+ :rtype: pd.DataFrame
+
+ .. code-block:: python3
+
+ import pm4py
+
+ event_log = pm4py.ocel_flattening(ocel, 'items')
+ """
+ from pm4py.objects.ocel.util import flattening
+
+ return flattening.flatten(ocel, object_type)
+
+
+def ocel_object_type_activities(ocel: OCEL) -> Dict[str, Collection[str]]:
+ """
+ Returns the set of activities performed for each object type.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Dictionary mapping object types to their associated activities.
+ :rtype: Dict[str, Collection[str]]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ot_activities = pm4py.ocel_object_type_activities(ocel)
+ """
+ from pm4py.statistics.ocel import ot_activities
+
+ return ot_activities.get_object_type_activities(ocel)
+
+
+def ocel_objects_ot_count(ocel: OCEL) -> Dict[str, Dict[str, int]]:
+ """
+ Returns the count of related objects per type for each event.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Nested dictionary mapping events to object types and their counts.
+ :rtype: Dict[str, Dict[str, int]]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ objects_ot_count = pm4py.ocel_objects_ot_count(ocel)
+ """
+ from pm4py.statistics.ocel import objects_ot_count
+
+ return objects_ot_count.get_objects_ot_count(ocel)
+
+
+def ocel_temporal_summary(ocel: OCEL) -> pd.DataFrame:
+ """
+ Returns the temporal summary of an object-centric event log.
+ The temporal summary aggregates all events that occur at the same timestamp
+ and reports the list of activities and involved objects.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Temporal summary DataFrame.
+ :rtype: pd.DataFrame
+
+ .. code-block:: python3
+
+ import pm4py
+
+ temporal_summary = pm4py.ocel_temporal_summary(ocel)
+ """
+ gdf = ocel.relations.groupby(ocel.event_timestamp)
+ act_comb = gdf[ocel.event_activity].agg(list).to_frame()
+ obj_comb = gdf[ocel.object_id_column].agg(list).to_frame()
+ temporal_summary = act_comb.join(obj_comb).reset_index()
+ return temporal_summary
+
+
+def ocel_objects_summary(ocel: OCEL) -> pd.DataFrame:
+ """
+ Returns the objects summary of an object-centric event log.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Objects summary DataFrame containing lifecycle information and interacting objects.
+ :rtype: pd.DataFrame
+
+ .. code-block:: python3
+
+ import pm4py
+
+ objects_summary = pm4py.ocel_objects_summary(ocel)
+ """
+ gdf = ocel.relations.groupby(ocel.object_id_column)
+ act_comb = (
+ gdf[ocel.event_activity]
+ .agg(list)
+ .to_frame()
+ .rename(columns={ocel.event_activity: "activities_lifecycle"})
+ )
+ lif_start_tim = (
+ gdf[ocel.event_timestamp]
+ .min()
+ .to_frame()
+ .rename(columns={ocel.event_timestamp: "lifecycle_start"})
+ )
+ lif_end_tim = (
+ gdf[ocel.event_timestamp]
+ .max()
+ .to_frame()
+ .rename(columns={ocel.event_timestamp: "lifecycle_end"})
+ )
+ objects_summary = act_comb.join(lif_start_tim)
+ objects_summary = objects_summary.join(lif_end_tim)
+ objects_summary = objects_summary.reset_index()
+ objects_summary["lifecycle_duration"] = pandas_utils.get_total_seconds(
+ objects_summary["lifecycle_end"] - objects_summary["lifecycle_start"]
+ )
+ ev_rel_obj = (
+ ocel.relations.groupby(ocel.event_id_column)[ocel.object_id_column]
+ .agg(list)
+ .to_dict()
+ )
+ objects_ids = pandas_utils.format_unique(
+ ocel.objects[ocel.object_id_column].unique()
+ )
+ graph = {o: set() for o in objects_ids}
+ for ev in ev_rel_obj:
+ rel_obj = ev_rel_obj[ev]
+ for o1 in rel_obj:
+ for o2 in rel_obj:
+ if o1 != o2:
+ graph[o1].add(o2)
+ objects_summary["interacting_objects"] = objects_summary[
+ ocel.object_id_column
+ ].map(graph)
+ return objects_summary
+
+
+def ocel_objects_interactions_summary(ocel: OCEL) -> pd.DataFrame:
+ """
+ Returns the objects interactions summary of an object-centric event log.
+ The summary includes a row for every combination of (event, related object, other related object).
+ Properties such as the activity of the event and the object types of the two related objects are included.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Objects interactions summary DataFrame.
+ :rtype: pd.DataFrame
+
+ .. code-block:: python3
+
+ import pm4py
+
+ interactions_summary = pm4py.ocel_objects_interactions_summary(ocel)
+ """
+ obj_types = (
+ ocel.objects.groupby(ocel.object_id_column)[ocel.object_type_column]
+ .first()
+ .to_dict()
+ )
+ eve_activities = (
+ ocel.events.groupby(ocel.event_id_column)[ocel.event_activity]
+ .first()
+ .to_dict()
+ )
+ ev_rel_obj = (
+ ocel.relations.groupby(ocel.event_id_column)[ocel.object_id_column]
+ .agg(list)
+ .to_dict()
+ )
+ stream = []
+ for ev in ev_rel_obj:
+ rel_obj = ev_rel_obj[ev]
+ for o1 in rel_obj:
+ for o2 in rel_obj:
+ if o1 != o2:
+ stream.append(
+ {
+ ocel.event_id_column: ev,
+ ocel.event_activity: eve_activities[ev],
+ ocel.object_id_column: o1,
+ ocel.object_type_column: obj_types[o1],
+ f"{ocel.object_id_column}_2": o2,
+ f"{ocel.object_type_column}_2": obj_types[o2],
+ }
+ )
+
+ return pandas_utils.instantiate_dataframe(stream)
+
+
+def discover_ocdfg(
+ ocel: OCEL,
+ event_id: Optional[str] = None,
+ event_activity: Optional[str] = None,
+ event_timestamp: Optional[str] = None,
+ object_id: Optional[str] = None,
+ object_type: Optional[str] = None,
+ compute_edges_performance: bool = True,
+ business_hours: bool = False,
+ business_hour_slots: Optional[
+ List[Tuple[int, int]]
+ ] = constants.DEFAULT_BUSINESS_HOUR_SLOTS,
+ workcalendar: str = constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR,
+) -> Dict[str, Any]:
+ """
+ Discovers an Object-Centric Directly-Follows Graph (OC-DFG) from an object-centric event log.
+
+ Object-centric directly-follows multigraphs are a composition of directly-follows graphs for each object type.
+ These graphs can be annotated with different metrics considering the entities of an object-centric event log
+ (i.e., events, unique objects, total objects).
+
+ Returns an object-centric directly-follows graph, expressed as a dictionary containing the following properties:
+ - activities: complete set of activities derived from the object-centric event log
+ - object_types: complete set of object types derived from the object-centric event log
+ - edges: dictionary connecting each object type to a set of directly-followed arcs between activities
+ - activities_indep: dictionary linking each activity, regardless of the object type
+ - activities_ot: dictionary linking each object type to another dictionary
+ - start_activities: dictionary linking each object type to start activities
+ - end_activities: dictionary linking each object type to end activities
+
+ Reference paper:
+ Berti, Alessandro, and Wil van der Aalst. "Extracting multiple viewpoint models from relational databases."
+ Data-Driven Process Discovery and Analysis. Springer, Cham, 2018. 24-51.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param event_id: Event identifier column to use.
+ :type event_id: Optional[str]
+ :param event_activity: Event activity column to use.
+ :type event_activity: Optional[str]
+ :param event_timestamp: Event timestamp column to use.
+ :type event_timestamp: Optional[str]
+ :param object_id: Object identifier column to use.
+ :type object_id: Optional[str]
+ :param object_type: Object type column to use.
+ :type object_type: Optional[str]
+ :param compute_edges_performance: Enable the computation of edge performance metrics if set to True.
+ :type compute_edges_performance: bool
+ :param business_hours: Enable the usage of business hours if set to True.
+ :type business_hours: bool
+ :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 tuple consists of a start
+ and an end time given in seconds since week start, e.g.,
+ [(25200, 61200), (9072, 43200), (46800, 61200)] meaning that business hours
+ are Mondays 07:00 - 17:00, Tuesdays 02:32 - 12:00, and Wednesdays 13:00 - 17:00.
+ :type business_hour_slots: Optional[List[Tuple[int, int]]]
+ :param workcalendar: Work calendar to use when business hours are enabled.
+ :type workcalendar: str
+ :return: OC-DFG discovery result.
+ :rtype: Dict[str, Any]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocdfg = pm4py.discover_ocdfg(ocel)
+ """
+ parameters = {
+ ocel_constants.PARAM_EVENT_ID: event_id if event_id is not None else ocel.event_id_column,
+ ocel_constants.PARAM_EVENT_ACTIVITY: event_activity if event_activity is not None else ocel.event_activity,
+ ocel_constants.PARAM_EVENT_TIMESTAMP: event_timestamp if event_timestamp is not None else ocel.event_timestamp,
+ ocel_constants.PARAM_OBJECT_ID: object_id if object_id is not None else ocel.object_id_column,
+ ocel_constants.PARAM_OBJECT_TYPE: object_type if object_type is not None else ocel.object_type_column,
+ "compute_edges_performance": compute_edges_performance,
+ "business_hours": business_hours,
+ "business_hour_slots": business_hour_slots,
+ "workcalendar": workcalendar,
+ }
+ from pm4py.algo.discovery.ocel.ocdfg import algorithm as ocdfg_discovery
+
+ return ocdfg_discovery.apply(ocel, parameters=parameters)
+
+
+def discover_oc_petri_net(
+ ocel: OCEL,
+ inductive_miner_variant: str = "im",
+ noise_threshold: float = 0.0,
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
+ disable_fallthroughs: bool = True,
+ disable_strict_sequence_cut: bool = True,
+ diagnostics_with_tbr: bool = False,
+) -> OCPetriNet:
+ """
+ Discovers an object-centric Petri net from the provided object-centric event log.
+
+ Reference paper: van der Aalst, Wil MP, and Alessandro Berti.
+ "Discovering object-centric Petri nets." Fundamenta Informaticae 175.1-4 (2020): 1-40.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param inductive_miner_variant: Variant of the inductive miner to use ("im" for traditional, "imf" for infrequent, or "imd" for the faster inductive miner directly-follows).
+ :type inductive_miner_variant: str
+ :param noise_threshold: Noise threshold for the inductive miner (default: 0.0).
+ :type noise_threshold: float
+ :param multi_processing: Enables or disables multiprocessing in the inductive miner.
+ :type multi_processing: bool
+ :param disable_fallthroughs: Disables the inductive miner fall-throughs.
+ :type disable_fallthroughs: bool
+ :param disable_strict_sequence_cut: Disables the strict sequence cut in the inductive miner.
+ :type disable_strict_sequence_cut: bool
+ :param diagnostics_with_tbr: Enable the computation of diagnostics using token-based replay if set to True.
+ :type diagnostics_with_tbr: bool
+ :return: Discovered object-centric Petri net.
+ :rtype: OCPetriNet
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocpn = pm4py.discover_oc_petri_net(ocel)
+ """
+ from pm4py.algo.discovery.ocel.ocpn import algorithm as ocpn_discovery
+
+ parameters = {
+ "inductive_miner_variant": inductive_miner_variant,
+ "noise_threshold": noise_threshold,
+ "multiprocessing": multi_processing,
+ "disable_fallthroughs": disable_fallthroughs,
+ "disable_strict_sequence_cut": disable_strict_sequence_cut,
+ "diagnostics_with_token_based_replay": diagnostics_with_tbr,
+ }
+
+ return ocpn_discovery.apply(ocel, parameters=parameters)
+
+
+def discover_objects_graph(
+ ocel: OCEL, graph_type: str = "object_interaction"
+) -> Set[Tuple[str, str]]:
+ """
+ Discovers an object graph from the provided object-centric event log.
+
+ Available graph types:
+ - "object_interaction"
+ - "object_descendants"
+ - "object_inheritance"
+ - "object_cobirth"
+ - "object_codeath"
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param graph_type: Type of graph to consider.
+ Options include "object_interaction", "object_descendants",
+ "object_inheritance", "object_cobirth", "object_codeath".
+ :type graph_type: str
+ :return: Discovered object graph as a set of tuples.
+ :rtype: Set[Tuple[str, str]]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ obj_graph = pm4py.discover_objects_graph(ocel, graph_type='object_interaction')
+ """
+ if graph_type == "object_interaction":
+ from pm4py.algo.transformation.ocel.graphs import (
+ object_interaction_graph,
+ )
+
+ return object_interaction_graph.apply(ocel)
+ elif graph_type == "object_descendants":
+ from pm4py.algo.transformation.ocel.graphs import (
+ object_descendants_graph,
+ )
+
+ return object_descendants_graph.apply(ocel)
+ elif graph_type == "object_inheritance":
+ from pm4py.algo.transformation.ocel.graphs import (
+ object_inheritance_graph,
+ )
+
+ return object_inheritance_graph.apply(ocel)
+ elif graph_type == "object_cobirth":
+ from pm4py.algo.transformation.ocel.graphs import object_cobirth_graph
+
+ return object_cobirth_graph.apply(ocel)
+ elif graph_type == "object_codeath":
+ from pm4py.algo.transformation.ocel.graphs import object_codeath_graph
+
+ return object_codeath_graph.apply(ocel)
+ else:
+ raise ValueError(f"Unsupported graph_type: {graph_type}")
+
+
+def ocel_o2o_enrichment(
+ ocel: OCEL, included_graphs: Optional[Collection[str]] = None
+) -> OCEL:
+ """
+ Enriches the OCEL with information inferred from graph computations by inserting them into the O2O relations.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param included_graphs: Types of graphs to include, provided as a list or set of strings.
+ Options include "object_interaction_graph", "object_descendants_graph",
+ "object_inheritance_graph", "object_cobirth_graph", "object_codeath_graph".
+ :type included_graphs: Optional[Collection[str]]
+ :return: Enriched object-centric event log.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ ocel = pm4py.ocel_o2o_enrichment(ocel)
+ print(ocel.o2o)
+ """
+ from pm4py.algo.transformation.ocel.graphs import ocel20_computation
+
+ return ocel20_computation.apply(
+ ocel, parameters={"included_graphs": included_graphs}
+ )
+
+
+def ocel_e2o_lifecycle_enrichment(ocel: OCEL) -> OCEL:
+ """
+ Enriches the OCEL with lifecycle-based information, indicating when an object is created, terminated,
+ or has other types of relations, by updating the E2O relations.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Enriched object-centric event log with lifecycle information.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ ocel = pm4py.ocel_e2o_lifecycle_enrichment(ocel)
+ print(ocel.relations)
+ """
+ from pm4py.objects.ocel.util import e2o_qualification
+
+ ocel = e2o_qualification.apply(ocel, "termination")
+ ocel = e2o_qualification.apply(ocel, "creation")
+ ocel = e2o_qualification.apply(ocel, "other")
+ return ocel
+
+
+def sample_ocel_objects(ocel: OCEL, num_objects: int) -> OCEL:
+ """
+ Returns a sampled object-centric event log containing a random subset of objects.
+ Only events related to at least one of the sampled objects are included in the returned log.
+ Note that this sampling may disrupt the relationships between different objects.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param num_objects: Number of objects to include in the sampled event log.
+ :type num_objects: int
+ :return: Sampled object-centric event log.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ sampled_ocel = pm4py.sample_ocel_objects(ocel, 50) # Keeps only 50 random objects
+ """
+ from pm4py.objects.ocel.util import sampling
+
+ return sampling.sample_ocel_objects(
+ ocel, parameters={"num_entities": num_objects}
+ )
+
+
+def sample_ocel_connected_components(
+ ocel: OCEL,
+ connected_components: int = 1,
+ max_num_events_per_cc: int = sys.maxsize,
+ max_num_objects_per_cc: int = sys.maxsize,
+ max_num_e2o_relations_per_cc: int = sys.maxsize,
+) -> OCEL:
+ """
+ Returns a sampled object-centric event log containing a specified number of connected components.
+ Users can also set maximum limits on the number of events, objects, and E2O relations per connected component.
+
+ Reference paper:
+ Adams, Jan Niklas, et al. "Defining cases and variants for object-centric event data."
+ 2022 4th International Conference on Process Mining (ICPM). IEEE, 2022.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param connected_components: Number of connected components to include in the sampled event log.
+ :type connected_components: int
+ :param max_num_events_per_cc: Maximum number of events allowed per connected component (default: sys.maxsize).
+ :type max_num_events_per_cc: int
+ :param max_num_objects_per_cc: Maximum number of objects allowed per connected component (default: sys.maxsize).
+ :type max_num_objects_per_cc: int
+ :param max_num_e2o_relations_per_cc: Maximum number of event-to-object relationships allowed per connected component (default: sys.maxsize).
+ :type max_num_e2o_relations_per_cc: int
+ :return: Sampled object-centric event log containing the specified connected components.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ sampled_ocel = pm4py.sample_ocel_connected_components(ocel, 5) # Keeps only 5 connected components
+ """
+ from pm4py.algo.transformation.ocel.split_ocel import algorithm
+
+ ocel_splits = algorithm.apply(
+ ocel, variant=algorithm.Variants.CONNECTED_COMPONENTS
+ )
+ events = None
+ objects = None
+ relations = None
+ ocel_splits = [
+ x
+ for x in ocel_splits
+ if len(x.events) <= max_num_events_per_cc
+ and len(x.objects) <= max_num_objects_per_cc
+ and len(x.relations) <= max_num_e2o_relations_per_cc
+ ]
+
+ if len(ocel_splits) > 0:
+ ocel_splits = random.sample(
+ ocel_splits, min(connected_components, len(ocel_splits))
+ )
+
+ for cc in ocel_splits:
+ if events is None:
+ events = cc.events
+ objects = cc.objects
+ relations = cc.relations
+ else:
+ events = pandas_utils.concat([events, cc.events])
+ objects = pandas_utils.concat([objects, cc.objects])
+ relations = pandas_utils.concat([relations, cc.relations])
+
+ return OCEL(events, objects, relations)
+
+
+def ocel_drop_duplicates(ocel: OCEL) -> OCEL:
+ """
+ Removes duplicate relations between events and objects that occur at the same time,
+ have the same activity, and are linked to the same object identifier.
+ This effectively cleans the OCEL by eliminating duplicate events.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Cleaned object-centric event log without duplicate relations.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ ocel = pm4py.ocel_drop_duplicates(ocel)
+ """
+ from pm4py.objects.ocel.util import filtering_utils
+
+ ocel.relations = ocel.relations.drop_duplicates(
+ subset=[
+ ocel.event_activity,
+ ocel.event_timestamp,
+ ocel.object_id_column,
+ ]
+ )
+ ocel = filtering_utils.propagate_relations_filtering(ocel)
+ return ocel
+
+
+def ocel_merge_duplicates(
+ ocel: OCEL, have_common_object: Optional[bool] = False
+) -> OCEL:
+ """
+ Merges events in the OCEL that have the same activity and timestamp. Optionally, ensures that
+ the events being merged share a common object.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param have_common_object: If set to True, only merges events that share a common object. Defaults to False.
+ :type have_common_object: Optional[bool]
+ :return: Object-centric event log with merged duplicate events.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ ocel = pm4py.ocel_merge_duplicates(ocel)
+ """
+ import copy
+ import uuid
+
+ relations = copy.copy(ocel.relations)
+ if have_common_object:
+ relations["@@groupn"] = relations.groupby(
+ [ocel.object_id_column, ocel.event_activity, ocel.event_timestamp]
+ ).ngroup()
+ else:
+ relations["@@groupn"] = relations.groupby(
+ [ocel.event_activity, ocel.event_timestamp]
+ ).ngroup()
+
+ group_size = relations["@@groupn"].value_counts().to_dict()
+ relations["@@groupsize"] = relations["@@groupn"].map(group_size)
+ relations = relations.sort_values(
+ ["@@groupsize", "@@groupn"], ascending=False
+ )
+ val_corr = {
+ x: str(uuid.uuid4())
+ for x in pandas_utils.format_unique(relations["@@groupn"].unique())
+ }
+ relations = (
+ relations.groupby(ocel.event_id_column).first()["@@groupn"].to_dict()
+ )
+ relations = {x: val_corr[y] for x, y in relations.items()}
+
+ ocel.events[ocel.event_id_column] = ocel.events[ocel.event_id_column].map(
+ relations
+ )
+ ocel.relations[ocel.event_id_column] = ocel.relations[
+ ocel.event_id_column
+ ].map(relations)
+
+ ocel.events = ocel.events.drop_duplicates(subset=[ocel.event_id_column])
+ ocel.relations = ocel.relations.drop_duplicates(
+ subset=[ocel.event_id_column, ocel.object_id_column]
+ )
+
+ return ocel
+
+
+def ocel_sort_by_additional_column(
+ ocel: OCEL, additional_column: str, primary_column: str = "ocel:timestamp"
+) -> OCEL:
+ """
+ Sorts the OCEL based on the primary timestamp column and an additional column to determine
+ the order of events occurring at the same timestamp.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param additional_column: Additional column to use for sorting.
+ :type additional_column: str
+ :param primary_column: Primary column to use for sorting (default: "ocel:timestamp").
+ Typically the timestamp column.
+ :type primary_column: str
+ :return: Sorted object-centric event log.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ ocel = pm4py.ocel_sort_by_additional_column(ocel, 'ordering')
+ """
+ ocel.events = pandas_utils.insert_index(
+ ocel.events, "@@index", reset_index=False, copy_dataframe=False
+ )
+ ocel.events = ocel.events.sort_values(
+ [primary_column, additional_column, "@@index"]
+ )
+ del ocel.events["@@index"]
+ ocel.events = ocel.events.reset_index(drop=True)
+ return ocel
+
+
+def ocel_add_index_based_timedelta(ocel: OCEL) -> OCEL:
+ """
+ Adds a small time delta to the timestamp column based on the event index to ensure the correct ordering
+ of events within any object-centric process mining solution.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :return: Object-centric event log with index-based time deltas added.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ ocel = pm4py.ocel_add_index_based_timedelta(ocel)
+ """
+ from datetime import timedelta
+
+ eids = ocel.events[ocel.event_id_column].to_numpy().tolist()
+ eids = {eids[i]: timedelta(milliseconds=i) for i in range(len(eids))}
+ ocel.events["@@timedelta"] = ocel.events[ocel.event_id_column].map(eids)
+ ocel.relations["@@timedelta"] = ocel.relations[ocel.event_id_column].map(
+ eids
+ )
+ ocel.events[ocel.event_timestamp] = (
+ ocel.events[ocel.event_timestamp] + ocel.events["@@timedelta"]
+ )
+ ocel.relations[ocel.event_timestamp] = (
+ ocel.relations[ocel.event_timestamp] + ocel.relations["@@timedelta"]
+ )
+ del ocel.events["@@timedelta"]
+ del ocel.relations["@@timedelta"]
+ return ocel
+
+
+def __vectors_to_clusters(keys, vectors, objects):
+ from sklearn.metrics import pairwise_distances
+ D = pairwise_distances(vectors, metric="hamming")
+ A = 1.0 - D
+ np.fill_diagonal(A, 1.0)
+ return D, A
+
+
+def __eqocel_to_keyset(clusters: Dict[str, Collection[OCEL]]):
+ clusters_keys = list(clusters.keys())
+ keyset = []
+ objects = []
+ for c in clusters_keys:
+ keyset.append(set())
+ for i in range(len(c[0])):
+ if i < len(c[0])-1:
+ keyset[-1].add((c[0][i][0], c[0][i + 1][0], "DF"))
+ pass
+ for j in range(1, len(c[0][i])):
+ keyset[-1].add((c[0][i][0], c[0][i][j], "E2O"))
+ pass
+ V = clusters[c]
+ objects.append([])
+ for v in V:
+ objects[-1].append(v.parameters["@@central_object"])
+ return keyset, objects
+
+
+def __eqocel_to_vectors(clusters: Dict[str, Collection[OCEL]]):
+ keyset, objects = __eqocel_to_keyset(clusters)
+ print(keyset)
+ keys = list(set(y for x in keyset for y in x))
+ keys = {x: i for i, x in enumerate(keys)}
+ vectors = [[0] * len(keys) for i in range(len(clusters))]
+ for z, ks in enumerate(keyset):
+ for k in ks:
+ vectors[z][keys[k]] = 1
+
+ return keys, keyset, vectors, objects
+
+
+def cluster_equivalent_ocel(
+ ocel: OCEL, object_type: str, max_objs: int = sys.maxsize, exclude_object_types_from_renaming : Optional[Set[str]] = None
+) -> Dict[str, Collection[OCEL]]:
+ """
+ Clusters the object-centric event log based on the 'executions' of a single object type.
+ Equivalent 'executions' are grouped together in the output dictionary.
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param object_type: Reference object type for clustering.
+ :type object_type: str
+ :param max_objs: Maximum number of objects (of the specified object type) to include per cluster.
+ Defaults to sys.maxsize.
+ :type max_objs: int
+ :return: Dictionary mapping cluster descriptions to collections of equivalent OCELs.
+ :rtype: Dict[str, Collection[OCEL]]
+
+ .. code-block:: python3
+
+ import pm4py
+
+ ocel = pm4py.read_ocel('trial.ocel')
+ clusters = pm4py.cluster_equivalent_ocel(ocel, "order")
+ """
+ from pm4py.algo.transformation.ocel.split_ocel import (
+ algorithm as split_ocel_algorithm,
+ )
+ from pm4py.objects.ocel.util import rename_objs_ot_tim_lex
+ from pm4py.algo.transformation.ocel.description import (
+ algorithm as ocel_description,
+ )
+
+ #aa = time.time_ns()
+ lst_ocels = split_ocel_algorithm.apply(
+ ocel,
+ variant=split_ocel_algorithm.Variants.ANCESTORS_DESCENDANTS,
+ parameters={"object_type": object_type, "max_objs": max_objs},
+ )
+ #bb = time.time_ns()
+ #print((bb-aa)/10**9)
+
+ ret = {}
+ for index, oc in enumerate(lst_ocels):
+ oc_ren = rename_objs_ot_tim_lex.apply(oc, parameters={"exclude_object_types": exclude_object_types_from_renaming})
+ descr = ocel_description.apply(
+ oc_ren, variant=ocel_description.Variants.VARIANT2, parameters={"include_timestamps": False}
+ )
+ if descr not in ret:
+ ret[descr] = []
+ ret[descr].append(oc)
+ return ret
+
+
+def ocel_drill_down(
+ ocel: OCEL, object_type: str, object_attribute: str
+) -> OCEL:
+ """
+ Drill-down OLAP operation on an object-centric event log: splits a given
+ object type into finer-grained tuple-style sub-types based on the values
+ of a given object attribute.
+
+ For every object whose ``ocel:type`` equals ``object_type`` and whose
+ ``object_attribute`` value is defined, the type is rewritten to
+ ``"(object_type, value)"``. Objects with an undefined attribute value
+ keep their original type. The operation is information-preserving and
+ reversible via :func:`ocel_roll_up`.
+
+ Reference: Khayatbashi, Miri, Jalali, "Advancing Object-Centric Process
+ Mining with Multi-Dimensional Data Operations", CAiSE Forum 2025
+ (arXiv:2412.00393).
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param object_type: Object type to split.
+ :type object_type: str
+ :param object_attribute: Object attribute column whose values drive
+ the split.
+ :type object_attribute: str
+ :return: A new OCEL with the drilled-down object type.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ drilled = pm4py.ocel_drill_down(ocel, "Test", "test_type")
+ """
+ from pm4py.algo.transformation.ocel.olap.drill_down import (
+ algorithm as drill_down_algorithm,
+ )
+ from pm4py.algo.transformation.ocel.olap.drill_down.variants import (
+ classic as drill_down_classic,
+ )
+
+ parameters = {
+ drill_down_classic.Parameters.OBJECT_TYPE: object_type,
+ drill_down_classic.Parameters.OBJECT_ATTRIBUTE: object_attribute,
+ }
+ return drill_down_algorithm.apply(ocel, parameters=parameters)
+
+
+def ocel_roll_up(
+ ocel: OCEL, object_type: str, object_attribute: Optional[str] = None
+) -> OCEL:
+ """
+ Roll-up OLAP operation on an object-centric event log: collapses
+ tuple-style sub-types of the given parent ``object_type`` back to the
+ parent type. Inverse of :func:`ocel_drill_down`.
+
+ Reference: Khayatbashi, Miri, Jalali, "Advancing Object-Centric Process
+ Mining with Multi-Dimensional Data Operations", CAiSE Forum 2025
+ (arXiv:2412.00393).
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param object_type: Parent object type to merge sub-types back to.
+ :type object_type: str
+ :param object_attribute: Optional, accepted for API symmetry with
+ :func:`ocel_drill_down`. When provided it must be a column of
+ ``ocel.objects``, but it is not semantically required because the
+ tuple type value already encodes the split.
+ :type object_attribute: Optional[str]
+ :return: A new OCEL with the rolled-up object type.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ rolled = pm4py.ocel_roll_up(drilled, "Test")
+ """
+ from pm4py.algo.transformation.ocel.olap.roll_up import (
+ algorithm as roll_up_algorithm,
+ )
+ from pm4py.algo.transformation.ocel.olap.roll_up.variants import (
+ classic as roll_up_classic,
+ )
+
+ parameters = {
+ roll_up_classic.Parameters.OBJECT_TYPE: object_type,
+ roll_up_classic.Parameters.OBJECT_ATTRIBUTE: object_attribute,
+ }
+ return roll_up_algorithm.apply(ocel, parameters=parameters)
+
+
+def ocel_unfold(
+ ocel: OCEL,
+ event_type: str,
+ object_type: str,
+ qualifiers: Optional[Collection[Any]] = None,
+) -> OCEL:
+ """
+ Unfold OLAP operation on an object-centric event log: splits an event
+ type into a tuple-style sub-type keyed by a related object type,
+ optionally restricted to a set of E2O qualifiers.
+
+ Every event of type ``event_type`` that has at least one matching
+ E2O relation to an object of type ``object_type`` has its activity
+ rewritten to ``"(event_type, object_type)"`` in both ``ocel.events``
+ and ``ocel.relations``. Reversible via :func:`ocel_fold`.
+
+ Reference: Khayatbashi, Miri, Jalali, "Advancing Object-Centric Process
+ Mining with Multi-Dimensional Data Operations", CAiSE Forum 2025
+ (arXiv:2412.00393).
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param event_type: Event type/activity to unfold.
+ :type event_type: str
+ :param object_type: Related object type to unfold over.
+ :type object_type: str
+ :param qualifiers: Optional collection of qualifier values to filter
+ the driving E2O relations. ``None`` means all qualifiers.
+ :type qualifiers: Optional[Collection[Any]]
+ :return: A new OCEL with the unfolded event type.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ unfolded = pm4py.ocel_unfold(ocel, "order test", "(Test, ECG)")
+ """
+ from pm4py.algo.transformation.ocel.olap.unfold import (
+ algorithm as unfold_algorithm,
+ )
+ from pm4py.algo.transformation.ocel.olap.unfold.variants import (
+ classic as unfold_classic,
+ )
+
+ parameters = {
+ unfold_classic.Parameters.EVENT_TYPE: event_type,
+ unfold_classic.Parameters.OBJECT_TYPE: object_type,
+ unfold_classic.Parameters.QUALIFIERS: qualifiers,
+ }
+ return unfold_algorithm.apply(ocel, parameters=parameters)
+
+
+def ocel_fold(ocel: OCEL, event_type: str, object_type: str) -> OCEL:
+ """
+ Fold OLAP operation on an object-centric event log: collapses the
+ unfolded activity ``"(event_type, object_type)"`` back to
+ ``event_type``. Inverse of :func:`ocel_unfold`.
+
+ Reference: Khayatbashi, Miri, Jalali, "Advancing Object-Centric Process
+ Mining with Multi-Dimensional Data Operations", CAiSE Forum 2025
+ (arXiv:2412.00393).
+
+ :param ocel: Object-centric event log.
+ :type ocel: OCEL
+ :param event_type: Parent event type to merge back to.
+ :type event_type: str
+ :param object_type: Object type used during the matching unfold.
+ :type object_type: str
+ :return: A new OCEL with the folded event type.
+ :rtype: OCEL
+
+ .. code-block:: python3
+
+ import pm4py
+
+ folded = pm4py.ocel_fold(unfolded, "order test", "(Test, ECG)")
+ """
+ from pm4py.algo.transformation.ocel.olap.fold import (
+ algorithm as fold_algorithm,
+ )
+ from pm4py.algo.transformation.ocel.olap.fold.variants import (
+ classic as fold_classic,
+ )
+
+ parameters = {
+ fold_classic.Parameters.EVENT_TYPE: event_type,
+ fold_classic.Parameters.OBJECT_TYPE: object_type,
+ }
+ return fold_algorithm.apply(ocel, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/org.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/org.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7c77305686b715ce5294033c277f4028f221d08
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/org.py
@@ -0,0 +1,415 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+__doc__ = """
+The ``pm4py.org`` module contains organizational analysis techniques offered in ``pm4py``.
+"""
+
+from typing import Union
+
+import pandas as pd
+
+from pm4py.objects.log.obj import EventLog, EventStream
+from pm4py.util.pandas_utils import (
+ check_is_pandas_dataframe,
+ check_pandas_dataframe_columns,
+)
+from pm4py.utils import get_properties, __event_log_deprecation_warning
+from pm4py.objects.org.sna.obj import SNA
+from pm4py.objects.org.roles.obj import Role
+from pm4py.util import xes_constants
+from typing import Dict, Tuple, Any, List
+
+
+def discover_handover_of_work_network(
+ log: Union[EventLog, pd.DataFrame],
+ beta=0,
+ resource_key: str = "org:resource",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> SNA:
+ """
+ Calculates the handover of work network of the event log.
+
+ The handover of work network is essentially the Directly-Follows Graph (DFG) of the event log, but using the
+ resource as the nodes of the graph instead of activities.
+ As such, resource information should be present in the event log.
+
+ :param log: Event log or Pandas DataFrame.
+ :param beta: Beta parameter for the Handover metric.
+ :param resource_key: Attribute to be used for the resource.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ metric = pm4py.discover_handover_of_work_network(
+ dataframe,
+ beta=0,
+ resource_key='org:resource',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ from pm4py.algo.organizational_mining.sna import algorithm as sna
+
+ parameters = get_properties(
+ log,
+ resource_key=resource_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["beta"] = beta
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
+ )
+ return sna.apply(
+ log, variant=sna.Variants.HANDOVER_PANDAS, parameters=parameters
+ )
+ else:
+ return sna.apply(
+ log, variant=sna.Variants.HANDOVER_LOG, parameters=parameters
+ )
+
+
+def discover_working_together_network(
+ log: Union[EventLog, pd.DataFrame],
+ resource_key: str = "org:resource",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> SNA:
+ """
+ Calculates the working together network of the process.
+ Two resource nodes are connected in the graph if the resources collaborate on an instance of the process.
+
+ :param log: Event log or Pandas DataFrame.
+ :param resource_key: Attribute to be used for the resource.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ metric = pm4py.discover_working_together_network(
+ dataframe,
+ resource_key='org:resource',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ resource_key=resource_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.organizational_mining.sna import algorithm as sna
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
+ )
+ return sna.apply(
+ log,
+ variant=sna.Variants.WORKING_TOGETHER_PANDAS,
+ parameters=properties,
+ )
+ else:
+ return sna.apply(
+ log,
+ variant=sna.Variants.WORKING_TOGETHER_LOG,
+ parameters=properties,
+ )
+
+
+def discover_activity_based_resource_similarity(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ resource_key: str = "org:resource",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> SNA:
+ """
+ Calculates similarity between the resources in the event log based on their activity profiles.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity.
+ :param resource_key: Attribute to be used for the resource.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ act_res_sim = pm4py.discover_activity_based_resource_similarity(
+ dataframe,
+ resource_key='org:resource',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ resource_key=resource_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.organizational_mining.sna import algorithm as sna
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ return sna.apply(
+ log,
+ variant=sna.Variants.JOINTACTIVITIES_PANDAS,
+ parameters=properties,
+ )
+ else:
+ return sna.apply(
+ log,
+ variant=sna.Variants.JOINTACTIVITIES_LOG,
+ parameters=properties,
+ )
+
+
+def discover_subcontracting_network(
+ log: Union[EventLog, pd.DataFrame],
+ n=2,
+ resource_key: str = "org:resource",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> SNA:
+ """
+ Calculates the subcontracting network of the process.
+
+ :param log: Event log or Pandas DataFrame.
+ :param n: N parameter for the Subcontracting metric.
+ :param resource_key: Attribute to be used for the resource.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ metric = pm4py.discover_subcontracting_network(
+ dataframe,
+ n=2,
+ resource_key='org:resource',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ from pm4py.algo.organizational_mining.sna import algorithm as sna
+
+ parameters = get_properties(
+ log,
+ resource_key=resource_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ parameters["n"] = n
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
+ )
+ return sna.apply(
+ log,
+ variant=sna.Variants.SUBCONTRACTING_PANDAS,
+ parameters=parameters,
+ )
+ else:
+ return sna.apply(
+ log, variant=sna.Variants.SUBCONTRACTING_LOG, parameters=parameters
+ )
+
+
+def discover_organizational_roles(
+ log: Union[EventLog, pd.DataFrame],
+ activity_key: str = "concept:name",
+ resource_key: str = "org:resource",
+ timestamp_key: str = "time:timestamp",
+ case_id_key: str = "case:concept:name",
+) -> List[Role]:
+ """
+ Mines the organizational roles.
+
+ A role is a set of activities in the log that are executed by a similar (multi)set of resources. Hence, it is a specific function within the organization. Grouping the activities into roles can help:
+
+ Reference paper:
+ Burattin, Andrea, Alessandro Sperduti, and Marco Veluscek. “Business models enhancement through discovery of roles.” 2013 IEEE Symposium on Computational Intelligence and Data Mining (CIDM). IEEE, 2013.
+
+ :param log: Event log or Pandas DataFrame.
+ :param activity_key: Attribute to be used for the activity.
+ :param resource_key: Attribute to be used for the resource.
+ :param timestamp_key: Attribute to be used for the timestamp.
+ :param case_id_key: Attribute to be used as case identifier.
+
+ .. code-block:: python3
+
+ import pm4py
+
+ roles = pm4py.discover_organizational_roles(
+ dataframe,
+ resource_key='org:resource',
+ activity_key='concept:name',
+ timestamp_key='time:timestamp',
+ case_id_key='case:concept:name'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ properties = get_properties(
+ log,
+ activity_key=activity_key,
+ resource_key=resource_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+
+ from pm4py.algo.organizational_mining.roles import algorithm as roles
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(
+ log,
+ activity_key=activity_key,
+ timestamp_key=timestamp_key,
+ case_id_key=case_id_key,
+ )
+ return roles.apply(
+ log, variant=roles.Variants.PANDAS, parameters=properties
+ )
+ else:
+ return roles.apply(
+ log, variant=roles.Variants.LOG, parameters=properties
+ )
+
+
+def discover_network_analysis(
+ log: Union[pd.DataFrame, EventLog, EventStream],
+ out_column: str,
+ in_column: str,
+ node_column_source: str,
+ node_column_target: str,
+ edge_column: str,
+ edge_reference: str = "_out",
+ performance: bool = False,
+ sorting_column: str = xes_constants.DEFAULT_TIMESTAMP_KEY,
+ timestamp_column: str = xes_constants.DEFAULT_TIMESTAMP_KEY,
+) -> Dict[Tuple[str, str], Dict[str, Any]]:
+ """
+ Performs a network analysis of the log based on the provided parameters.
+
+ Classical social network analysis methods are based on the order of events within a case. For example, the Handover of Work metric considers the directly-follows relationships between resources during the execution of a case. An edge is added between two resources if such a relationship occurs.
+
+ Real-life scenarios may be more complicated. Firstly, it is difficult to collect events within the same case without encountering convergence/divergence issues (see the first section of the OCEL part). Secondly, the type of relationship may also be important. For example, the relationship between two resources may be more efficient if the activity executed is liked by the resources rather than disliked.
+
+ The network analysis introduced here generalizes some existing social network analysis metrics, making them independent of the case notion and allowing the construction of a multigraph instead of a simple graph.
+
+ We assume events are linked by signals. An event emits a signal (contained in one attribute of the event) that is assumed to be received by other events (also containing this attribute) that follow the first event in the log. We assume there is an OUT attribute (of the event) that is identical to the IN attribute (of the other events).
+
+ When collecting this information, we can build the network analysis graph:
+ - The source node of the relationship is determined by aggregating the `node_column_source` attribute.
+ - The target node of the relationship is determined by aggregating the `node_column_target` attribute.
+ - The type of edge is determined by aggregating the `edge_column` attribute.
+ - The network analysis graph can be annotated with frequency or performance information.
+
+ The output is a multigraph.
+ Two events EV1 and EV2 in the log are connected (independently of the case notion) based on having
+ EV1.OUT_COLUMN = EV2.IN_COLUMN.
+ Then, an aggregation is applied on the pair of events (NODE_COLUMN) to obtain the connected nodes.
+ The edges between these nodes are aggregated based on some property of the *source* event (`edge_column`).
+
+ :param log: Event log, Pandas DataFrame, or EventStream.
+ :param out_column: The source column of the link (default: the case identifier; events of the same case are linked).
+ :param in_column: The target column of the link (default: the case identifier; events of the same case are linked).
+ :param node_column_source: The attribute to be used for defining the source node (default: the resource of the log, "org:resource").
+ :param node_column_target: The attribute to be used for defining the target node (default: the resource of the log, "org:resource").
+ :param edge_column: The attribute to be used for defining the edge (default: the activity of the log, "concept:name").
+ :param edge_reference: Determines if the edge attribute should be picked from the source event. Values: "_out" => the source event; "_in" => the target event.
+ :param performance: Boolean value that enables performance calculation on the edges of the network analysis.
+ :param sorting_column: The column to be used for sorting the log before performing the network analysis (default: "time:timestamp").
+ :param timestamp_column: The column to be used as timestamp for performance-related analysis (default: "time:timestamp").
+ :rtype: ``Dict[Tuple[str, str], Dict[str, Any]]``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ net_ana = pm4py.discover_network_analysis(
+ dataframe,
+ out_column='case:concept:name',
+ in_column='case:concept:name',
+ node_column_source='org:resource',
+ node_column_target='org:resource',
+ edge_column='concept:name',
+ edge_reference='_out',
+ performance=False,
+ sorting_column='time:timestamp',
+ timestamp_column='time:timestamp'
+ )
+ """
+ __event_log_deprecation_warning(log)
+
+ if check_is_pandas_dataframe(log):
+ check_pandas_dataframe_columns(log)
+
+ from pm4py.algo.organizational_mining.network_analysis.variants import (
+ dataframe,
+ )
+
+ parameters = {}
+ parameters[dataframe.Parameters.OUT_COLUMN] = out_column
+ parameters[dataframe.Parameters.IN_COLUMN] = in_column
+ parameters[dataframe.Parameters.NODE_COLUMN_SOURCE] = node_column_source
+ parameters[dataframe.Parameters.NODE_COLUMN_TARGET] = node_column_target
+ parameters[dataframe.Parameters.EDGE_COLUMN] = edge_column
+ parameters[dataframe.Parameters.EDGE_REFERENCE] = edge_reference
+ parameters[dataframe.Parameters.SORTING_COLUMN] = sorting_column
+ parameters[dataframe.Parameters.TIMESTAMP_KEY] = timestamp_column
+ parameters[dataframe.Parameters.INCLUDE_PERFORMANCE] = performance
+
+ from pm4py.algo.organizational_mining.network_analysis import (
+ algorithm as network_analysis,
+ )
+
+ return network_analysis.apply(log, parameters=parameters)
diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/privacy.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/privacy.py
new file mode 100644
index 0000000000000000000000000000000000000000..8477eed5de0b27b65f8b79e88f480f760d18a827
--- /dev/null
+++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/privacy.py
@@ -0,0 +1,72 @@
+'''
+PM4Py – A Process Mining Library for Python
+Copyright (C) 2026 Process Intelligence Solutions GmbH
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see this software project's root or
+visit .
+
+Website: https://processintelligence.solutions
+Contact: info@processintelligence.solutions
+'''
+
+from pm4py.objects.log.obj import EventLog
+import pandas as pd
+from typing import Union
+
+
+def anonymize_differential_privacy(log: Union[EventLog, pd.DataFrame], epsilon: float = 1.0, k: int = 10, p: int = 20) -> pd.DataFrame:
+ """
+ Protect event logs with differential privacy. Differential privacy is a guarantee that bounds the impact the data of one individual has on a query result.
+
+ Control-flow information is anonymized with SaCoFa. This algorithm inserts noise into a trace-variant count, through the step-wise construction of a prefix tree.
+
+ Contextual-information, like timestamps or resources, is anonymized with PRIPEL. This technique enriches a control-flow anonymized event log with contextual information from the original log, while still achieving differential privacy.
+ PRIPEL anonymizes each event's timestamp and other attributes, that are stored as strings, integers, floats, or booleans.
+
+ Please install diffprivlib https://diffprivlib.readthedocs.io/en/latest/ (pip install diffprivlib==0.5.2) to run our algorithm.
+
+
+ SaCoFa is described in:
+ S. A. Fahrenkog-Petersen, M. Kabierski, F. Rösel, H. van der Aa and M. Weidlich, "SaCoFa: Semantics-aware
+ Control-flow Anonymization for Process Mining," 2021 3rd International Conference on Process Mining (ICPM), 2021,
+ pp. 72-79. https://doi.org/10.48550/arXiv.2109.08501
+
+ PRIPEL is described in:
+ Fahrenkrog-Petersen, S.A., van der Aa, H., Weidlich, M. (2020). PRIPEL: Privacy-Preserving Event Log Publishing
+ Including Contextual Information. In: Fahland, D., Ghidini, C., Becker, J., Dumas, M. (eds) Business Process
+ Management. BPM 2020. Lecture Notes in Computer Science, vol 12168. Springer, Cham.
+ https://doi.org/10.1007/978-3-030-58666-9_7
+
+
+ :param log: event log / Pandas dataframe
+ :param epsilon: the strength of the differential privacy guarantee. The smaller the value of epsilon, the stronger the privacy guarantee that is provided.
+ :param k: the maximal length of considered traces in the prefix tree. We recommend setting k, that roughly 80% of all traces from the original event log are covered.
+ :param p: the pruning parameter, which denotes the minimum count a prefix has to have in order to not be discarded. The dependent exponential runtime of the algorithms is mitigated by the pruning parameter.
+ :rtype: ``pd.DataFrame``
+
+ .. code-block:: python3
+
+ import pm4py
+
+ event_log = pm4py.read_xes("running-example.xes")
+ anonymized_event_log = pm4py.anonymize_differential_privacy(event_log, epsilon=1.0, k=10, p=20)
+ """
+
+ from pm4py.algo.anonymization.trace_variant_query import algorithm as trace_variant_query
+ sacofa_result = trace_variant_query.apply(log=log, variant=trace_variant_query.Variants.SACOFA, parameters={"epsilon": epsilon, "k": k, "p": p})
+
+ from pm4py.algo.anonymization.pripel import algorithm as pripel
+ anonymized_log = pripel.apply(log, sacofa_result, epsilon=epsilon)
+
+ return anonymized_log