diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/pandas.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..cd5640ba5380036c3499fcff24140ae0ff2bcdc4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/pandas.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 +''' +from enum import Enum +from typing import Optional, Dict, Any, List, Tuple, Union + +import pandas as pd + +from pm4py.algo.discovery.batches.utils import detection +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils +import numpy as np + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + RESOURCE_KEY = constants.PARAMETER_CONSTANT_RESOURCE_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 + EVENT_ID_KEY = "event_id_key" + MERGE_DISTANCE = "merge_distance" + MIN_BATCH_SIZE = "min_batch_size" + + +def apply( + log: pd.DataFrame, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> List[Tuple[Tuple[str, str], int, Dict[str, Any]]]: + """ + Provided a Pandas dataframe, returns. + + a list having as elements the activity-resources with the batches that are detected, divided in: + + - Simultaneous (all the events in the batch have identical start and end timestamps) + - Batching at start (all the events in the batch have identical start timestamp) + - Batching at end (all the events in the batch have identical end timestamp) + - Sequential batching (for all the consecutive events, the end of the first is equal to the start of the second) + - Concurrent batching (for all the consecutive events that are not sequentially matched) + + The approach has been described in the following 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). + + Parameters + ---------- + log + Dataframe + parameters + Parameters of the algorithm: + + - ACTIVITY_KEY => the attribute that should be used as activity + - RESOURCE_KEY => the attribute that should be used as resource + - START_TIMESTAMP_KEY => the attribute that should be used as start timestamp + - TIMESTAMP_KEY => the attribute that should be used as timestamp + - CASE_ID_KEY => the attribute that should be used as case identifier + - MERGE_DISTANCE => the maximum time distance between non-overlapping intervals in order for them to be considered belonging to the same batch (default: 15*60 15 minutes) + - MIN_BATCH_SIZE => the minimum number of events for a batch to be considered (default: 2) + + Returns + ----------------- + list_batches + A (sorted) list containing tuples. Each tuple contain: + + - Index 0: the activity-resource for which at least one batch has been detected + - Index 1: the number of batches for the given activity-resource + - Index 2: a list containing all the batches. Each batch is described by: # The start timestamp of the batch + + * The start timestamp of the batch + * The complete timestamp of the batch + * The list of events that are executed in the batch + + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + resource_key = exec_utils.get_param_value( + Parameters.RESOURCE_KEY, parameters, xes_constants.DEFAULT_RESOURCE_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, parameters, timestamp_key + ) + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + event_id_key = exec_utils.get_param_value( + Parameters.EVENT_ID_KEY, parameters, constants.DEFAULT_INDEX_KEY + ) + + attributes_to_consider = { + activity_key, + resource_key, + start_timestamp_key, + timestamp_key, + case_id_key, + } + log_contains_evidkey = event_id_key in log + if log_contains_evidkey: + attributes_to_consider.add(event_id_key) + + log = log[list(attributes_to_consider)] + # the timestamp columns are expressed in nanoseconds values + # here, we want them to have the second granularity, so we divide by 10**9 + # for example 1001000000 nanoseconds (value stored in the column) + # is equivalent to 1,001 seconds. + log[timestamp_key] = pandas_utils.convert_to_seconds(log[timestamp_key]) + if start_timestamp_key != timestamp_key: + # see the aforementioned explanation. + log[start_timestamp_key] = pandas_utils.convert_to_seconds( + log[start_timestamp_key] + ) + + actres_grouping0 = ( + log.groupby([activity_key, resource_key]).agg(list).to_dict() + ) + start_timestamps = actres_grouping0[start_timestamp_key] + complete_timestamps = actres_grouping0[timestamp_key] + cases = actres_grouping0[case_id_key] + if log_contains_evidkey: + events_ids = actres_grouping0[event_id_key] + + actres_grouping = {} + for k in start_timestamps: + st = start_timestamps[k] + et = complete_timestamps[k] + c = cases[k] + if log_contains_evidkey: + eid = events_ids[k] + actres_grouping_k = [] + for i in range(len(st)): + if log_contains_evidkey: + actres_grouping_k.append((st[i], et[i], c[i], eid[i])) + else: + actres_grouping_k.append((st[i], et[i], c[i])) + actres_grouping[k] = actres_grouping_k + + return detection.detect(actres_grouping, parameters=parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/polars.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/polars.py new file mode 100644 index 0000000000000000000000000000000000000000..f8379362da8b9f2cf0421ca2ae491ff576d14994 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/polars.py @@ -0,0 +1,175 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, Union + +import polars as pl + +from pm4py.algo.discovery.batches.utils import detection +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + RESOURCE_KEY = constants.PARAMETER_CONSTANT_RESOURCE_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 + EVENT_ID_KEY = "event_id_key" + MERGE_DISTANCE = "merge_distance" + MIN_BATCH_SIZE = "min_batch_size" + + +def _to_seconds_expr(column_name: str, schema: Dict[str, Any]) -> pl.Expr: + expr = pl.col(column_name) + dtype_repr = str(schema[column_name]).lower() + if "date" in dtype_repr or "time" in dtype_repr: + return ( + expr.dt.cast_time_unit("ns") + .dt.timestamp("ns") + .cast(pl.Float64) + / 1_000_000_000 + ) + if any(token in dtype_repr for token in ("int", "float")): + return expr.cast(pl.Float64) + raise Exception( + f"Column '{column_name}' must be temporal or numeric to evaluate seconds." + ) + + +def apply( + log: pl.LazyFrame, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> List[Tuple[Tuple[str, str], int, Dict[str, Any]]]: + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + resource_key = exec_utils.get_param_value( + Parameters.RESOURCE_KEY, parameters, xes_constants.DEFAULT_RESOURCE_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, parameters, timestamp_key + ) + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + event_id_key = exec_utils.get_param_value( + Parameters.EVENT_ID_KEY, parameters, constants.DEFAULT_INDEX_KEY + ) + + pandas_utils.check_pandas_dataframe_columns( + log, + activity_key=activity_key, + case_id_key=case_id_key, + timestamp_key=timestamp_key, + start_timestamp_key=start_timestamp_key, + ) + + schema = log.collect_schema() + attributes = [ + activity_key, + resource_key, + start_timestamp_key, + timestamp_key, + case_id_key, + ] + log_contains_evidkey = event_id_key in schema + if log_contains_evidkey: + attributes.append(event_id_key) + + # ensure attribute order without duplicates + seen = set() + ordered_attributes: List[str] = [] + for attr in attributes: + if attr not in seen: + seen.add(attr) + ordered_attributes.append(attr) + + lf = log.select([pl.col(col) for col in ordered_attributes]) + + lf = lf.with_columns( + [ + _to_seconds_expr(start_timestamp_key, schema).alias("__pm4py_start_sec__"), + _to_seconds_expr(timestamp_key, schema).alias("__pm4py_complete_sec__"), + ] + ) + + lf = lf.with_row_index("__pm4py_order__") + + aggregation_exprs = [ + pl.col("__pm4py_start_sec__") + .sort_by("__pm4py_order__") + .alias("__pm4py_start__"), + pl.col("__pm4py_complete_sec__") + .sort_by("__pm4py_order__") + .alias("__pm4py_complete__"), + pl.col(case_id_key) + .sort_by("__pm4py_order__") + .alias("__pm4py_cases__"), + ] + + if log_contains_evidkey: + aggregation_exprs.append( + pl.col(event_id_key) + .sort_by("__pm4py_order__") + .alias("__pm4py_events__") + ) + + grouped = ( + lf.group_by(activity_key, resource_key, maintain_order=True) + .agg(aggregation_exprs) + .collect() + ) + + actres_grouping: Dict[Tuple[str, str], List[Tuple[Any, ...]]] = {} + + for row in grouped.iter_rows(named=True): + key = (row[activity_key], row[resource_key]) + starts = list(row["__pm4py_start__"]) + completes = list(row["__pm4py_complete__"]) + cases = list(row["__pm4py_cases__"]) + events_list = ( + list(row["__pm4py_events__"]) + if log_contains_evidkey + else None + ) + + batches = [] + for idx in range(len(starts)): + entry: Tuple[Any, ...] + if log_contains_evidkey and events_list is not None: + entry = (starts[idx], completes[idx], cases[idx], events_list[idx]) + else: + entry = (starts[idx], completes[idx], cases[idx]) + batches.append(entry) + + actres_grouping[key] = batches + + return detection.detect(actres_grouping, parameters=parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/test.rst b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/test.rst new file mode 100644 index 0000000000000000000000000000000000000000..396363f75eaadb43dc3929f447c3f0a955b49ad7 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/batches/variants/test.rst @@ -0,0 +1,41 @@ +Discovers an Heuristics Net using Heuristics Miner. + +Parameters +---------- +dfg + Directly-Follows Graph +activities + (If provided) list of activities of the log +activities_occurrences + (If provided) dictionary of activities occurrences +start_activities + (If provided) dictionary of start activities occurrences +end_activities + (If provided) dictionary of end activities occurrences +parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + +variant + Variant of the algorithm: + + - Variants.CLASSIC + +Returns +------------ +net + Petri net +im + Initial marking +fm + Final marking \ No newline at end of file diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da1847bf8a4a091cc7a25efbdfb8f6a99a1b4610 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/__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.discovery.causal import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..03f4f8921cd45ca8b9741b0f853def2c5c34b7da --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/algorithm.py @@ -0,0 +1,59 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.causal.variants import alpha, heuristic +from enum import Enum +from pm4py.util import exec_utils +from typing import Dict, Tuple + + +class Variants(Enum): + CAUSAL_ALPHA = alpha + CAUSAL_HEURISTIC = heuristic + + +CAUSAL_ALPHA = Variants.CAUSAL_ALPHA +CAUSAL_HEURISTIC = Variants.CAUSAL_HEURISTIC + +VERSIONS = {CAUSAL_ALPHA, CAUSAL_HEURISTIC} + + +def apply( + dfg: Dict[Tuple[str, str], int], variant=CAUSAL_ALPHA +) -> Dict[Tuple[str, str], int]: + """ + Computes the causal relation on the basis of a given directly follows graph. + + Parameters + ----------- + dfg + Directly follows graph + variant + Variant of the algorithm to use: + - Variants.CAUSAL_ALPHA + - Variants.CAUSAL_HEURISTIC + + Returns + ----------- + causal relations + dict + """ + return exec_utils.get_variant(variant).apply(dfg) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d9fd0d2174447195449cb12c951f7d3359e3ce6c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/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.algo.discovery.causal.variants import alpha, heuristic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/alpha.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/alpha.py new file mode 100644 index 0000000000000000000000000000000000000000..a2deafce42b373341a5799c2aaefcb74251c9d04 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/alpha.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, Tuple + + +def apply(dfg: Dict[Tuple[str, str], int]) -> Dict[Tuple[str, str], int]: + """ + Computes a causal graph based on a directly follows graph according to the alpha miner + + Parameters + ---------- + dfg: :class:`dict` directly follows relation, should be a dict of the form (activity,activity) -> num of occ. + + Returns + ------- + causal_relation: :class:`dict` containing all causal relations as keys (with value 1 indicating that it holds) + """ + causal_alpha = {} + for f, t in dfg: + if dfg[(f, t)] > 0: + if (t, f) not in dfg: + causal_alpha[(f, t)] = 1 + elif dfg[(t, f)] == 0: + causal_alpha[(f, t)] = 1 + return causal_alpha diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/heuristic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/heuristic.py new file mode 100644 index 0000000000000000000000000000000000000000..66638d5a8f9a58b73d05de66874a259648baf08a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/causal/variants/heuristic.py @@ -0,0 +1,46 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 + + +def apply(dfg: Dict[Tuple[str, str], int]) -> Dict[Tuple[str, str], float]: + """ + Computes a causal graph based on a directly follows graph according to the heuristics miner + + Parameters + ---------- + dfg: :class:`dict` directly follows relation, should be a dict of the form (activity,activity) -> num of occ. + + Returns + ------- + :return: dictionary containing all causal relations as keys (with value inbetween -1 and 1 indicating that + how strong it holds) + """ + causal_heur = {} + for f, t in dfg: + if (f, t) not in causal_heur: + rev = dfg[(t, f)] if (t, f) in dfg else 0 + causal_heur[(f, t)] = float( + (dfg[(f, t)] - rev) / (dfg[(f, t)] + rev + 1) + ) + causal_heur[(t, f)] = -1 * causal_heur[(f, t)] + return causal_heur diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07d3838cadc7833c9ae70be6686361f245bf6635 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/__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.discovery.correlation_mining import variants, algorithm, util diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..997f129be7d97f67c68b0e3a489c45b216353e02 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/algorithm.py @@ -0,0 +1,75 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.correlation_mining.variants import ( + classic_split, + classic, + trace_based, +) +from pm4py.util import exec_utils +from enum import Enum +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd + + +class Variants(Enum): + CLASSIC_SPLIT = classic_split + CLASSIC = classic + TRACE_BASED = trace_based + + +DEFAULT_VARIANT = Variants.CLASSIC + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + variant=DEFAULT_VARIANT, + parameters: Optional[Dict[Any, Any]] = None, +) -> Tuple[Dict[Tuple[str, str], int], Dict[Tuple[str, str], float]]: + """ + Applies the Correlation Miner to the event stream (a log is converted to a stream) + + 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. + + Parameters + ------------- + log + Log object + variant + Variant of the algorithm to use + parameters + Parameters of the algorithm + + Returns + -------------- + dfg + Directly-follows graph + performance_dfg + Performance DFG (containing the estimated performance for the arcs) + """ + if parameters is None: + parameters = {} + + return exec_utils.get_variant(variant).apply(log, parameters=parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/util.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/util.py new file mode 100644 index 0000000000000000000000000000000000000000..7925eee5b55e38c21ebdaf98e8bbe9f1e43ad0d6 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/util.py @@ -0,0 +1,308 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 + + +def get_c_matrix(PS_matrix, duration_matrix, activities, activities_counter): + """ + Calculates the C-matrix out of the PS matrix and the duration matrix + + Parameters + -------------- + PS_matrix + PS matrix + duration_matrix + Duration matrix + activities + Ordered list of activities of the log + activities_counter + Counter of activities + + Returns + -------------- + c_matrix + C matrix + """ + C_matrix = np.zeros((len(activities), len(activities))) + for i in range(len(activities)): + for j in range(len(activities)): + val = ( + duration_matrix[i, j] + / PS_matrix[i, j] + * 1 + / ( + min( + activities_counter[activities[i]], + activities_counter[activities[j]], + ) + ) + if PS_matrix[i, j] > 0 + else 0 + ) + if val == 0: + val = 100000000000 + C_matrix[i, j] = val + return C_matrix + + +def resolve_LP(C_matrix, duration_matrix, activities, activities_counter): + """ + Formulates and solve the LP problem + + Parameters + -------------- + C_matrix + C_matrix + duration_matrix + Duration matrix + activities + Ordered list of activities of the log + activities_counter + Counter of activities + + Returns + ------------- + dfg + Directly-Follows Graph + performance_dfg + Performance DFG (containing the estimated performance for the arcs) + """ + edges = [ + (i, j) for i in range(len(activities)) for j in range(len(activities)) + ] + c = [ + C_matrix[i, j] + for i in range(len(activities)) + for j in range(len(activities)) + ] + edges_sources = { + i: [z for z in range(len(edges)) if edges[z][0] == i] + for i in range(len(activities)) + } + edges_targets = { + j: [z for z in range(len(edges)) if edges[z][1] == j] + for j in range(len(activities)) + } + activities_occurrences = { + i: activities_counter[activities[i]] for i in range(len(activities)) + } + Aeq = [] + beq = [] + for i in range(len(activities)): + rec = [0] * len(edges) + for e in edges_sources[i]: + rec[e] = 1 + Aeq.append(rec) + beq.append(activities_occurrences[i]) + for j in range(len(activities)): + rec = [0] * len(edges) + for e in edges_targets[j]: + rec[e] = 1 + Aeq.append(rec) + beq.append(activities_occurrences[j]) + Aeq = np.asmatrix(Aeq).astype(np.float64) + beq = np.asmatrix(beq).transpose().astype(np.float64) + Aub = [] + bub = [] + for i in range(len(activities)): + for e in edges_sources[i]: + rec = [0] * len(edges) + rec[e] = 1 + Aub.append(rec) + bub.append(activities_occurrences[i]) + rec = [-x for x in rec] + Aub.append(rec) + bub.append(0) + for j in range(len(activities)): + for e in edges_targets[j]: + rec = [0] * len(edges) + rec[e] = 1 + Aub.append(rec) + bub.append(activities_occurrences[j]) + rec = [-x for x in rec] + Aub.append(rec) + bub.append(0) + Aub = np.asmatrix(Aub).astype(np.float64) + bub = np.asmatrix(bub).transpose().astype(np.float64) + + use_cvxopt = False + if ( + solver.DEFAULT_LP_SOLVER_VARIANT == solver.CVXOPT_SOLVER_CUSTOM_ALIGN + or solver.DEFAULT_LP_SOLVER_VARIANT + == solver.CVXOPT_SOLVER_CUSTOM_ALIGN_ILP + ): + use_cvxopt = True + + if use_cvxopt: + from cvxopt import matrix + + c = matrix(c) + Aub = matrix(Aub) + bub = matrix(bub) + Aeq = matrix(Aeq) + beq = matrix(beq) + + res = solver.apply( + c, Aub, bub, Aeq, beq, variant=solver.DEFAULT_LP_SOLVER_VARIANT + ) + points = solver.get_points_from_sol( + res, variant=solver.DEFAULT_LP_SOLVER_VARIANT + ) + points = [round(p) for p in points] + + dfg = {} + performance_dfg = {} + + for idx, p in enumerate(points): + if p > 0: + dfg[(activities[edges[idx][0]], activities[edges[idx][1]])] = p + performance_dfg[ + (activities[edges[idx][0]], activities[edges[idx][1]]) + ] = duration_matrix[edges[idx][0], edges[idx][1]] + return dfg, performance_dfg + + +def match_return_avg_time(ai, aj, exact=False): + """ + Matches two list of times (exact or greedy) + and returns the average. + + Parameters + -------------- + ai + First list + aj + Second list + + Returns + --------------- + times_mean + Mean of times + """ + from statistics import mean + + if exact: + from pm4py.statistics.util import times_bipartite_matching + + matching = times_bipartite_matching.exact_match_minimum_average(ai, aj) + ret_exact = mean([x[1] - x[0] for x in matching]) if matching else 0 + return ret_exact + else: + ret_greedy = greedy_match_return_avg_time(ai, aj) + return ret_greedy + + +def greedy_match_return_avg_time(ai, aj): + """ + Matches two list of times with a greedy method + and returns the average. + + Parameters + -------------- + ai + First list + aj + Second list + parameters + Parameters of the algorithm + + Returns + --------------- + times_mean + Mean of times + """ + from statistics import mean + + tm0 = calculate_time_match_fifo(ai, aj) + td0 = mean([x[1] - x[0] for x in tm0]) if tm0 else 0 + tm1 = calculate_time_match_rlifo(ai, aj) + td1 = mean([x[1] - x[0] for x in tm1]) if tm1 else 0 + return min(td0, td1) + + +def calculate_time_match_fifo(ai, aj, times0=None): + """ + Associate the times between + two lists of timestamps using FIFO + + Parameters + -------------- + ai + First list of timestamps + aj + Second list of timestamps + times0 + Correspondence between execution times + + Returns + -------------- + times0 + Correspondence between execution times + """ + if times0 is None: + times0 = [] + k = 0 + z = 0 + while k < len(ai): + while z < len(aj): + if ai[k] < aj[z]: + times0.append((ai[k], aj[z])) + z = z + 1 + break + z = z + 1 + k = k + 1 + return times0 + + +def calculate_time_match_rlifo(ai, aj, times1=None): + """ + Associate the times between + two lists of timestamps using LIFO (start from end) + + Parameters + -------------- + ai + First list of timestamps + aj + Second list of timestamps + times0 + Correspondence between execution times + + Returns + -------------- + times0 + Correspondence between execution times + """ + if times1 is None: + times1 = [] + k = len(ai) - 1 + z = len(aj) - 1 + while z >= 0: + while k >= 0: + if ai[k] < aj[z]: + times1.append((ai[k], aj[z])) + k = k - 1 + break + k = k - 1 + z = z - 1 + return times1 diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb8134bf2ce11b3b05679d0115b8206af81440d --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/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.algo.discovery.correlation_mining.variants import ( + classic_split, + classic, + trace_based, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..198c13de1fc5fdb099d8b325048dd9a92b0b64a2 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/classic.py @@ -0,0 +1,347 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 pm4py.util import constants, xes_constants, pandas_utils +from pm4py.objects.conversion.log import converter +from pm4py.objects.log.obj import Event +from pm4py.algo.discovery.correlation_mining import util as cm_util +import numpy as np +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream +from pm4py.utils import is_polars_lazyframe +import pandas as pd + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY + START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY + EXACT_TIME_MATCHING = "exact_time_matching" + INDEX_KEY = "index_key" + + +DEFAULT_INDEX_KEY = "@@@index" + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Tuple[Dict[Tuple[str, str], int], Dict[Tuple[str, str], float]]: + """ + Apply the correlation miner to an event stream + (other types of logs are converted to that) + + 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. + + Parameters + --------------- + log + Log object + parameters + Parameters of the algorithm + + Returns + --------------- + dfg + DFG + performance_dfg + Performance DFG (containing the estimated performance for the arcs) + """ + if parameters is None: + parameters = {} + + transf_stream, activities_grouped, activities = preprocess_log( + log, parameters=parameters + ) + + PS_matrix, duration_matrix = get_PS_dur_matrix( + activities_grouped, activities, parameters=parameters + ) + activities_counter = {x: len(y) for x, y in activities_grouped.items()} + + return resolve_lp_get_dfg( + PS_matrix, duration_matrix, activities, activities_counter + ) + + +def resolve_lp_get_dfg( + PS_matrix, duration_matrix, activities, activities_counter +): + """ + Resolves a LP problem to get a DFG + + Parameters + -------------- + PS_matrix + Precede-succeed matrix + duration_matrix + Duration matrix + activities + List of activities of the log + activities_counter + Counter of the activities + + Returns + -------------- + dfg + DFG + performance_dfg + Performance DFG (containing the estimated performance for the arcs) + """ + C_matrix = cm_util.get_c_matrix( + PS_matrix, duration_matrix, activities, activities_counter + ) + dfg, performance_dfg = cm_util.resolve_LP( + C_matrix, duration_matrix, activities, activities_counter + ) + return dfg, performance_dfg + + +def get_PS_dur_matrix(activities_grouped, activities, parameters=None): + """ + Combined methods to get the two matrixes + + Parameters + ---------------- + activities_grouped + Grouped activities + activities + List of activities of the log + parameters + Parameters of the algorithm + + Returns + --------------- + PS_matrix + Precede-succeed matrix + duration_matrix + Duration matrix + """ + if parameters is None: + parameters = {} + + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + exact_time_matching = exec_utils.get_param_value( + Parameters.EXACT_TIME_MATCHING, parameters, False + ) + + PS_matrix = get_precede_succeed_matrix( + activities, activities_grouped, timestamp_key, start_timestamp_key + ) + duration_matrix = get_duration_matrix( + activities, + activities_grouped, + timestamp_key, + start_timestamp_key, + exact=exact_time_matching, + ) + + return PS_matrix, duration_matrix + + +def preprocess_log(log, activities=None, parameters=None): + """ + Preprocess a log to enable correlation mining + + Parameters + -------------- + log + Log object + activities + (if provided) list of activities of the log + parameters + Parameters of the algorithm + + Returns + -------------- + transf_stream + Transformed stream + activities_grouped + Grouped activities + activities + List of activities of the 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, + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + index_key = exec_utils.get_param_value( + Parameters.INDEX_KEY, parameters, DEFAULT_INDEX_KEY + ) + + if pandas_utils.check_is_pandas_dataframe(log): + if not is_polars_lazyframe(log): + # keep only the two columns before conversion + log = log[ + list(set([activity_key, timestamp_key, start_timestamp_key])) + ] + + parameters["deepcopy"] = False + parameters["include_case_attributes"] = False + log = converter.apply( + log, variant=converter.TO_EVENT_STREAM, parameters=parameters + ) + transf_stream = EventStream() + for idx, ev in enumerate(log): + transf_stream.append( + Event( + { + activity_key: ev[activity_key], + timestamp_key: ev[timestamp_key].timestamp(), + start_timestamp_key: ev[start_timestamp_key].timestamp(), + index_key: idx, + } + ) + ) + transf_stream = sorted( + transf_stream, + key=lambda x: (x[start_timestamp_key], x[timestamp_key], x[index_key]), + ) + + if activities is None: + activities = sorted(list(set(x[activity_key] for x in transf_stream))) + + activities_grouped = { + x: [y for y in transf_stream if y[activity_key] == x] + for x in activities + } + + return transf_stream, activities_grouped, activities + + +def get_precede_succeed_matrix( + activities, activities_grouped, timestamp_key, start_timestamp_key +): + """ + Calculates the precede succeed matrix + + Parameters + --------------- + activities + Ordered list of activities of the log + activities_grouped + Grouped list of activities + timestamp_key + Timestamp key + start_timestamp_key + Start timestamp key (events start) + + Returns + --------------- + precede_succeed_matrix + Precede succeed matrix + """ + ret = np.zeros((len(activities), len(activities))) + for i in range(len(activities)): + ai = [x[timestamp_key] for x in activities_grouped[activities[i]]] + if ai: + for j in range(len(activities)): + if not i == j: + aj = [ + x[start_timestamp_key] + for x in activities_grouped[activities[j]] + ] + if aj: + k = 0 + z = 0 + count = 0 + while k < len(ai): + while z < len(aj): + if ai[k] < aj[z]: + break + z = z + 1 + count = count + (len(aj) - z) + k = k + 1 + ret[i, j] = count / float(len(ai) * len(aj)) + + return ret + + +def get_duration_matrix( + activities, + activities_grouped, + timestamp_key, + start_timestamp_key, + exact=False, +): + """ + Calculates the duration matrix + + Parameters + --------------- + activities + Ordered list of activities of the log + activities_grouped + Grouped list of activities + timestamp_key + Timestamp key + start_timestamp_key + Start timestamp key (events start) + exact + Performs an exact matching of the times (True/False) + + Returns + --------------- + duration_matrix + Duration matrix + """ + # greedy algorithm + ret = np.zeros((len(activities), len(activities))) + for i in range(len(activities)): + ai = [x[timestamp_key] for x in activities_grouped[activities[i]]] + if ai: + for j in range(len(activities)): + if not i == j: + aj = [ + x[start_timestamp_key] + for x in activities_grouped[activities[j]] + ] + if aj: + ret[i, j] = cm_util.match_return_avg_time( + ai, aj, exact=exact + ) + return ret diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/classic_split.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/classic_split.py new file mode 100644 index 0000000000000000000000000000000000000000..fd3774cdff43d1a1250b686f2e2e174c93a9c47d --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/classic_split.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 exec_utils +from enum import Enum +from pm4py.util import constants, xes_constants, pandas_utils +from pm4py.objects.conversion.log import converter +from pm4py.algo.discovery.correlation_mining.variants import classic +from collections import Counter +import numpy as np +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream +from pm4py.utils import is_polars_lazyframe +import pandas as pd +import importlib.util + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY + START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY + SAMPLE_SIZE = "sample_size" + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Tuple[Dict[Tuple[str, str], int], Dict[Tuple[str, str], float]]: + """ + Applies the correlation miner (splits the log in smaller chunks) + + Parameters + --------------- + log + Log object + parameters + Parameters of the algorithm + + Returns + --------------- + dfg + Frequency DFG + performance_dfg + Performance DFG + """ + 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, + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + sample_size = exec_utils.get_param_value( + Parameters.SAMPLE_SIZE, parameters, 100000 + ) + + PS_matrixes = [] + duration_matrixes = [] + + if pandas_utils.check_is_pandas_dataframe(log): + if is_polars_lazyframe(log): + 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] + + required_columns = list( + {activity_key, timestamp_key, start_timestamp_key} + ) + missing_columns = [ + col for col in required_columns if col not in log.columns + ] + if missing_columns: + raise Exception( + "The provided Polars LazyFrame does not contain the following required columns: " + + ", ".join(sorted(missing_columns)) + ) + + activities_counter = ( + log.group_by(activity_key) + .agg(pl.len().alias("__pm4py_count__")) + .collect() + ) + activities_counter = { + row[activity_key]: row["__pm4py_count__"] + for row in activities_counter.iter_rows(named=True) + } + activities = sorted(list(activities_counter.keys())) + + log = ( + log.select(required_columns) + .sort([timestamp_key, start_timestamp_key], maintain_order=True) + .collect() + .to_pandas() + ) + else: + # code for Pandas dataframes + log = log[ + list(set([activity_key, timestamp_key, start_timestamp_key])) + ] + log = log.sort_values([timestamp_key, start_timestamp_key]) + activities_counter = log[activity_key].value_counts().to_dict() + activities = sorted(list(activities_counter.keys())) + else: + log = converter.apply( + log, + variant=converter.Variants.TO_EVENT_STREAM, + parameters={"deepcopy": False, "include_case_attributes": False}, + ) + activities_counter = Counter(x[activity_key] for x in log) + activities = sorted(list(activities_counter.keys())) + + prev = 0 + while prev < len(log): + sample = log[prev: min(len(log), prev + sample_size)] + transf_stream, activities_grouped, activities = classic.preprocess_log( + sample, activities=activities, parameters=parameters + ) + PS_matrix, duration_matrix = classic.get_PS_dur_matrix( + activities_grouped, activities, parameters=parameters + ) + PS_matrixes.append(PS_matrix) + duration_matrixes.append(duration_matrix) + + prev = prev + sample_size + + PS_matrix = np.zeros((len(activities), len(activities))) + duration_matrix = np.zeros((len(activities), len(activities))) + z = 0 + while z < len(PS_matrixes): + PS_matrix = PS_matrix + PS_matrixes[z] + duration_matrix = np.maximum(duration_matrix, duration_matrixes[z]) + z = z + 1 + PS_matrix = PS_matrix / float(len(PS_matrixes)) + + return classic.resolve_lp_get_dfg( + PS_matrix, duration_matrix, activities, activities_counter + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/trace_based.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/trace_based.py new file mode 100644 index 0000000000000000000000000000000000000000..5528a0b34260ba793a69ac7dbdaa0af2ce37592b --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/correlation_mining/variants/trace_based.py @@ -0,0 +1,359 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 pm4py.util import constants, xes_constants, pandas_utils +from pm4py.objects.conversion.log import converter +from pm4py.algo.discovery.correlation_mining import util as cm_util +import numpy as np +from collections import Counter +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY + START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY + CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY + INDEX_KEY = "index_key" + + +DEFAULT_INDEX_KEY = "@@@index" + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Tuple[Dict[Tuple[str, str], int], Dict[Tuple[str, str], float]]: + """ + Novel approach of correlation mining, that creates the PS-matrix and the duration matrix + using the order list of events of each trace of the log + + Parameters + ------------- + log + Event log + parameters + Parameters + + Returns + --------------- + dfg + DFG + performance_dfg + Performance DFG (containing the estimated performance for the arcs) + """ + traces_list, trace_grouped_list, activities, activities_counter = ( + preprocess_log(log, activities=None, activities_counter=None) + ) + + PS_matrix, duration_matrix = get_PS_duration_matrix( + activities, trace_grouped_list, parameters=parameters + ) + + return resolve_lp_get_dfg( + PS_matrix, duration_matrix, activities, activities_counter + ) + + +def resolve_lp_get_dfg( + PS_matrix, duration_matrix, activities, activities_counter +): + """ + Resolves a LP problem to get a DFG + + Parameters + --------------- + PS_matrix + Precede-succeed matrix + duration_matrix + Duration matrix + activities + List of activities of the log + activities_counter + Counter for the activities of the log + + Returns + --------------- + dfg + Frequency DFG + performance_dfg + Performance DFG + """ + C_matrix = cm_util.get_c_matrix( + PS_matrix, duration_matrix, activities, activities_counter + ) + dfg, performance_dfg = cm_util.resolve_LP( + C_matrix, duration_matrix, activities, activities_counter + ) + return dfg, performance_dfg + + +def get_PS_duration_matrix(activities, trace_grouped_list, parameters=None): + """ + Gets the precede-succeed matrix + + Parameters + -------------- + activities + Activities + trace_grouped_list + Grouped list of simplified traces (per activity) + parameters + Parameters of the algorithm + + Returns + -------------- + PS_matrix + precede-succeed matrix + duration_matrix + Duration matrix + """ + if parameters is None: + parameters = {} + + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + + PS_matrix = get_precede_succeed_matrix( + activities, trace_grouped_list, timestamp_key, start_timestamp_key + ) + duration_matrix = get_duration_matrix( + activities, trace_grouped_list, timestamp_key, start_timestamp_key + ) + + return PS_matrix, duration_matrix + + +def preprocess_log( + log, activities=None, activities_counter=None, parameters=None +): + """ + Preprocess the log to get a grouped list of simplified traces (per activity) + + Parameters + -------------- + log + Log object + activities + (if provided) activities of the log + activities_counter + (if provided) counter of the activities of the log + parameters + Parameters of the algorithm + + Returns + -------------- + traces_list + List of simplified traces of the log + trace_grouped_list + Grouped list of simplified traces (per activity) + activities + Activities of the log + activities_counter + Activities counter + """ + 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, + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + caseid_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + index_key = exec_utils.get_param_value( + Parameters.INDEX_KEY, parameters, DEFAULT_INDEX_KEY + ) + + if pandas_utils.check_is_pandas_dataframe(log): + # keep only the two columns before conversion + log = log[ + list( + set( + [ + activity_key, + timestamp_key, + start_timestamp_key, + caseid_key, + ] + ) + ) + ] + + log = converter.apply( + log, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters + ) + + traces_list = [] + for trace in log: + trace_stream = [ + { + activity_key: trace[i][activity_key], + timestamp_key: trace[i][timestamp_key].timestamp(), + start_timestamp_key: trace[i][start_timestamp_key].timestamp(), + index_key: i, + } + for i in range(len(trace)) + ] + trace_stream = sorted( + trace_stream, + key=lambda x: ( + x[start_timestamp_key], + x[timestamp_key], + x[index_key], + ), + ) + traces_list.append(trace_stream) + + if activities is None: + activities = sorted( + list(set(y[activity_key] for x in traces_list for y in x)) + ) + + trace_grouped_list = [] + for trace in traces_list: + gr = [] + for act in activities: + act_gr = [x for x in trace if x[activity_key] == act] + gr.append(act_gr) + trace_grouped_list.append(gr) + + if activities_counter is None: + activities_counter = Counter( + y[activity_key] for x in traces_list for y in x + ) + + return traces_list, trace_grouped_list, activities, activities_counter + + +def get_precede_succeed_matrix( + activities, trace_grouped_list, timestamp_key, start_timestamp_key +): + """ + Calculates the precede succeed matrix + + Parameters + --------------- + activities + Sorted list of activities of the log + trace_grouped_list + A list of lists of lists, containing for each trace and each activity the events having such activity + timestamp_key + The key to be used as timestamp + start_timestamp_key + The key to be used as start timestamp + + Returns + --------------- + mat + The precede succeed matrix + """ + ret = np.zeros((len(activities), len(activities))) + for i in range(len(activities)): + for j in range(len(activities)): + if not i == j: + count = 0 + total = 0 + for tr in trace_grouped_list: + ai = [x[timestamp_key] for x in tr[i]] + aj = [x[start_timestamp_key] for x in tr[j]] + if ai and aj: + total += len(ai) * len(aj) + k = 0 + z = 0 + while k < len(ai): + while z < len(aj): + if ai[k] < aj[z]: + break + z = z + 1 + count = count + (len(aj) - z) + k = k + 1 + if total > 0: + ret[i, j] = count / float(total) + return ret + + +def get_duration_matrix( + activities, trace_grouped_list, timestamp_key, start_timestamp_key +): + """ + Calculates the duration matrix + + Parameters + -------------- + activities + Sorted list of activities of the log + trace_grouped_list + A list of lists of lists, containing for each trace and each activity the events having such activity + timestamp_key + The key to be used as timestamp + start_timestamp_key + The key to be used as start timestamp + + Returns + -------------- + mat + The duration matrix + """ + from statistics import mean + + ret = np.zeros((len(activities), len(activities))) + for i in range(len(activities)): + for j in range(len(activities)): + if not i == j: + tm0 = [] + tm1 = [] + for tr in trace_grouped_list: + ai = [x[timestamp_key] for x in tr[i]] + aj = [x[start_timestamp_key] for x in tr[j]] + if ai and aj: + tm0 = cm_util.calculate_time_match_fifo( + ai, aj, times0=tm0 + ) + tm1 = cm_util.calculate_time_match_rlifo( + ai, aj, times1=tm1 + ) + td0 = mean([x[1] - x[0] for x in tm0]) if tm0 else 0 + td1 = mean([x[1] - x[0] for x in tm1]) if tm1 else 0 + ret[i, j] = min(td0, td1) + return ret diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2dec7e0f3616c29734807465097d3b5fb7e0df03 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/__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.algo.discovery.declare import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9faed2dbd9375c8bebf4cd81f6eb43e26eef71 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/algorithm.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 +''' + +from pm4py.util import exec_utils +from enum import Enum +from pm4py.algo.discovery.declare.variants import classic +from pm4py.objects.log.obj import EventLog +import pandas as pd +from typing import Union, Dict, Optional, Any + + +class Variants(Enum): + CLASSIC = classic + + +def apply( + log: Union[EventLog, pd.DataFrame], + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Dict[Any, Dict[str, int]]]: + """ + Discovers a DECLARE model from the provided event log + + Parameters + --------------- + log + Log object (EventLog, Pandas dataframe) + variant + Variant of the algorithm to be used, including: + - Variants.CLASSIC + parameters + Variant-specific parameters + + Returns + --------------- + declare_model + DECLARE model (as Python dictionary), where each template is associated with its own rules + """ + return exec_utils.get_variant(variant).apply(log, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/templates.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/templates.py new file mode 100644 index 0000000000000000000000000000000000000000..341a7f9bce9d25a02c7166f3d80845fe343912e2 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/templates.py @@ -0,0 +1,40 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' + +EXISTENCE = "existence" +EXACTLY_ONE = "exactly_one" +INIT = "init" +RESPONDED_EXISTENCE = "responded_existence" +RESPONSE = "response" +PRECEDENCE = "precedence" +SUCCESSION = "succession" +ALTRESPONSE = "altresponse" +ALTPRECEDENCE = "altprecedence" +ALTSUCCESSION = "altsuccession" +CHAINRESPONSE = "chainresponse" +CHAINPRECEDENCE = "chainprecedence" +CHAINSUCCESSION = "chainsuccession" +ABSENCE = "absence" +COEXISTENCE = "coexistence" +NONCOEXISTENCE = "noncoexistence" +NONSUCCESSION = "nonsuccession" +NONCHAINSUCCESSION = "nonchainsuccession" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea7a2e9b24fceeb79465e040ec834efcff5a07e2 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/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.algo.discovery.declare.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..97088884f39a1a251454e0e77a3b5b23e9031b54 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/declare/variants/classic.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 +''' + +from enum import Enum +from pm4py.objects.log.obj import EventLog +from pm4py.algo.discovery.declare.templates import * +import pandas as pd +from typing import Union, Dict, Optional, Any, Tuple, Collection, Set, List +from typing import Counter as TCounter +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils +from collections import Counter +import numpy as np + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY + CONSIDERED_ACTIVITIES = "considered_activities" + MIN_SUPPORT_RATIO = "min_support_ratio" + MIN_CONFIDENCE_RATIO = "min_confidence_ratio" + AUTO_SELECTION_MULTIPLIER = "auto_selection_multiplier" + ALLOWED_TEMPLATES = "allowed_templates" + + +def __rule_existence_column(act: str) -> Tuple[str, str]: + return (EXISTENCE, act) + + +def __rule_exactly_one_column(act: str) -> Tuple[str, str]: + return (EXACTLY_ONE, act) + + +def __rule_init_column(act: str) -> Tuple[str, str]: + return (INIT, act) + + +def __rule_responded_existence_column(act: str, act2: str) -> Tuple[str, str, str]: + return (RESPONDED_EXISTENCE, act, act2) + + +def __rule_response(act: str, act2: str) -> Tuple[str, str, str]: + return (RESPONSE, act, act2) + + +def __rule_precedence(act: str, act2: str) -> Tuple[str, str, str]: + return (PRECEDENCE, act, act2) + + +def __rule_succession(act: str, act2: str) -> Tuple[str, str, str]: + return (SUCCESSION, act, act2) + + +def __rule_alternate_response(act: str, act2: str) -> Tuple[str, str, str]: + return (ALTRESPONSE, act, act2) + + +def __rule_alternate_precedence(act: str, act2: str) -> Tuple[str, str, str]: + return (ALTPRECEDENCE, act, act2) + + +def __rule_alternate_succession(act: str, act2: str) -> Tuple[str, str, str]: + return (ALTSUCCESSION, act, act2) + + +def __rule_chain_response(act: str, act2: str) -> Tuple[str, str, str]: + return (CHAINRESPONSE, act, act2) + + +def __rule_chain_precedence(act: str, act2: str) -> Tuple[str, str, str]: + return (CHAINPRECEDENCE, act, act2) + + +def __rule_chain_succession(act: str, act2: str) -> Tuple[str, str, str]: + return (CHAINSUCCESSION, act, act2) + + +def __rule_absence_act(act: str) -> Tuple[str, str]: + return (ABSENCE, act) + + +def __rule_coexistence(act: str, act2: str) -> Tuple[str, str, str]: + return (COEXISTENCE, act, act2) + + +def __rule_non_coexistence(act: str, act2: str) -> Tuple[str, str, str]: + return (NONCOEXISTENCE, act, act2) + + +def __rule_non_succession(act: str, act2: str) -> Tuple[str, str, str]: + return (NONSUCCESSION, act, act2) + + +def __rule_non_chain_succession(act: str, act2: str) -> Tuple[str, str, str]: + return (NONCHAINSUCCESSION, act, act2) + + +def __col_to_dict_rule( + col_name: Union[Tuple[str, str], Tuple[str, str, str]] +) -> Tuple[str, Any]: + if len(col_name) == 2: + return col_name[0], col_name[1] + else: + if col_name[2] is None or pd.isna(col_name[2]) or not col_name[2]: + return col_name[0], col_name[1] + return col_name[0], (col_name[1], col_name[2]) + + +def __table_nrows(table: Dict[Any, Any]) -> int: + if not table: + return 0 + return int(len(next(iter(table.values())))) + + +def __is_alternate_response_satisfied( + trace_len: int, act_idxs: Dict[str, List[int]], act: str, act2: str +) -> bool: + """ + Alternate response(act, act2): + for each occurrence of act, there exists an occurrence of act2 AFTER it, + and BEFORE the next occurrence of act (if any). + Extra act2 occurrences are allowed. + """ + a_idxs = act_idxs.get(act, []) + if not a_idxs: + return True # vacuous (not activated) + b_idxs = act_idxs.get(act2, []) + if not b_idxs: + return False + + b_ptr = 0 + for i, a in enumerate(a_idxs): + next_a = a_idxs[i + 1] if i + 1 < len(a_idxs) else trace_len + while b_ptr < len(b_idxs) and b_idxs[b_ptr] <= a: + b_ptr += 1 + if b_ptr >= len(b_idxs) or b_idxs[b_ptr] >= next_a: + return False + return True + + +def __is_chain_response_satisfied( + trace: Collection[str], act_idxs: Dict[str, List[int]], act: str, act2: str +) -> bool: + """ + Chain response(act, act2): + for each occurrence of act, act2 occurs IMMEDIATELY after. + Extra act2 occurrences are allowed. + """ + a_idxs = act_idxs.get(act, []) + if not a_idxs: + return True # vacuous (not activated) + + trace_list = list(trace) + n = len(trace_list) + for a in a_idxs: + if a + 1 >= n or trace_list[a + 1] != act2: + return False + return True + + +def __is_alternate_precedence_satisfied( + act_idxs: Dict[str, List[int]], act: str, act2: str +) -> bool: + """ + Alternate precedence(act, act2): + for each occurrence of act2, there exists an occurrence of act BEFORE it, + and AFTER the previous occurrence of act2 (if any). + Extra act occurrences are allowed. + """ + b_idxs = act_idxs.get(act2, []) + if not b_idxs: + return True # vacuous (not activated) + a_idxs = act_idxs.get(act, []) + if not a_idxs: + return False + + a_ptr = 0 + prev_b = -1 + for b in b_idxs: + while a_ptr < len(a_idxs) and a_idxs[a_ptr] <= prev_b: + a_ptr += 1 + if a_ptr >= len(a_idxs) or a_idxs[a_ptr] >= b: + return False + prev_b = b + return True + + +def __is_chain_precedence_satisfied( + trace: Collection[str], act_idxs: Dict[str, List[int]], act: str, act2: str +) -> bool: + """ + Chain precedence(act, act2): + for each occurrence of act2, act occurs IMMEDIATELY before. + Extra act occurrences are allowed. + """ + b_idxs = act_idxs.get(act2, []) + if not b_idxs: + return True # vacuous (not activated) + + trace_list = list(trace) + for b in b_idxs: + if b == 0 or trace_list[b - 1] != act: + return False + return True + + +def existence_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + if EXISTENCE in allowed_templates: + for act in activities: + if act in act_counter: + rules[__rule_existence_column(act)] = 1 + else: + rules[__rule_existence_column(act)] = -1 + + +def exactly_one_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + # BUGFIX: previously did not mark absence as a violation and could leave 0 values + # (i.e., "not activated"), which is wrong for a unary constraint like EXACTLY_ONE. + if EXACTLY_ONE in allowed_templates: + for act in activities: + if act_counter.get(act, 0) == 1: + rules[__rule_exactly_one_column(act)] = 1 + else: + rules[__rule_exactly_one_column(act)] = -1 + + +def init_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + # BUGFIX: handle empty traces safely + if INIT in allowed_templates: + trace_list = list(trace) + first = trace_list[0] if trace_list else None + for act in activities: + if first is not None and act == first: + rules[__rule_init_column(act)] = 1 + else: + rules[__rule_init_column(act)] = -1 + + +def responded_existence_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + if RESPONDED_EXISTENCE in allowed_templates: + for act in act_counter: + for act2 in activities: + if act2 != act: + if act2 not in act_counter: + rules[__rule_responded_existence_column(act, act2)] = -1 + else: + rules[__rule_responded_existence_column(act, act2)] = 1 + + +def response_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + if RESPONSE in allowed_templates: + for act in act_counter: + for act2 in activities: + if act2 != act: + if act2 not in act_counter: + rules[__rule_response(act, act2)] = -1 + else: + if act_idxs[act][-1] < act_idxs[act2][-1]: + rules[__rule_response(act, act2)] = 1 + else: + rules[__rule_response(act, act2)] = -1 + + +def precedence_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + # BUGFIX: previously "pass" when the precedent activity was missing, producing 0 + # and inflating confidence/support in discovery. If B occurs and A is missing, + # precedence(A,B) is violated. + if PRECEDENCE in allowed_templates: + for b in act_counter: # activation on the consequent (B) + for a in activities: + if a != b: + if a not in act_counter: + rules[__rule_precedence(a, b)] = -1 + else: + rules[__rule_precedence(a, b)] = ( + 1 if act_idxs[a][0] < act_idxs[b][0] else -1 + ) + + +def altresponse_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + # BUGFIX: previous implementation wrongly required |A| == |B| and penalized extra B's + if ALTRESPONSE in allowed_templates: + trace_len = len(list(trace)) + for act in act_counter: # activation on A + for act2 in activities: + if act2 != act: + ok = __is_alternate_response_satisfied(trace_len, act_idxs, act, act2) + rules[__rule_alternate_response(act, act2)] = 1 if ok else -1 + + +def chainresponse_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + # BUGFIX: previous implementation wrongly required |A| == |B| and penalized extra B's + if CHAINRESPONSE in allowed_templates: + trace_list = list(trace) + for act in act_counter: # activation on A + for act2 in activities: + if act2 != act: + ok = __is_chain_response_satisfied(trace_list, act_idxs, act, act2) + rules[__rule_chain_response(act, act2)] = 1 if ok else -1 + + +def altprecedence_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + # BUGFIX: previous implementation wrongly required |A| == |B| and penalized extra A's + # (e.g., A after last B). Alternate precedence is activated by B and only constrains B's. + if ALTPRECEDENCE in allowed_templates: + for b in act_counter: # activation on B + for a in activities: + if a != b: + ok = __is_alternate_precedence_satisfied(act_idxs, a, b) + rules[__rule_alternate_precedence(a, b)] = 1 if ok else -1 + + +def chainprecedence_template_step1( + rules: Dict[Union[Tuple[str, str], Tuple[str, str, str]], int], + trace: Collection[str], + activities: Set[str], + act_counter: TCounter[str], + act_idxs: Dict[str, List[int]], + allowed_templates: Collection[str], +): + # BUGFIX: previous implementation penalized extra A's (e.g., A after last B). + # Chain precedence is activated by B and only constrains B's. + if CHAINPRECEDENCE in allowed_templates: + trace_list = list(trace) + for b in act_counter: # activation on B + for a in activities: + if a != b: + ok = __is_chain_precedence_satisfied(trace_list, act_idxs, a, b) + rules[__rule_chain_precedence(a, b)] = 1 if ok else -1 + + +def absence_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if ABSENCE in allowed_templates and EXISTENCE in allowed_templates: + for act in activities: + if __rule_existence_column(act) in table: + table[__rule_absence_act(act)] = -1 * table[__rule_existence_column(act)] + return table + + +def exactly_one_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if EXACTLY_ONE in allowed_templates: + n = __table_nrows(table) + for act in activities: + if __rule_exactly_one_column(act) not in table: + table[__rule_exactly_one_column(act)] = np.zeros(n, dtype=int) + return table + + +def responded_existence_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if RESPONDED_EXISTENCE in allowed_templates: + n = __table_nrows(table) + for act in activities: + for act2 in activities: + if act2 != act: + if __rule_responded_existence_column(act, act2) not in table: + table[__rule_responded_existence_column(act, act2)] = np.zeros( + n, dtype=int + ) + return table + + +def response_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if RESPONSE in allowed_templates: + n = __table_nrows(table) + for act in activities: + for act2 in activities: + if act2 != act: + if __rule_response(act, act2) not in table: + table[__rule_response(act, act2)] = np.zeros(n, dtype=int) + return table + + +def precedence_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if PRECEDENCE in allowed_templates: + n = __table_nrows(table) + for act in activities: + for act2 in activities: + if act2 != act: + if __rule_precedence(act, act2) not in table: + table[__rule_precedence(act, act2)] = np.zeros(n, dtype=int) + return table + + +def altresponse_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if ALTRESPONSE in allowed_templates: + n = __table_nrows(table) + for act in activities: + for act2 in activities: + if act2 != act: + if __rule_alternate_response(act, act2) not in table: + table[__rule_alternate_response(act, act2)] = np.zeros( + n, dtype=int + ) + return table + + +def chainresponse_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if CHAINRESPONSE in allowed_templates: + n = __table_nrows(table) + for act in activities: + for act2 in activities: + if act2 != act: + if __rule_chain_response(act, act2) not in table: + table[__rule_chain_response(act, act2)] = np.zeros(n, dtype=int) + return table + + +def altprecedence_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if ALTPRECEDENCE in allowed_templates: + n = __table_nrows(table) + for act in activities: + for act2 in activities: + if act2 != act: + if __rule_alternate_precedence(act, act2) not in table: + table[__rule_alternate_precedence(act, act2)] = np.zeros( + n, dtype=int + ) + return table + + +def chainprecedence_template_step2( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if CHAINPRECEDENCE in allowed_templates: + n = __table_nrows(table) + for act in activities: + for act2 in activities: + if act2 != act: + if __rule_chain_precedence(act, act2) not in table: + table[__rule_chain_precedence(act, act2)] = np.zeros( + n, dtype=int + ) + return table + + +def succession_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if ( + SUCCESSION in allowed_templates + and RESPONSE in allowed_templates + and PRECEDENCE in allowed_templates + ): + for act in activities: + for act2 in activities: + if act2 != act: + table[__rule_succession(act, act2)] = np.minimum( + table[__rule_response(act, act2)], + table[__rule_precedence(act, act2)], + ) + return table + + +def altsuccession_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if ( + ALTSUCCESSION in allowed_templates + and ALTRESPONSE in allowed_templates + and ALTPRECEDENCE in allowed_templates + ): + for act in activities: + for act2 in activities: + if act2 != act: + table[__rule_alternate_succession(act, act2)] = np.minimum( + table[__rule_alternate_response(act, act2)], + table[__rule_alternate_precedence(act, act2)], + ) + return table + + +def chainsuccession_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if ( + CHAINSUCCESSION in allowed_templates + and CHAINRESPONSE in allowed_templates + and CHAINPRECEDENCE in allowed_templates + ): + for act in activities: + for act2 in activities: + if act2 != act: + table[__rule_chain_succession(act, act2)] = np.minimum( + table[__rule_chain_response(act, act2)], + table[__rule_chain_precedence(act, act2)], + ) + return table + + +def coexistence_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if COEXISTENCE in allowed_templates and RESPONDED_EXISTENCE in allowed_templates: + for act in activities: + for act2 in activities: + if act2 != act: + table[__rule_coexistence(act, act2)] = np.minimum( + table[__rule_responded_existence_column(act, act2)], + table[__rule_responded_existence_column(act2, act)], + ) + return table + + +def noncoexistence_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if ( + NONCOEXISTENCE in allowed_templates + and COEXISTENCE in allowed_templates + and RESPONDED_EXISTENCE in allowed_templates + ): + for act in activities: + for act2 in activities: + if act2 != act: + table[__rule_non_coexistence(act, act2)] = -1 * table[ + __rule_coexistence(act, act2) + ] + return table + + +def nonsuccession_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if ( + NONSUCCESSION in allowed_templates + and SUCCESSION in allowed_templates + and RESPONSE in allowed_templates + and PRECEDENCE in allowed_templates + ): + for act in activities: + for act2 in activities: + if act2 != act: + table[__rule_non_succession(act, act2)] = -1 * table[ + __rule_succession(act, act2) + ] + return table + + +def nonchainsuccession_template( + table, + columns: Collection[str], + activities: Set[str], + allowed_templates: Collection[str], +) -> pd.DataFrame: + if not table: + return table + if ( + NONCHAINSUCCESSION in allowed_templates + and CHAINSUCCESSION in allowed_templates + and CHAINRESPONSE in allowed_templates + and CHAINPRECEDENCE in allowed_templates + ): + for act in activities: + for act2 in activities: + if act2 != act: + table[__rule_non_chain_succession(act, act2)] = -1 * table[ + __rule_chain_succession(act, act2) + ] + return table + + +def form_rules_table( + log: Union[EventLog, pd.DataFrame], + parameters: Optional[Dict[Any, Any]] = None, +) -> pd.DataFrame: + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + + allowed_templates = exec_utils.get_param_value( + Parameters.ALLOWED_TEMPLATES, parameters, None + ) + + if allowed_templates is None: + # BUGFIX: include negative templates as documented/implemented + allowed_templates = { + EXISTENCE, + EXACTLY_ONE, + INIT, + RESPONDED_EXISTENCE, + RESPONSE, + PRECEDENCE, + SUCCESSION, + ALTRESPONSE, + ALTPRECEDENCE, + ALTSUCCESSION, + CHAINRESPONSE, + CHAINPRECEDENCE, + CHAINSUCCESSION, + ABSENCE, + COEXISTENCE, + NONCOEXISTENCE, + NONSUCCESSION, + NONCHAINSUCCESSION, + } + + import pm4py + + projected_log = pm4py.project_on_event_attribute( + log, activity_key, case_id_key=case_id_key + ) + activities = exec_utils.get_param_value( + Parameters.CONSIDERED_ACTIVITIES, parameters, None + ) + + if activities is None: + activities = set(y for x in projected_log for y in x) + + allowed_templates = set(allowed_templates) + activities = set(activities) + + # If there are no considered activities or no traces, return an empty dataframe safely. + if not activities or projected_log is None or len(projected_log) == 0: + return pandas_utils.instantiate_dataframe({}) + + vars = Counter([tuple([y for y in x if y in activities]) for x in projected_log]) + table = [] + + for trace, occs in vars.items(): + act_counter = Counter(trace) + act_idxs = {x: [] for x in set(trace)} + + for idx, act in enumerate(trace): + act_idxs[act].append(idx) + + rules = {} + + existence_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + exactly_one_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + init_template_step1(rules, trace, activities, act_counter, act_idxs, allowed_templates) + responded_existence_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + response_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + precedence_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + altresponse_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + chainresponse_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + altprecedence_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + chainprecedence_template_step1( + rules, trace, activities, act_counter, act_idxs, allowed_templates + ) + + for _ in range(occs): + table.append(rules) + + if not table: + return pandas_utils.instantiate_dataframe({}) + + columns = set(y for x in table for y in x.keys()) + table2 = {c: [] for c in columns} + for i in range(len(table)): + trace = table[i] + for c in columns: + table2[c].append(trace.get(c, 0)) + + for c in table2: + table2[c] = np.array(table2[c], dtype=int) + + table2 = absence_template(table2, columns, activities, allowed_templates) + table2 = exactly_one_template_step2(table2, columns, activities, allowed_templates) + table2 = responded_existence_template_step2( + table2, columns, activities, allowed_templates + ) + table2 = response_template_step2(table2, columns, activities, allowed_templates) + table2 = precedence_template_step2(table2, columns, activities, allowed_templates) + table2 = altresponse_template_step2(table2, columns, activities, allowed_templates) + table2 = chainresponse_template_step2(table2, columns, activities, allowed_templates) + table2 = altprecedence_template_step2(table2, columns, activities, allowed_templates) + table2 = chainprecedence_template_step2(table2, columns, activities, allowed_templates) + + table2 = succession_template(table2, columns, activities, allowed_templates) + table2 = altsuccession_template(table2, columns, activities, allowed_templates) + table2 = chainsuccession_template(table2, columns, activities, allowed_templates) + table2 = coexistence_template(table2, columns, activities, allowed_templates) + table2 = noncoexistence_template(table2, columns, activities, allowed_templates) + table2 = nonsuccession_template(table2, columns, activities, allowed_templates) + table2 = nonchainsuccession_template(table2, columns, activities, allowed_templates) + + return pandas_utils.instantiate_dataframe(table2) + + +def get_rules_from_rules_df( + rules_df, parameters: Optional[Dict[Any, Any]] = None +) -> Dict[str, Dict[Any, Dict[str, int]]]: + if parameters is None: + parameters = {} + + # BUGFIX: handle empty / None dataframes safely and handle partial threshold specification + if rules_df is None or len(rules_df) == 0: + return {} + + min_support_ratio = exec_utils.get_param_value( + Parameters.MIN_SUPPORT_RATIO, parameters, None + ) + min_confidence_ratio = exec_utils.get_param_value( + Parameters.MIN_CONFIDENCE_RATIO, parameters, None + ) + rules = {} + + if min_support_ratio is None and min_confidence_ratio is None: + # auto determine the minimum support and confidence ratio by + # identifying the values for the best feature + auto_selection_multiplier = exec_utils.get_param_value( + Parameters.AUTO_SELECTION_MULTIPLIER, parameters, 0.8 + ) + cols_prod = [] + for col_name in rules_df: + col = rules_df[col_name] + supp = len(col[col != 0]) + supp_ratio = float(supp) / float(len(rules_df)) if len(rules_df) > 0 else 0.0 + if supp_ratio > 0: + conf_ratio = float(len(col[col == 1])) / float(supp) + prod = supp_ratio * conf_ratio + cols_prod.append((col_name, prod)) + if not cols_prod: + return {} + cols_prod = sorted(cols_prod, key=lambda x: (x[1], x[0]), reverse=True) + col = rules_df[cols_prod[0][0]] + supp = len(col[col != 0]) + min_support_ratio = float(supp) / float(len(rules_df)) * auto_selection_multiplier + min_confidence_ratio = ( + float(len(col[col == 1])) / float(supp) * auto_selection_multiplier + if supp > 0 + else 1.0 + ) + + # If one of the two is provided and the other is not, interpret missing as "no filter" + if min_support_ratio is None: + min_support_ratio = 0.0 + if min_confidence_ratio is None: + min_confidence_ratio = 0.0 + + for col_name in rules_df: + col = rules_df[col_name] + supp = len(col[col != 0]) + + if supp >= len(rules_df) * float(min_support_ratio): + conf = len(col[col == 1]) + + if supp == 0: + continue + if conf >= supp * float(min_confidence_ratio): + rule, key = __col_to_dict_rule(col_name) + if rule not in rules: + rules[rule] = {} + rules[rule][key] = {"support": supp, "confidence": conf} + + return rules + + +def apply( + log: Union[EventLog, pd.DataFrame], + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Dict[Any, Dict[str, int]]]: + """ + Discovers a DECLARE model from the provided event log. + + 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. + + Parameters + ---------- + log + Log object (EventLog, Pandas table) + parameters + Possible parameters of the algorithm, including: + + - Parameters.ACTIVITY_KEY + - Parameters.CONSIDERED_ACTIVITIES + - Parameters.MIN_SUPPORT_RATIO + - Parameters.MIN_CONFIDENCE_RATIO + - Parameters.AUTO_SELECTION_MULTIPLIER + - Parameters.ALLOWED_TEMPLATES: collection of templates to consider, including: + + * existence + * exactly_one + * init + * responded_existence + * response + * precedence + * succession + * altresponse + * altprecedence + * altsuccession + * chainresponse + * chainprecedence + * chainsuccession + * absence + * coexistence + * noncoexistence + * nonsuccession + * nonchainsuccession + + Returns + ------- + declare_model + DECLARE model (as Python dictionary), where each template is associated with its own rules + """ + if parameters is None: + parameters = {} + + rules_df = form_rules_table(log, parameters=parameters) + rules = get_rules_from_rules_df(rules_df, parameters=parameters) + return rules diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..409daa72d4499ce925c1f42c3e6b7d9002616f4b --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/__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 +''' +from pm4py.algo.discovery.dfg import ( + adapters, + variants, + algorithm, + replacement, + utils, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75a640a79545010479eabddf37d735cc5e18676d --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/__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.algo.discovery.dfg.adapters import pandas + +import importlib.util + +if importlib.util.find_spec("polars"): + from pm4py.algo.discovery.dfg.adapters import polars diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4aaaee9584e727158bb9a251a39a153855ef9ad --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/__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.algo.discovery.dfg.adapters.pandas import ( + df_statistics, + freq_triples, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/df_statistics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/df_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5084e5857dbe294e5ef245ce9954273dfd78be --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/df_statistics.py @@ -0,0 +1,455 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 import xes_constants, pandas_utils, constants +from pm4py.util.business_hours import soj_time_business_hours_diff +import pandas as pd + + +def get_dfg_graph( + df, + measure="frequency", + activity_key="concept:name", + case_id_glue="case:concept:name", + start_timestamp_key=None, + timestamp_key="time:timestamp", + perf_aggregation_key="mean", + sort_caseid_required=True, + sort_timestamp_along_case_id=True, + keep_once_per_case=False, + window=1, + business_hours=False, + business_hours_slot=None, + workcalendar=constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR, + target_activity_key=None, + reduce_columns=True, + cost_attribute=None, +): + """ + Get DFG graph from Pandas dataframe - optimized version + + Parameters + ----------- + df + Dataframe + measure + Measure to use (frequency/performance/both) + activity_key + Activity key to use in the grouping + case_id_glue + Case ID identifier + start_timestamp_key + Start timestamp key + timestamp_key + Timestamp key + perf_aggregation_key + Performance aggregation key (mean, median, min, max) + sort_caseid_required + Specify if a sort on the Case ID is required + sort_timestamp_along_case_id + Specifying if sorting by timestamp along the CaseID is required + keep_once_per_case + In the counts, keep only one occurrence of the path per case (the first) + window + Window of the DFG (default 1) + + Returns + ------- + dfg : dict + DFG in the chosen measure (may be only the frequency, only the performance, or both) + + """ + # added support to specify an activity key for the target event which is different + # from the activity key of the source event. + if target_activity_key is None: + target_activity_key = activity_key + + # if not differently specified, set the start timestamp key to the timestamp key + # to avoid retro-compatibility problems + st_eq_ct = start_timestamp_key == timestamp_key + if start_timestamp_key is None: + start_timestamp_key = xes_constants.DEFAULT_START_TIMESTAMP_KEY + if start_timestamp_key not in df.columns: + df[start_timestamp_key] = df[timestamp_key] + st_eq_ct = True + + # Determine which columns we need to keep before reducing + needed_columns = {case_id_glue, activity_key, target_activity_key} + if measure != "frequency" or sort_timestamp_along_case_id: + needed_columns.update({start_timestamp_key, timestamp_key}) + if measure == "cost": + needed_columns.add(cost_attribute) + + # Reduce dataframe to necessary columns (more efficient than previous implementation) + if reduce_columns: + df = df[list(needed_columns)] + + if measure == "cost": + df[cost_attribute] = df[cost_attribute].fillna(0) # Using 0 directly is more efficient + + # Create a view with the needed sorting for more efficient memory usage + if sort_caseid_required: + if sort_timestamp_along_case_id: + df = df.sort_values([case_id_glue, start_timestamp_key, timestamp_key]) + else: + df = df.sort_values(case_id_glue) + + # Pre-create the suffixed column names for more efficient joining + suffix = "_2" + # Get a list of column names before shift to avoid recreating them + orig_cols = df.columns.tolist() + shifted_cols = [str(col) + suffix for col in orig_cols] + + # Shift the dataframe by window + df_shifted = df.shift(-window) + df_shifted.columns = shifted_cols + + # Concatenate the dataframes efficiently + df_successive_rows = pandas_utils.DATAFRAME.concat([df, df_shifted], axis=1) + + # Filter for matching case IDs (more efficient with direct access) + case_id_col = case_id_glue + case_id_col_shifted = case_id_glue + suffix + df_successive_rows = df_successive_rows[df_successive_rows[case_id_col] == df_successive_rows[case_id_col_shifted]] + + # Handle keep_once_per_case more efficiently + if keep_once_per_case: + # Use drop_duplicates which is more efficient than groupby + first for this operation + df_successive_rows = df_successive_rows.drop_duplicates( + subset=[case_id_glue, activity_key, target_activity_key + suffix] + ) + + # Calculate performance metrics if needed + if measure in ["performance", "both"]: + if not st_eq_ct: + # Calculate max more efficiently using numpy + df_successive_rows[start_timestamp_key + suffix] = np.maximum( + df_successive_rows[start_timestamp_key + suffix], + df_successive_rows[timestamp_key] + ) + + # Calculate the time difference + if business_hours: + if business_hours_slot is None: + business_hours_slot = constants.DEFAULT_BUSINESS_HOUR_SLOTS + + # Business hours calculation requires Python datetime objects + # Use a more efficient approach than apply, but ensure we're working with correct datetime types + + # Convert timestamps - we need to use to_pydatetime() to get Python datetime objects + # that are compatible with the business hours function + if hasattr(df_successive_rows[timestamp_key], 'dt'): + # If timestamps are already pandas datetime, convert to Python datetime + ts_values = np.array(df_successive_rows[timestamp_key].dt.to_pydatetime()) + start_ts_values = np.array(df_successive_rows[start_timestamp_key + suffix].dt.to_pydatetime()) + else: + # If timestamps are pandas Timestamp objects or strings, convert properly + ts_values = np.array(pandas_utils.DATAFRAME.to_datetime(df_successive_rows[timestamp_key]).dt.to_pydatetime()) + start_ts_values = np.array(pandas_utils.DATAFRAME.to_datetime(df_successive_rows[start_timestamp_key + suffix]).dt.to_pydatetime()) + + # Use list comprehension which is faster than apply but handles datetime objects correctly + flow_times = [ + soj_time_business_hours_diff(ts, start_ts, business_hours_slot, workcalendar) + for ts, start_ts in zip(ts_values, start_ts_values) + ] + + df_successive_rows[constants.DEFAULT_FLOW_TIME] = flow_times + else: + # Vectorized timestamp difference calculation (already efficient) + difference = df_successive_rows[start_timestamp_key + suffix] - df_successive_rows[timestamp_key] + df_successive_rows[constants.DEFAULT_FLOW_TIME] = pandas_utils.get_total_seconds(difference) + + # Set up grouping based on measure + group_cols = [activity_key, target_activity_key + suffix] + + if measure == "performance" or measure == "both": + agg_col = constants.DEFAULT_FLOW_TIME + elif measure == "cost": + agg_col = cost_attribute + suffix + else: + # For frequency, find the first non-grouping column to use (more efficient) + remaining_cols = set(df_successive_rows.columns) - set(group_cols) + agg_col = next(iter(remaining_cols)) if remaining_cols else case_id_col + + # Create dictionary directly rather than creating a Series object first (more efficient) + if measure == "frequency" or measure == "both": + # Use value_counts which is more efficient than groupby+size for frequency + if type(df) is pd.DataFrame and len(group_cols) == 2: # Most common case + temp_df = df_successive_rows[group_cols].copy() + temp_df['dummy'] = 1 # Add a column to count + pivot = temp_df.pivot_table( + index=group_cols[0], + columns=group_cols[1], + values='dummy', + aggfunc='count', + fill_value=0 + ) + dfg_frequency = {(idx, col): val for idx, row in pivot.iterrows() for col, val in row.items() if val > 0} + else: + # Fallback to groupby + dfg_frequency = df_successive_rows.groupby(group_cols).size().to_dict() + + # Performance metrics calculation + dfg_performance = {} + if measure in ["performance", "cost", "both"]: + grouped = df_successive_rows.groupby(group_cols)[agg_col] + + if perf_aggregation_key == "all": + # Calculate all metrics at once (more efficient than separate calls) + metrics = grouped.agg(['mean', 'median', 'max', 'min', 'sum', 'std']) + + if type(metrics) is pd.DataFrame: + metrics = metrics.iterrows() + else: + metrics = metrics.to_pandas().iterrows() + + # Convert to the expected dictionary structure + dfg_performance = { + group: { + 'mean': row['mean'], + 'median': row['median'], + 'max': row['max'], + 'min': row['min'], + 'sum': row['sum'], + 'stdev': row['std'] + } + for group, row in metrics + } + elif perf_aggregation_key == "raw_values": + dfg_performance = grouped.agg(list).to_dict() + else: + dfg_performance = grouped.agg(perf_aggregation_key).to_dict() + + # Return appropriate results based on measure + if measure == "frequency": + return dfg_frequency + elif measure == "performance" or measure == "cost": + return dfg_performance + else: # measure == "both" + return [dfg_frequency, dfg_performance] + + +def get_partial_order_dataframe( + df, + start_timestamp_key=None, + timestamp_key="time:timestamp", + case_id_glue="case:concept:name", + activity_key="concept:name", + sort_caseid_required=True, + sort_timestamp_along_case_id=True, + reduce_dataframe=True, + keep_first_following=True, + business_hours=False, + business_hours_slot=None, + workcalendar=constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR, + event_index=constants.DEFAULT_INDEX_KEY, +): + """ + Gets the partial order between events (of the same case) in a Pandas dataframe + + Parameters + -------------- + df + Dataframe + start_timestamp_key + Start timestamp key (if not provided, defaulted to the timestamp_key) + timestamp_key + Complete timestamp + case_id_glue + Column of the dataframe to use as case ID + activity_key + Activity key + sort_caseid_required + Tells if a sort by case ID is required (default: True) + sort_timestamp_along_case_id + Tells if a sort by timestamp is required along the case ID (default: True) + reduce_dataframe + To fasten operation, keep only essential columns in the dataframe + keep_first_following + Keep only the first event following the given event + Returns + --------------- + part_ord_dataframe + Partial order dataframe (with @@flow_time between events) + """ + # if not differently specified, set the start timestamp key to the timestamp key + # to avoid retro-compatibility problems + if start_timestamp_key is None: + start_timestamp_key = xes_constants.DEFAULT_START_TIMESTAMP_KEY + + if start_timestamp_key not in df: + df[start_timestamp_key] = df[timestamp_key] + + # to increase the speed of the approaches reduce dataframe to case, activity (and possibly complete timestamp) + # columns + if reduce_dataframe: + needed_columns = { + case_id_glue, + activity_key, + start_timestamp_key, + timestamp_key, + } + if event_index in df.columns: + needed_columns.add(event_index) + needed_columns = list(needed_columns) + df = df[needed_columns] + + # to get rows belonging to same case ID together, we need to sort on case + # ID + if sort_caseid_required: + if sort_timestamp_along_case_id: + df = df.sort_values( + [case_id_glue, start_timestamp_key, timestamp_key] + ) + else: + df = df.sort_values(case_id_glue) + df = df.reset_index(drop=True) + + if event_index not in df.columns: + df = pandas_utils.insert_index( + df, event_index, copy_dataframe=False, reset_index=False + ) + + df = df.set_index(case_id_glue) + + df = df.join(df, rsuffix="_2") + df = df[df[event_index] < df[event_index + "_2"]] + df = df[df[timestamp_key] <= df[start_timestamp_key + "_2"]] + + df = df.reset_index() + + if business_hours: + if business_hours_slot is None: + business_hours_slot = constants.DEFAULT_BUSINESS_HOUR_SLOTS + df[constants.DEFAULT_FLOW_TIME] = df.apply( + lambda x: soj_time_business_hours_diff( + x[timestamp_key], + x[start_timestamp_key + "_2"], + business_hours_slot, + workcalendar, + ), + axis=1, + ) + else: + df[constants.DEFAULT_FLOW_TIME] = pandas_utils.get_total_seconds( + df[start_timestamp_key + "_2"] - df[timestamp_key] + ) + + if keep_first_following: + df = df.groupby(constants.DEFAULT_INDEX_KEY).first().reset_index() + + return df + + +def get_concurrent_events_dataframe( + df, + start_timestamp_key=None, + timestamp_key="time:timestamp", + case_id_glue="case:concept:name", + activity_key="concept:name", + sort_caseid_required=True, + sort_timestamp_along_case_id=True, + reduce_dataframe=True, + max_start_column="@@max_start_column", + min_complete_column="@@min_complete_column", + diff_maxs_minc="@@diff_maxs_minc", + strict=False, +): + """ + Gets the concurrent events (of the same case) in a Pandas dataframe + + Parameters + -------------- + df + Dataframe + start_timestamp_key + Start timestamp key (if not provided, defaulted to the timestamp_key) + timestamp_key + Complete timestamp + case_id_glue + Column of the dataframe to use as case ID + activity_key + Activity key + sort_caseid_required + Tells if a sort by case ID is required (default: True) + sort_timestamp_along_case_id + Tells if a sort by timestamp is required along the case ID (default: True) + reduce_dataframe + To fasten operation, keep only essential columns in the dataframe + strict + Gets only entries that are strictly concurrent (i.e. the length of the intersection as real interval is > 0) + + Returns + --------------- + conc_ev_dataframe + Concurrent events dataframe (with @@diff_maxs_minc as the size of the intersection of the intervals) + """ + # if not differently specified, set the start timestamp key to the timestamp key + # to avoid retro-compatibility problems + if start_timestamp_key is None: + start_timestamp_key = xes_constants.DEFAULT_START_TIMESTAMP_KEY + df[start_timestamp_key] = df[timestamp_key] + + # to get rows belonging to same case ID together, we need to sort on case + # ID + if sort_caseid_required: + if sort_timestamp_along_case_id: + df = df.sort_values( + [case_id_glue, start_timestamp_key, timestamp_key] + ) + else: + df = df.sort_values(case_id_glue) + + # to increase the speed of the approaches reduce dataframe to case, activity (and possibly complete timestamp) + # columns + if reduce_dataframe: + df = df[ + [case_id_glue, activity_key, start_timestamp_key, timestamp_key] + ] + + df = pandas_utils.insert_index(df) + df = df.set_index(case_id_glue) + df_copy = df.copy() + + df = df.join(df_copy, rsuffix="_2").dropna() + df = df[ + df[constants.DEFAULT_INDEX_KEY] + < df[constants.DEFAULT_INDEX_KEY + "_2"] + ] + df[max_start_column] = df[ + [start_timestamp_key, start_timestamp_key + "_2"] + ].max(axis=1) + df[min_complete_column] = df[[timestamp_key, timestamp_key + "_2"]].min( + axis=1 + ) + df[max_start_column] = df[max_start_column].apply(lambda x: x.timestamp()) + df[min_complete_column] = df[min_complete_column].apply( + lambda x: x.timestamp() + ) + df[diff_maxs_minc] = df[min_complete_column] - df[max_start_column] + if strict: + df = df[df[diff_maxs_minc] > 0] + else: + df = df[df[diff_maxs_minc] >= 0] + + return df diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/freq_triples.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/freq_triples.py new file mode 100644 index 0000000000000000000000000000000000000000..edc4b4435a17e2cdb22ff32c031f92166a841941 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/pandas/freq_triples.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 pm4py.util import constants, pandas_utils + + +def get_freq_triples( + df, + activity_key="concept:name", + case_id_glue="case:concept:name", + timestamp_key="time:timestamp", + sort_caseid_required=True, + sort_timestamp_along_case_id=True, +): + """ + Gets the frequency triples out of a dataframe + + Parameters + ------------ + df + Dataframe + activity_key + Activity key + case_id_glue + Case ID glue + timestamp_key + Timestamp key + sort_caseid_required + Determine if sort by case ID is required (default: True) + sort_timestamp_along_case_id + Determine if sort by timestamp is required (default: True) + + Returns + ------------- + freq_triples + Frequency triples from the dataframe + """ + import pandas as pd + + if sort_caseid_required: + if sort_timestamp_along_case_id: + df = df.sort_values([case_id_glue, timestamp_key]) + else: + df = df.sort_values(case_id_glue) + df_reduced = df[[case_id_glue, activity_key]] + # shift the dataframe by 1 + df_reduced_1 = df_reduced.shift(-1) + # shift the dataframe by 2 + df_reduced_2 = df_reduced.shift(-2) + # change column names to shifted dataframe + df_reduced_1.columns = [str(col) + "_2" for col in df_reduced_1.columns] + df_reduced_2.columns = [str(col) + "_3" for col in df_reduced_2.columns] + + df_successive_rows = pandas_utils.concat( + [df_reduced, df_reduced_1, df_reduced_2], axis=1 + ) + df_successive_rows = df_successive_rows[ + df_successive_rows[case_id_glue] + == df_successive_rows[case_id_glue + "_2"] + ] + df_successive_rows = df_successive_rows[ + df_successive_rows[case_id_glue] + == df_successive_rows[case_id_glue + "_3"] + ] + all_columns = set(df_successive_rows.columns) + all_columns = list( + all_columns + - set([activity_key, activity_key + "_2", activity_key + "_3"]) + ) + directly_follows_grouping = df_successive_rows.groupby( + [activity_key, activity_key + "_2", activity_key + "_3"] + ) + if all_columns: + directly_follows_grouping = directly_follows_grouping[all_columns[0]] + freq_triples = directly_follows_grouping.size().to_dict() + return freq_triples diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9ac197b52ee78bfc636183f6e2fa61577ed3a7f --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/__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 +''' + +from . import df_statistics, freq_triples + +__all__ = [ + "df_statistics", + "freq_triples", +] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/df_statistics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/df_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..e56176abed1ee3a6dfa3b3f16bb452d7f43f51ca --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/df_statistics.py @@ -0,0 +1,416 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, Optional, Tuple, Union + +import polars as pl + +from pm4py.util import constants, xes_constants +from pm4py.util.business_hours import soj_time_business_hours_diff + + +def _ensure_start_timestamp( + lf: pl.LazyFrame, start_timestamp_key: str, timestamp_key: str +) -> pl.LazyFrame: + schema_names = lf.collect_schema().names() + if start_timestamp_key not in schema_names: + lf = lf.with_columns(pl.col(timestamp_key).alias(start_timestamp_key)) + return lf + + +def _ensure_row_index(lf: pl.LazyFrame, column_name: str) -> pl.LazyFrame: + schema_names = lf.collect_schema().names() + if column_name in schema_names: + return lf + return lf.with_row_index(column_name) + + +def get_dfg_graph( + df: pl.LazyFrame, + measure: str = "frequency", + activity_key: str = "concept:name", + case_id_glue: str = "case:concept:name", + start_timestamp_key: Optional[str] = None, + timestamp_key: str = "time:timestamp", + perf_aggregation_key: str = "mean", + sort_caseid_required: bool = True, + sort_timestamp_along_case_id: bool = True, + keep_once_per_case: bool = False, + window: int = 1, + business_hours: bool = False, + business_hours_slot=None, + workcalendar=constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR, + target_activity_key: Optional[str] = None, + reduce_columns: bool = True, + cost_attribute: Optional[str] = None, +) -> Union[Dict[Tuple[str, str], int], Dict[Tuple[str, str], float], List[Dict]]: + """Compute DFG statistics on a Polars LazyFrame.""" + + if target_activity_key is None: + target_activity_key = activity_key + + if start_timestamp_key is None: + start_timestamp_key = xes_constants.DEFAULT_START_TIMESTAMP_KEY + + schema_names = df.collect_schema().names() + st_eq_ct = start_timestamp_key == timestamp_key + + if start_timestamp_key not in schema_names: + df = df.with_columns(pl.col(timestamp_key).alias(start_timestamp_key)) + schema_names = df.collect_schema().names() + st_eq_ct = True + + needed_columns = {case_id_glue, activity_key, target_activity_key} + if measure != "frequency" or sort_timestamp_along_case_id: + needed_columns.update({start_timestamp_key, timestamp_key}) + if measure == "cost" and cost_attribute: + needed_columns.add(cost_attribute) + + if reduce_columns: + available = [col for col in schema_names if col in needed_columns] + df = df.select([pl.col(col) for col in available]) + schema_names = df.collect_schema().names() + + if measure == "cost" and cost_attribute: + df = df.with_columns(pl.col(cost_attribute).fill_null(0)) + schema_names = df.collect_schema().names() + + if sort_caseid_required: + if sort_timestamp_along_case_id: + sort_cols = [case_id_glue] + if start_timestamp_key in schema_names: + sort_cols.append(start_timestamp_key) + if timestamp_key in schema_names: + sort_cols.append(timestamp_key) + df = df.sort(sort_cols, maintain_order=True) + else: + df = df.sort(case_id_glue, maintain_order=True) + + suffix = "_2" + shift_exprs = [ + pl.col(case_id_glue) + .shift(-window) + .over(case_id_glue) + .alias(case_id_glue + suffix), + pl.col(target_activity_key) + .shift(-window) + .over(case_id_glue) + .alias(target_activity_key + suffix), + ] + + if start_timestamp_key in schema_names or start_timestamp_key == timestamp_key: + shift_exprs.append( + pl.col(start_timestamp_key) + .shift(-window) + .over(case_id_glue) + .alias(start_timestamp_key + suffix) + ) + if timestamp_key in schema_names: + shift_exprs.append( + pl.col(timestamp_key) + .shift(-window) + .over(case_id_glue) + .alias(timestamp_key + suffix) + ) + if measure == "cost" and cost_attribute: + shift_exprs.append( + pl.col(cost_attribute) + .shift(-window) + .over(case_id_glue) + .alias(cost_attribute + suffix) + ) + + pairs = df.with_columns(shift_exprs) + pairs = pairs.filter(pl.col(case_id_glue + suffix).is_not_null()) + pairs = pairs.filter(pl.col(target_activity_key + suffix).is_not_null()) + + if keep_once_per_case: + pairs = pairs.unique( + subset=[case_id_glue, activity_key, target_activity_key + suffix], + keep="first", + ) + + if measure in {"performance", "both", "cost"}: + if not st_eq_ct: + pairs = pairs.with_columns( + pl.max_horizontal( + [pl.col(start_timestamp_key + suffix), pl.col(timestamp_key)] + ).alias(start_timestamp_key + suffix) + ) + + if business_hours: + if business_hours_slot is None: + business_hours_slot = constants.DEFAULT_BUSINESS_HOUR_SLOTS + pairs = pairs.with_columns( + pl.struct( + [pl.col(timestamp_key), pl.col(start_timestamp_key + suffix)] + ) + .map_elements( + lambda row: soj_time_business_hours_diff( + row[timestamp_key], + row[start_timestamp_key + suffix], + business_hours_slot, + workcalendar, + ), + return_dtype=pl.Float64, + ) + .alias(constants.DEFAULT_FLOW_TIME) + ) + else: + pairs = pairs.with_columns( + ( + pl.col(start_timestamp_key + suffix) - pl.col(timestamp_key) + ) + .dt.total_seconds() + .alias(constants.DEFAULT_FLOW_TIME) + ) + + group_cols = [activity_key, target_activity_key + suffix] + + freq_dict: Dict[Tuple[str, str], int] = {} + perf_dict: Dict[Tuple[str, str], Union[float, Dict[str, float], List[float]]] = {} + + if measure in {"frequency", "both"}: + freq_df = ( + pairs.group_by(group_cols) + .agg(pl.len().alias("count")) + .collect() + ) + freq_dict = { + (row[group_cols[0]], row[group_cols[1]]): row["count"] + for row in freq_df.iter_rows(named=True) + if row[group_cols[0]] is not None and row[group_cols[1]] is not None + } + + if measure in {"performance", "both", "cost"}: + if measure == "cost" and cost_attribute: + value_expr = pl.col(cost_attribute + suffix) + else: + value_expr = pl.col(constants.DEFAULT_FLOW_TIME) + + if perf_aggregation_key == "all": + agg_exprs = [ + value_expr.mean().alias("mean"), + value_expr.median().alias("median"), + value_expr.max().alias("max"), + value_expr.min().alias("min"), + value_expr.sum().alias("sum"), + value_expr.std().alias("stdev"), + ] + perf_df = pairs.group_by(group_cols).agg(agg_exprs).collect() + perf_dict = { + (row[group_cols[0]], row[group_cols[1]]): { + "mean": row["mean"], + "median": row["median"], + "max": row["max"], + "min": row["min"], + "sum": row["sum"], + "stdev": row["stdev"], + } + for row in perf_df.iter_rows(named=True) + } + elif perf_aggregation_key == "raw_values": + perf_df = ( + pairs.group_by(group_cols) + .agg(value_expr.implode().alias("raw_values")) + .collect() + ) + perf_dict = { + (row[group_cols[0]], row[group_cols[1]]): row["raw_values"] + for row in perf_df.iter_rows(named=True) + } + else: + if not hasattr(pl.Expr, perf_aggregation_key): + raise ValueError( + f"Unsupported aggregation key: {perf_aggregation_key}" + ) + agg_expr = getattr(value_expr, perf_aggregation_key)().alias( + perf_aggregation_key + ) + perf_df = ( + pairs.group_by(group_cols).agg(agg_expr).collect() + ) + perf_dict = { + (row[group_cols[0]], row[group_cols[1]]): row[perf_aggregation_key] + for row in perf_df.iter_rows(named=True) + } + + if measure == "frequency": + return freq_dict + if measure in {"performance", "cost"}: + return perf_dict + return [freq_dict, perf_dict] + + +def get_partial_order_dataframe( + df: pl.LazyFrame, + start_timestamp_key: Optional[str] = None, + timestamp_key: str = "time:timestamp", + case_id_glue: str = "case:concept:name", + activity_key: str = "concept:name", + sort_caseid_required: bool = True, + sort_timestamp_along_case_id: bool = True, + reduce_dataframe: bool = True, + keep_first_following: bool = True, + business_hours: bool = False, + business_hours_slot=None, + workcalendar=constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR, + event_index: str = constants.DEFAULT_INDEX_KEY, +) -> pl.LazyFrame: + """Compute partial order dataframe using Polars.""" + + if start_timestamp_key is None: + start_timestamp_key = xes_constants.DEFAULT_START_TIMESTAMP_KEY + + df = _ensure_start_timestamp(df, start_timestamp_key, timestamp_key) + + if reduce_dataframe: + schema_names = df.collect_schema().names() + columns = { + case_id_glue, + activity_key, + start_timestamp_key, + timestamp_key, + } + if event_index in schema_names: + columns.add(event_index) + df = df.select([pl.col(col) for col in schema_names if col in columns]) + + if sort_caseid_required: + if sort_timestamp_along_case_id: + df = df.sort([case_id_glue, start_timestamp_key, timestamp_key], maintain_order=True) + else: + df = df.sort(case_id_glue, maintain_order=True) + + df = _ensure_row_index(df, event_index) + + joined = df.join(df, on=case_id_glue, how="inner", suffix="_2", maintain_order="left") + joined = joined.filter( + pl.col(event_index) < pl.col(event_index + "_2") + ) + joined = joined.filter( + pl.col(timestamp_key) <= pl.col(start_timestamp_key + "_2") + ) + + if business_hours: + if business_hours_slot is None: + business_hours_slot = constants.DEFAULT_BUSINESS_HOUR_SLOTS + joined = joined.with_columns( + pl.struct( + [pl.col(timestamp_key), pl.col(start_timestamp_key + "_2")] + ) + .map_elements( + lambda row: soj_time_business_hours_diff( + row[timestamp_key], + row[start_timestamp_key + "_2"], + business_hours_slot, + workcalendar, + ), + return_dtype=pl.Float64, + ) + .alias(constants.DEFAULT_FLOW_TIME) + ) + else: + joined = joined.with_columns( + ( + pl.col(start_timestamp_key + "_2") - pl.col(timestamp_key) + ) + .dt.total_seconds() + .alias(constants.DEFAULT_FLOW_TIME) + ) + + if keep_first_following: + joined = joined.sort([case_id_glue, event_index, event_index + "_2"], maintain_order=True) + joined = joined.unique( + subset=[event_index], keep="first", maintain_order=True + ) + + return joined + + +def get_concurrent_events_dataframe( + df: pl.LazyFrame, + start_timestamp_key: Optional[str] = None, + timestamp_key: str = "time:timestamp", + case_id_glue: str = "case:concept:name", + activity_key: str = "concept:name", + sort_caseid_required: bool = True, + sort_timestamp_along_case_id: bool = True, + reduce_dataframe: bool = True, + max_start_column: str = "@@max_start_column", + min_complete_column: str = "@@min_complete_column", + diff_maxs_minc: str = "@@diff_maxs_minc", + strict: bool = False, +) -> pl.LazyFrame: + """Compute concurrency dataframe using Polars.""" + + if start_timestamp_key is None: + start_timestamp_key = xes_constants.DEFAULT_START_TIMESTAMP_KEY + + df = _ensure_start_timestamp(df, start_timestamp_key, timestamp_key) + + if reduce_dataframe: + columns = [case_id_glue, activity_key, start_timestamp_key, timestamp_key] + df = df.select([pl.col(col) for col in df.schema if col in columns]) + + if sort_caseid_required: + if sort_timestamp_along_case_id: + df = df.sort([case_id_glue, start_timestamp_key, timestamp_key], maintain_order=True) + else: + df = df.sort(case_id_glue, maintain_order=True) + + df = _ensure_row_index(df, constants.DEFAULT_INDEX_KEY) + + joined = df.join(df, on=case_id_glue, how="inner", suffix="_2", maintain_order="left") + joined = joined.filter( + pl.col(constants.DEFAULT_INDEX_KEY) + < pl.col(constants.DEFAULT_INDEX_KEY + "_2") + ) + + joined = joined.filter( + pl.col(timestamp_key) + <= pl.col(start_timestamp_key + "_2") + ) + + joined = joined.with_columns([ + pl.max_horizontal( + [pl.col(start_timestamp_key), pl.col(start_timestamp_key + "_2")] + ).alias(max_start_column), + pl.min_horizontal([pl.col(timestamp_key), pl.col(timestamp_key + "_2")]).alias( + min_complete_column + ), + ]) + + joined = joined.with_columns( + ( + pl.col(min_complete_column) - pl.col(max_start_column) + ) + .dt.total_seconds() + .alias(diff_maxs_minc) + ) + + if strict: + joined = joined.filter(pl.col(diff_maxs_minc) > 0) + else: + joined = joined.filter(pl.col(diff_maxs_minc) >= 0) + + return joined.drop(constants.DEFAULT_INDEX_KEY + "_2") diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/freq_triples.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/freq_triples.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c8cc19854d9522dd7ce57534a91996bf8ace6c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/adapters/polars/freq_triples.py @@ -0,0 +1,77 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 + +import polars as pl + + +def get_freq_triples( + df: pl.LazyFrame, + activity_key: str = "concept:name", + case_id_glue: str = "case:concept:name", + timestamp_key: str = "time:timestamp", + sort_caseid_required: bool = True, + sort_timestamp_along_case_id: bool = True, +) -> Dict[Tuple[str, str, str], int]: + """Compute frequency triples directly on a Polars LazyFrame.""" + + if sort_caseid_required: + if sort_timestamp_along_case_id: + df = df.sort([case_id_glue, timestamp_key], maintain_order=True) + else: + df = df.sort(case_id_glue, maintain_order=True) + + triples = df.with_columns( + [ + pl.col(activity_key) + .shift(-1) + .over(case_id_glue) + .alias(activity_key + "_2"), + pl.col(activity_key) + .shift(-2) + .over(case_id_glue) + .alias(activity_key + "_3"), + ] + ) + + triples = triples.filter( + pl.col(activity_key + "_2").is_not_null() + & pl.col(activity_key + "_3").is_not_null() + ) + + grouped = ( + triples.group_by( + [activity_key, activity_key + "_2", activity_key + "_3"] + ) + .agg(pl.len().alias("count")) + .collect() + ) + + return { + ( + row[activity_key], + row[activity_key + "_2"], + row[activity_key + "_3"], + ): row["count"] + for row in grouped.iter_rows(named=True) + } diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1963d003bb8f6481c67ebd359f4dc9e6f73205 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/algorithm.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 +''' + +from pm4py import util as pmutil +from pm4py.algo.discovery.dfg.variants import ( + native, + performance, + freq_triples, + case_attributes, + clean, +) +from pm4py.objects.conversion.log import converter as log_conversion +from pm4py.util import xes_constants as xes_util +from pm4py.util import exec_utils +from pm4py.util import constants, pandas_utils +from enum import Enum +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream +from pm4py.algo.discovery.dfg.adapters.pandas import df_statistics +import pandas as pd + + +class Parameters(Enum): + 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 + + +class Variants(Enum): + NATIVE = native + FREQUENCY = native + PERFORMANCE = performance + FREQUENCY_GREEDY = native + PERFORMANCE_GREEDY = performance + FREQ_TRIPLES = freq_triples + CASE_ATTRIBUTES = case_attributes + CLEAN = clean # 'novel' replacement for native + + +DFG_NATIVE = Variants.NATIVE +DFG_FREQUENCY = Variants.FREQUENCY +DFG_PERFORMANCE = Variants.PERFORMANCE +DFG_FREQUENCY_GREEDY = Variants.FREQUENCY_GREEDY +DFG_PERFORMANCE_GREEDY = Variants.PERFORMANCE_GREEDY +FREQ_TRIPLES = Variants.FREQ_TRIPLES +DFG_CLEAN = Variants.CLEAN + +DEFAULT_VARIANT = Variants.NATIVE + +VERSIONS = { + DFG_NATIVE, + DFG_FREQUENCY, + DFG_PERFORMANCE, + DFG_FREQUENCY_GREEDY, + DFG_PERFORMANCE_GREEDY, + FREQ_TRIPLES, +} + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + parameters: Optional[Dict[Any, Any]] = None, + variant=DEFAULT_VARIANT, +) -> Dict[Tuple[str, str], float]: + """ + Calculates DFG graph (frequency or performance) starting from a log + + Parameters + ---------- + log + Log + parameters + Possible parameters passed to the algorithms: + Parameters.AGGREGATION_MEASURE -> performance aggregation measure (min, max, mean, median) + Parameters.ACTIVITY_KEY -> Attribute to use as activity + Parameters.TIMESTAMP_KEY -> Attribute to use as timestamp + variant + Variant of the algorithm to use, possible values: + - Variants.NATIVE + - Variants.FREQUENCY + - Variants.FREQUENCY_GREEDY + - Variants.PERFORMANCE + - Variants.PERFORMANCE_GREEDY + - Variants.FREQ_TRIPLES + + Returns + ------- + dfg: dict + DFG graph + """ + if variant == Variants.CLEAN and pandas_utils.check_is_pandas_dataframe( + log + ): + return clean.apply(log, parameters) + elif variant is None: + variant = Variants.NATIVE + + if parameters is None: + parameters = {} + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, parameters, None + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY + ) + case_id_glue = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, pmutil.constants.CASE_CONCEPT_NAME + ) + + if ( + pandas_utils.check_is_pandas_dataframe(log) + and not variant == Variants.FREQ_TRIPLES + ): + dfg_frequency, dfg_performance = df_statistics.get_dfg_graph( + log, + measure="both", + activity_key=activity_key, + timestamp_key=timestamp_key, + case_id_glue=case_id_glue, + start_timestamp_key=start_timestamp_key, + ) + if variant in [Variants.PERFORMANCE, Variants.PERFORMANCE_GREEDY]: + return dfg_performance + else: + return dfg_frequency + + return exec_utils.get_variant(variant).apply( + log_conversion.apply(log, parameters, log_conversion.TO_EVENT_LOG), + parameters=parameters, + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/replacement.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/replacement.py new file mode 100644 index 0000000000000000000000000000000000000000..dfadb4a63140c840a1c0603b0869b8a8d18dc949 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/replacement.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 +''' +def replace_values(dfg1, dfg2): + """ + Replace edge values specified in a DFG by values from a (potentially bigger) DFG + + Parameters + ----------- + dfg1 + First specified DFG (where values of edges should be replaces) + dfg2 + Second specified DFG (from which values should be taken) + + Returns + ----------- + dfg1 + First specified DFG with overrided values + """ + for edge in dfg1: + if edge in dfg2: + dfg1[edge] = dfg2[edge] + return dfg1 diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1957e86b27b2cb6dbd2f50c41e1d171c44cf4357 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/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.algo.discovery.dfg.utils import dfg_utils diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/utils/dfg_utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/utils/dfg_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fd0f0f27149bfc40c092f60754ce4131faf731f7 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/utils/dfg_utils.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.dfg_utils import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e2202343a12e9a9cec5c14f8e4e61083e3a0649 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/__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.algo.discovery.dfg.variants import ( + native, + performance, + freq_triples, + case_attributes, + clean, +) +import importlib.util + +if importlib.util.find_spec("polars"): + from pm4py.algo.discovery.dfg.variants import clean_polars diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/case_attributes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/case_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..e5bcce2aaf41870b063596f792c5de3f4c276531 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/case_attributes.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 +''' +from enum import Enum +from typing import Optional, Dict, Any, Tuple, Union + +from pm4py.objects.conversion.log import converter as log_converter +from pm4py.objects.log.obj import EventLog +from pm4py.util import exec_utils, constants, xes_constants + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + CASE_ATTRIBUTES = "case_attributes" + RETURN_NODES_ATTRIBUTES = "return_nodes_attributes" + + +def apply( + log: EventLog, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Union[ + Tuple[ + Dict[Tuple[str, str], Dict[str, Dict[str, Any]]], + Dict[str, Dict[str, Dict[str, Any]]], + ], + Dict[Tuple[str, str], Dict[str, Dict[str, Any]]], +]: + """ + Discovers a directly-follows graph from an event log, with the edges that are annotated with the different values + for the given case attributes. + + Parameters + ----------------- + log + Event log + parameters + Parameters of the variant, including: + - Parameters.ACTIVITY_KEY => the attribute to use as activity + - Parameters.CASE_ATTRIBUTES => the case attributes that are used to annotate the edges (default: the case ID) + - Parameters.RETURN_NODES_ATTRIBUTES => (optional) returns also a dictionary with the values of the + attributes for each activity of the graph (default: False) + + Returns + ----------------- + dfg + Directly-follows graph (with the edges annotated with the specified case attributes), e.g.: + {('register request', 'examine casually'): {'creator': {'Fluxicon Nitro': 3}, 'concept:name': + {'3': 1, '6': 1, '5': 1}} ... + nodes + (Optional) dictionary of activities (annotated with the specified case attributes), e.g.: + {'register request': {'creator': {'Fluxicon Nitro': 6}, 'concept:name': + {'3': 1, '2': 1, '1': 1, '6': 1, '5': 1, '4': 1}} ... + """ + if parameters is None: + parameters = {} + + log = log_converter.apply( + log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters + ) + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + case_attributes = exec_utils.get_param_value( + Parameters.CASE_ATTRIBUTES, + parameters, + list([xes_constants.DEFAULT_TRACEID_KEY]), + ) + return_nodes_attributes = exec_utils.get_param_value( + Parameters.RETURN_NODES_ATTRIBUTES, parameters, False + ) + dfg = {} + + for trace in log: + for attr in set(case_attributes).intersection(set(trace.attributes)): + attr_value = trace.attributes[attr] + for i in range(len(trace) - 1): + ev_couple = ( + trace[i][activity_key], + trace[i + 1][activity_key], + ) + if ev_couple not in dfg: + dfg[ev_couple] = {} + if attr not in dfg[ev_couple]: + dfg[ev_couple][attr] = {} + if attr_value not in dfg[ev_couple][attr]: + dfg[ev_couple][attr][attr_value] = 0 + dfg[ev_couple][attr][attr_value] += 1 + + if return_nodes_attributes: + nodes = {} + for trace in log: + for attr in set(case_attributes).intersection( + set(trace.attributes) + ): + attr_value = trace.attributes[attr] + for i in range(len(trace)): + act = trace[i][activity_key] + if act not in nodes: + nodes[act] = {} + if attr not in nodes[act]: + nodes[act][attr] = {} + if attr_value not in nodes[act][attr]: + nodes[act][attr][attr_value] = 0 + nodes[act][attr][attr_value] += 1 + + return dfg, nodes + + return dfg diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean.py new file mode 100644 index 0000000000000000000000000000000000000000..406145df6a10a5f729381389bbf7533cef464e39 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean.py @@ -0,0 +1,114 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 enum import Enum +from typing import Optional, Dict, Any + +import numpy as np +import pandas as pd + +from pm4py.objects.dfg.obj import DFG +from pm4py.util import constants, exec_utils +from pm4py.util import xes_constants as xes_util + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY + TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY + + +CONST_AUX_ACT_START = "aux_act_start" +CONST_PROCESS_START = "#!$#PROCESS_START#!$#" +CONST_AUX_ACT_END = "aux_act_end" +CONST_PROCESS_END = "#!$#PROCESS_END#!$#" + + +def apply( + log: pd.DataFrame, parameters: Optional[Dict[str, Any]] = None +) -> DFG: + parameters = {} if parameters is None else parameters + act_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + cid_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_ATTRIBUTE_GLUE + ) + time_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY + ) + + df = ( + log.sort_values([cid_key, time_key]) + .loc[:, [cid_key, act_key]] + .reset_index() + ) + + aux_act_start = CONST_AUX_ACT_START + str(time.time()) + aux_act_end = CONST_AUX_ACT_END + str(time.time()) + df[aux_act_start] = ( + df.groupby(cid_key)[act_key] + .shift(1) + .replace(np.nan, CONST_PROCESS_START) + ) + df[aux_act_end] = ( + df.groupby(cid_key)[act_key] + .shift(-1) + .replace(np.nan, CONST_PROCESS_END) + ) + + starters = df[(df[aux_act_start] == CONST_PROCESS_START)] + borders = df[(df[aux_act_end] == CONST_PROCESS_END)] + connections = df[ + ( + (df[aux_act_start] != CONST_PROCESS_START) + & (df[aux_act_end] != CONST_PROCESS_END) + ) + ] + + dfg = DFG() + + for a, b, f in list( + connections.groupby([act_key, aux_act_end]) + .size() + .reset_index() + .itertuples(index=False, name=None) + ): + dfg.graph[(a, b)] += f + + for a, f in list( + starters.groupby([act_key]) + .size() + .reset_index() + .itertuples(index=False, name=None) + ): + dfg.start_activities[a] += f + + for a, f in list( + borders.groupby([act_key]) + .size() + .reset_index() + .itertuples(index=False, name=None) + ): + dfg.end_activities[a] += f + + return dfg diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean_polars.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean_polars.py new file mode 100644 index 0000000000000000000000000000000000000000..572ecc24e1f404234da0b355f1ee06f9c0f7357a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean_polars.py @@ -0,0 +1,87 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 enum import Enum +from typing import Optional, Dict, Any, Union + +import polars as pl + +from pm4py.objects.dfg.obj import DFG +from pm4py.util import constants, exec_utils +from pm4py.util import xes_constants as xes_util + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY + TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY + + +CONST_AUX_ACT = "aux_act_" +CONST_AUX_CASE = "aux_case_" +CONST_COUNT = "count_" + + +def apply( + log: Union[pl.DataFrame, pl.LazyFrame], parameters: Optional[Dict[str, Any]] = None +) -> DFG: + parameters = {} if parameters is None else parameters + act_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + cid_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_ATTRIBUTE_GLUE + ) + time_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY + ) + aux_act = CONST_AUX_ACT + str(time.time()) + df = log.lazy() if isinstance(log, pl.DataFrame) else log + df = df.select([cid_key, act_key, time_key]).sort( + [cid_key, time_key], maintain_order=True + ) + cases = df.group_by(cid_key).agg( + pl.col(act_key).first().alias("__start_activity"), + pl.col(act_key).last().alias("__end_activity"), + ) + dfg = DFG() + + for column, counts in ( + ("__start_activity", dfg.start_activities), + ("__end_activity", dfg.end_activities), + ): + activities = cases.group_by(column).len(name="count").collect() + for activity, count in activities.iter_rows(): + if activity is not None: + counts[activity] = count + + for d in ( + df.with_columns(pl.col(act_key).shift(-1).over(cid_key).alias(aux_act)) + .filter(pl.col(act_key).is_not_null() & pl.col(aux_act).is_not_null()) + .group_by([act_key, aux_act]) + .len(name="count") + .collect() + .to_dicts() + ): + dfg.graph[(d[act_key], d[aux_act])] = d["count"] + + return dfg diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean_time.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean_time.py new file mode 100644 index 0000000000000000000000000000000000000000..186a711afb48cd84c21c77794dddec72e70cd485 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/clean_time.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 +''' + +import time +from enum import Enum +from typing import List, Optional, Dict, Any + +import pandas as pd +import numpy as np +from pandas._libs.tslibs.timestamps import Timestamp +from pandas.core.frame import DataFrame +from pandas.core.tools.datetimes import to_datetime + +from pm4py.objects.dfg.obj import DFG +from pm4py.util import constants, exec_utils +from pm4py.util import xes_constants as xes_util + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY + TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY + + +CONST_AUX_ACT = 'aux_act_' +CONST_AUX_CASE = 'aux_case_' +CONST_COUNT = 'count_' + + +from pm4py.discovery import discover_dfg_typed + + +def apply(log: pd.DataFrame, parameters=None): + if parameters is None: + parameters = {} + + act_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY) + cid_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_ATTRIBUTE_GLUE) + time_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY) + + '''sort the values according to cid and timekey''' + df = log.sort_values([cid_key, time_key]).loc[:, [cid_key, act_key, time_key]].reset_index() + + '''mapping each case ID to the first time stamp of that case.''' + grouped = df.groupby(cid_key) + all_cases = df[cid_key].unique() + + time_dictionary_list = {} + + for case in all_cases: + current_group = grouped.get_group(case) + current_group = current_group.sort_values([cid_key, time_key]).loc[:, [cid_key, act_key, time_key]].reset_index() + + all_act = current_group[act_key].unique() + init_timestamp = current_group[time_key][0] + '''deal with loops in a case''' + for act in all_act: + df1 = current_group[current_group[act_key] == act] + mean_time = df1[time_key].mean() + average_time = mean_time - init_timestamp + + if act not in time_dictionary_list.keys(): + time_dictionary_list[act] = [] + time_dictionary_list[act].append(average_time) + else: + time_dictionary_list[act].append(average_time) + + + keys = time_dictionary_list.keys() + time_dictionary = {} + for key in keys: + avg=pd.to_timedelta(pd.Series(time_dictionary_list[key])).mean() + time_dictionary[key] = avg + + return time_dictionary + diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/freq_triples.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/freq_triples.py new file mode 100644 index 0000000000000000000000000000000000000000..ed4d8e50251af49711d459ef9ca42ba0b1444256 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/freq_triples.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 collections import Counter +from enum import Enum + +from pm4py.util import constants, exec_utils +from pm4py.util import xes_constants as xes_util +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + + +def apply( + log: Union[EventLog, EventStream], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[Tuple[str, str, str], int]: + return freq_triples(log, parameters=parameters) + + +def freq_triples( + log: Union[EventLog, EventStream], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[Tuple[str, str, str], int]: + """ + Counts the number of directly follows occurrences, i.e. of the form <...a,b...>, in an event log. + + Parameters + ---------- + log + Trace log + parameters + Possible parameters passed to the algorithms: + activity_key -> Attribute to use as activity + + Returns + ------- + dfg: dict + DFG graph + """ + if parameters is None: + parameters = {} + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + dfgs = map( + ( + lambda t: [ + ( + t[i - 2][activity_key], + t[i - 1][activity_key], + t[i][activity_key], + ) + for i in range(2, len(t)) + ] + ), + log, + ) + return dict(Counter([dfg for lista in dfgs for dfg in lista])) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/native.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/native.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4f0d51a40f3302c2fc32d868da9a5ab1017a40 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/native.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 +''' +from collections import Counter + +from pm4py.util import constants, exec_utils +from pm4py.util import xes_constants as xes_util +from enum import Enum +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + WINDOW = "window" + KEEP_ONCE_PER_CASE = "keep_once_per_case" + + +def apply( + log: Union[EventLog, EventStream], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[Tuple[str, str], int]: + return native(log, parameters=parameters) + + +def native( + log: Union[EventLog, EventStream], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[Tuple[str, str], int]: + """ + Counts the number of directly follows occurrences, i.e. of the form <...a,b...>, in an event log. + + Parameters + ---------- + log + Trace log + parameters + Possible parameters passed to the algorithms: + activity_key -> Attribute to use as activity + + Returns + ------- + dfg: dict + DFG graph + """ + if parameters is None: + parameters = {} + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + window = exec_utils.get_param_value(Parameters.WINDOW, parameters, 1) + keep_once_per_case = exec_utils.get_param_value( + Parameters.KEEP_ONCE_PER_CASE, parameters, False + ) + if keep_once_per_case: + dfgs = map( + ( + lambda t: set( + (t[i - window][activity_key], t[i][activity_key]) + for i in range(window, len(t)) + ) + ), + log, + ) + else: + dfgs = map( + ( + lambda t: [ + (t[i - window][activity_key], t[i][activity_key]) + for i in range(window, len(t)) + ] + ), + log, + ) + return Counter([dfg for lista in dfgs for dfg in lista]) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/performance.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/performance.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc3fe1785586fc661cee9a1f40d8b492a745211 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/dfg/variants/performance.py @@ -0,0 +1,190 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 pm4py.util import constants, exec_utils +from pm4py.util import xes_constants as xes_util +from pm4py.util.business_hours import BusinessHours +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY + TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY + AGGREGATION_MEASURE = "aggregationMeasure" + BUSINESS_HOURS = "business_hours" + BUSINESS_HOUR_SLOTS = "business_hour_slots" + WORKCALENDAR = "workcalendar" + + +def apply( + log: Union[EventLog, EventStream], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[Tuple[str, str], float]: + return performance(log, parameters=parameters) + + +def performance( + log: Union[EventLog, EventStream], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[Tuple[str, str], float]: + """ + Measure performance between couples of attributes in the DFG graph. + + Parameters + ---------- + log + Log + parameters + Possible parameters passed to the algorithms: + aggregationMeasure -> performance aggregation measure (min, max, mean, median) + activity_key -> Attribute to use as activity + timestamp_key -> Attribute to use as timestamp + + - Parameters.BUSINESS_HOURS => calculates the difference of time based on the business hours, not the total time. Default: False + - Parameters.BUSINESS_HOURS_SLOTS => work schedule of the company. + The following list defines that business hours are Mondays 07:00 - 17:00 + and Tuesdays 07:00 - 12:00 and 13:00 - 17:00:: + + [ + (7 * 60 * 60, 17 * 60 * 60), + ((24 + 7) * 60 * 60, (24 + 12) * 60 * 60), + ((24 + 13) * 60 * 60, (24 + 17) * 60 * 60), + ] + Returns + ------- + dfg : dict + DFG graph + + """ + + if parameters is None: + parameters = {} + + from statistics import mean, median, stdev + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, + parameters, + xes_util.DEFAULT_TIMESTAMP_KEY, + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY + ) + aggregation_measure = exec_utils.get_param_value( + Parameters.AGGREGATION_MEASURE, parameters, "mean" + ) + + 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, + ) + + workcalendar = exec_utils.get_param_value( + Parameters.WORKCALENDAR, + parameters, + constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR, + ) + + if business_hours: + dfgs0 = map( + ( + lambda t: [ + ( + (t[i - 1][activity_key], t[i][activity_key]), + max( + 0, + BusinessHours( + t[i - 1][timestamp_key], + t[i][start_timestamp_key], + business_hour_slots=business_hours_slots, + workcalendar=workcalendar, + ).get_seconds(), + ), + ) + for i in range(1, len(t)) + ] + ), + log, + ) + else: + dfgs0 = map( + ( + lambda t: [ + ( + (t[i - 1][activity_key], t[i][activity_key]), + max( + 0, + ( + t[i][start_timestamp_key] + - t[i - 1][timestamp_key] + ).total_seconds(), + ), + ) + for i in range(1, len(t)) + ] + ), + log, + ) + ret0 = {} + for el in dfgs0: + for couple in el: + if couple[0] not in ret0: + ret0[couple[0]] = [] + ret0[couple[0]].append(couple[1]) + ret = Counter() + for key in ret0: + if aggregation_measure == "median": + ret[key] = median(ret0[key]) + elif aggregation_measure == "min": + ret[key] = min(ret0[key]) + elif aggregation_measure == "max": + ret[key] = max(ret0[key]) + elif aggregation_measure == "stdev": + ret[key] = stdev(ret0[key]) if len(ret0[key]) > 1 else 0 + elif aggregation_measure == "sum": + ret[key] = sum(ret0[key]) + elif aggregation_measure == "raw_values": + ret[key] = ret0[key] + elif aggregation_measure == "all": + ret[key] = { + "median": median(ret0[key]), + "min": min(ret0[key]), + "max": max(ret0[key]), + "stdev": stdev(ret0[key]) if len(ret0[key]) > 1 else 0, + "sum": sum(ret0[key]), + "mean": mean(ret0[key]), + } + else: + ret[key] = mean(ret0[key]) + + return ret diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7104e0098091ffbab4642ac0c7134fda45b8f8e2 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/__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.discovery.footprints import log, petri, dfg, algorithm, tree diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..c7685ca9ca24c464245e4ff51206431a1e61a6a1 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/algorithm.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 +''' +from pm4py.algo.discovery.footprints.log.variants import ( + entire_event_log, + trace_by_trace, + entire_dataframe, +) +from pm4py.algo.discovery.footprints.petri.variants import reach_graph +from pm4py.algo.discovery.footprints.dfg.variants import dfg +from pm4py.algo.discovery.footprints.tree.variants import bottomup +from pm4py.algo.discovery.footprints.powl.variants import bottomup as bottomup_powl +from pm4py.objects.log.obj import EventLog +from pm4py.objects.petri_net.obj import PetriNet +from pm4py.objects.process_tree.obj import ProcessTree +from enum import Enum +from pm4py.util import exec_utils, pandas_utils +from pm4py.utils import is_polars_lazyframe +import pandas as pd +from typing import Optional, Dict, Any +import importlib.util + +POLARS_AVAILABLE = importlib.util.find_spec("polars") is not None +if POLARS_AVAILABLE: + from pm4py.algo.discovery.footprints.log.variants import polars_lazyframes + + +class Variants(Enum): + ENTIRE_EVENT_LOG = entire_event_log + ENTIRE_DATAFRAME = entire_dataframe + TRACE_BY_TRACE = trace_by_trace + PETRI_REACH_GRAPH = reach_graph + PROCESS_TREE = bottomup + POWL = bottomup_powl + DFG = dfg + POLARS_LAZYFRAMES = polars_lazyframes if POLARS_AVAILABLE else entire_dataframe + + +def apply( + *args, variant=None, parameters: Optional[Dict[Any, Any]] = None +) -> Dict[str, Any]: + """ + Discovers a footprint object from a log/model + + Parameters + -------------- + args + Positional arguments that describe the log/model + parameters + Parameters of the algorithm + variant + Variant of the algorithm, including: + - Variants.ENTIRE_EVENT_LOG + - Variants.TRACE_BY_TRACE + - Variants.PETRI_REACH_GRAPH + - Variants.DFG + + Returns + -------------- + footprints_obj + Footprints object + """ + from pm4py.objects.powl.obj import POWL, StrictPartialOrder, OperatorPOWL + + if variant is None: + if type(args[0]) is EventLog: + variant = Variants.TRACE_BY_TRACE + elif type(args[0]) is PetriNet: + variant = Variants.PETRI_REACH_GRAPH + elif isinstance(args[0], POWL): + variant = Variants.POWL + elif type(args[0]) is ProcessTree: + variant = Variants.PROCESS_TREE + elif isinstance(args[0], dict): + variant = Variants.DFG + + if pandas_utils.check_is_pandas_dataframe(args[0]): + if is_polars_lazyframe(args[0]): + if not POLARS_AVAILABLE: + raise RuntimeError( + "Polars LazyFrame provided but 'polars' package is not installed." + ) + variant = Variants.POLARS_LAZYFRAMES + else: + variant = Variants.ENTIRE_DATAFRAME + + if variant is None: + return Exception("unsupported arguments") + + if variant in [ + Variants.TRACE_BY_TRACE, + Variants.ENTIRE_EVENT_LOG, + Variants.DFG, + Variants.PROCESS_TREE, + Variants.POWL, + Variants.ENTIRE_DATAFRAME, + Variants.POLARS_LAZYFRAMES, + ]: + return exec_utils.get_variant(variant).apply( + args[0], parameters=parameters + ) + elif variant in [Variants.PETRI_REACH_GRAPH]: + return exec_utils.get_variant(variant).apply( + args[0], args[1], parameters=parameters + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb4d677cbe8259906a07ccc217baca0a0a698d43 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/__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.discovery.footprints.dfg import variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb9d40f58cedd06b4cda619783895f5502f46603 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/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.algo.discovery.footprints.dfg.variants import dfg diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/variants/dfg.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/variants/dfg.py new file mode 100644 index 0000000000000000000000000000000000000000..27489247da3668c7a8d8ee14fe8814be43a092f6 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/dfg/variants/dfg.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.dfg import utils +from enum import Enum +from typing import Optional, Dict, Any, Tuple + + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + TRACE = "trace" + + +def apply( + dfg: Dict[Tuple[str, str], int], + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Any]: + """ + Discovers a footprint object from a DFG + + Parameters + -------------- + dfg + DFG + parameters + Parameters of the algorithm + + Returns + -------------- + footprints_obj + Footprints object + """ + if parameters is None: + parameters = {} + + parallel = {(x, y) for (x, y) in dfg if (y, x) in dfg} + sequence = {(x, y) for (x, y) in dfg if not (y, x) in dfg} + # replace this if needed + start_activities = set(utils.dfg_utils.infer_start_activities(dfg)) + # replace this if needed + end_activities = set(utils.dfg_utils.infer_end_activities(dfg)) + activities = set(utils.dfg_utils.get_activities_from_dfg(dfg)) + + return { + Outputs.SEQUENCE.value: sequence, + Outputs.PARALLEL.value: parallel, + Outputs.START_ACTIVITIES.value: start_activities, + Outputs.END_ACTIVITIES.value: end_activities, + Outputs.ACTIVITIES.value: activities, + } diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd8ffe1fee3abc1f738da254d8f7d81a4ed5028 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/__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.discovery.footprints.log import variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ccf80d50d16472eb2a6c801b87d76258c5159fe --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/__init__.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 pm4py.algo.discovery.footprints.log.variants import ( + entire_event_log, + trace_by_trace, + entire_dataframe, +) + +import importlib.util + +if importlib.util.find_spec("polars"): + from pm4py.algo.discovery.footprints.log.variants import polars_lazyframes # type: ignore[F401] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/entire_dataframe.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/entire_dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..6f811935242368838efbeaaf2b9f19c70464a2af --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/entire_dataframe.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 +''' +from pm4py.util import xes_constants +from pm4py.util import constants +from pm4py.algo.discovery.dfg.adapters.pandas import df_statistics +from pm4py.util import exec_utils, pandas_utils +from pm4py.algo.discovery.causal import algorithm as causal_discovery +from enum import Enum +from typing import Optional, Dict, Any, Union +import pandas as pd + + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + TRACE = "trace" + + +class Parameters(Enum): + SORT_REQUIRED = "sort_required" + 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 + INDEX_KEY = "index_key" + + +DEFAULT_SORT_REQUIRED = True +DEFAULT_INDEX_KEY = "@@index" + + +def apply( + df: pd.DataFrame, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """ + Discovers a footprint object from a dataframe + (the footprints of the dataframe are returned) + + Parameters + -------------- + df + Dataframe + parameters + Parameters of the algorithm + + Returns + -------------- + footprints_obj + Footprints object + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + caseid_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, None + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + sort_required = exec_utils.get_param_value( + Parameters.SORT_REQUIRED, parameters, DEFAULT_SORT_REQUIRED + ) + index_key = exec_utils.get_param_value( + Parameters.INDEX_KEY, parameters, DEFAULT_INDEX_KEY + ) + + df = df[[caseid_key, activity_key, timestamp_key]] + if sort_required: + df = pandas_utils.insert_index(df, index_key) + if start_timestamp_key is not None: + df = df.sort_values( + [caseid_key, start_timestamp_key, timestamp_key, index_key] + ) + else: + df = df.sort_values([caseid_key, timestamp_key, index_key]) + + grouped_df = df.groupby(caseid_key) + dfg = df_statistics.get_dfg_graph( + df, + measure="frequency", + activity_key=activity_key, + case_id_glue=caseid_key, + timestamp_key=timestamp_key, + sort_caseid_required=False, + sort_timestamp_along_case_id=False, + start_timestamp_key=start_timestamp_key, + ) + activities = set(pandas_utils.format_unique(df[activity_key].unique())) + start_activities = set( + pandas_utils.format_unique(grouped_df.first()[activity_key].unique()) + ) + end_activities = set( + pandas_utils.format_unique(grouped_df.last()[activity_key].unique()) + ) + + parallel = {(x, y) for (x, y) in dfg if (y, x) in dfg} + sequence = set( + causal_discovery.apply(dfg, causal_discovery.Variants.CAUSAL_ALPHA) + ) + + ret = {} + ret[Outputs.DFG.value] = dfg + ret[Outputs.SEQUENCE.value] = sequence + ret[Outputs.PARALLEL.value] = parallel + ret[Outputs.ACTIVITIES.value] = activities + ret[Outputs.START_ACTIVITIES.value] = start_activities + ret[Outputs.END_ACTIVITIES.value] = end_activities + ret[Outputs.MIN_TRACE_LENGTH.value] = int(grouped_df.size().min()) + + return ret diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/entire_event_log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/entire_event_log.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb0b516005d366fa3d2dd3645f93841d935926c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/entire_event_log.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.util import xes_constants +from pm4py.util import constants +from pm4py.algo.discovery.dfg import algorithm as dfg_discovery +from pm4py.algo.discovery.causal import algorithm as causal_discovery +from pm4py.statistics.start_activities.log import get as get_start_activities +from pm4py.statistics.end_activities.log import get as get_end_activities +from pm4py.objects.conversion.log import converter +from pm4py.util import exec_utils +from enum import Enum +from typing import Optional, Dict, Any, Union +from pm4py.objects.log.obj import EventLog + + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + TRACE = "trace" + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + + +def apply( + log: EventLog, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """ + Discovers a footprint object from an event log + (the footprints of the event log are returned) + + Parameters + -------------- + log + Log + parameters + Parameters of the algorithm: + - Parameters.ACTIVITY_KEY + + Returns + -------------- + footprints_obj + Footprints object + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + + log = converter.apply( + log, variant=converter.TO_EVENT_LOG, parameters=parameters + ) + + dfg = dfg_discovery.apply(log, parameters=parameters) + parallel = {(x, y) for (x, y) in dfg if (y, x) in dfg} + sequence = set( + causal_discovery.apply(dfg, causal_discovery.Variants.CAUSAL_ALPHA) + ) + + start_activities = set( + get_start_activities.get_start_activities(log, parameters=parameters) + ) + end_activities = set( + get_end_activities.get_end_activities(log, parameters=parameters) + ) + activities = set(y[activity_key] for x in log for y in x) + + return { + Outputs.DFG.value: dfg, + Outputs.SEQUENCE.value: sequence, + Outputs.PARALLEL.value: parallel, + Outputs.START_ACTIVITIES.value: start_activities, + Outputs.END_ACTIVITIES.value: end_activities, + Outputs.ACTIVITIES.value: activities, + Outputs.MIN_TRACE_LENGTH.value: ( + min(len(x) for x in log) if len(log) > 0 else 0 + ), + } diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/polars_lazyframes.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/polars_lazyframes.py new file mode 100644 index 0000000000000000000000000000000000000000..dc20dbe56bfb50638f21a38ad3264102d04a9609 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/polars_lazyframes.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 enum import Enum +from typing import Optional, Dict, Any, Union + +import importlib.util + +from pm4py.util import xes_constants, constants, exec_utils, pandas_utils +from pm4py.algo.discovery.causal import algorithm as causal_discovery + + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + TRACE = "trace" + + +class Parameters(Enum): + SORT_REQUIRED = "sort_required" + 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 + INDEX_KEY = "index_key" + + +DEFAULT_SORT_REQUIRED = True +DEFAULT_INDEX_KEY = "@@index" + + +def apply( + lf, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + if parameters is None: + parameters = {} + + 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] + from pm4py.algo.discovery.dfg.adapters.polars import df_statistics + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + caseid_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, None + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + sort_required = exec_utils.get_param_value( + Parameters.SORT_REQUIRED, parameters, DEFAULT_SORT_REQUIRED + ) + index_key = exec_utils.get_param_value( + Parameters.INDEX_KEY, parameters, DEFAULT_INDEX_KEY + ) + + required_columns = {caseid_key, activity_key, timestamp_key} + if start_timestamp_key is not None: + required_columns.add(start_timestamp_key) + + if hasattr(lf, "collect_schema"): + lf_columns = lf.collect_schema().names() + else: + lf_columns = lf.columns + + missing_columns = [col for col in required_columns if col not in lf_columns] + if missing_columns: + raise Exception( + "The provided Polars LazyFrame does not contain the following required columns: " + + ", ".join(sorted(missing_columns)) + ) + + lf_selected = lf.select(list(required_columns)) + + if sort_required: + lf_selected = pandas_utils.insert_index( + lf_selected, column_name=index_key, copy_dataframe=False + ) + + sort_columns = [caseid_key] + if start_timestamp_key is not None: + sort_columns.append(start_timestamp_key) + sort_columns.append(timestamp_key) + sort_columns.append(index_key) + + lf_selected = lf_selected.sort(sort_columns, maintain_order=True) + + dfg = df_statistics.get_dfg_graph( + lf_selected, + measure="frequency", + activity_key=activity_key, + case_id_glue=caseid_key, + timestamp_key=timestamp_key, + sort_caseid_required=False, + sort_timestamp_along_case_id=False, + start_timestamp_key=start_timestamp_key, + ) + + activities_df = ( + lf_selected.select(pl.col(activity_key).unique().alias("__act__")) + .collect() + ) + activities = set(activities_df["__act__"].to_list()) + + grouped = lf_selected.group_by(caseid_key) + first_df = grouped.agg(pl.col(activity_key).first().alias("__first__")) + last_df = grouped.agg(pl.col(activity_key).last().alias("__last__")) + + start_activities = set(first_df.collect()["__first__"].to_list()) + end_activities = set(last_df.collect()["__last__"].to_list()) + + parallel = {(x, y) for (x, y) in dfg if (y, x) in dfg} + sequence = set( + causal_discovery.apply(dfg, causal_discovery.Variants.CAUSAL_ALPHA) + ) + + min_trace_length_df = grouped.agg(pl.len().alias("__size__")).collect() + min_trace_length = int(min_trace_length_df["__size__"].min()) + + ret: Dict[str, Any] = {} + ret[Outputs.DFG.value] = dfg + ret[Outputs.SEQUENCE.value] = sequence + ret[Outputs.PARALLEL.value] = parallel + ret[Outputs.ACTIVITIES.value] = activities + ret[Outputs.START_ACTIVITIES.value] = start_activities + ret[Outputs.END_ACTIVITIES.value] = end_activities + ret[Outputs.MIN_TRACE_LENGTH.value] = min_trace_length + + return ret + diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/trace_by_trace.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/trace_by_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..7222bb72a294b5155a707ad35a5d25b547a8233e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/log/variants/trace_by_trace.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.util import constants +from pm4py.algo.discovery.dfg import algorithm as dfg_discovery +from pm4py.objects.conversion.log import converter +from pm4py.util import xes_constants +from pm4py.util import exec_utils +from enum import Enum +from typing import Optional, Dict, Any, Union +from pm4py.objects.log.obj import EventLog + + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + TRACE = "trace" + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + + +def apply( + log, parameters: Optional[Dict[Union[str, Parameters], Any]] = None +) -> Dict[str, Any]: + """ + Discovers a footprint object from an event log + (the footprints are returned case-by-case) + + Parameters + -------------- + log + Log + parameters + Parameters of the algorithm: + - Parameters.ACTIVITY_KEY + + Returns + -------------- + footprints_obj + List of footprints for the cases of the log + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + + log = converter.apply( + log, variant=converter.TO_EVENT_LOG, parameters=parameters + ) + + ret = [] + + for trace in log: + dfg = dfg_discovery.apply(EventLog([trace]), parameters=parameters) + parallel = {(x, y) for (x, y) in dfg if (y, x) in dfg} + sequence = {(x, y) for (x, y) in dfg if not (y, x) in dfg} + trace = tuple(x[activity_key] for x in trace) + activities = set(trace) + if len(trace) > 0: + start_activities = {trace[0]} + end_activities = {trace[-1]} + else: + start_activities = set() + end_activities = set() + + ret.append( + { + Outputs.DFG.value: dfg, + Outputs.SEQUENCE.value: sequence, + Outputs.PARALLEL.value: parallel, + Outputs.ACTIVITIES.value: activities, + Outputs.START_ACTIVITIES.value: start_activities, + Outputs.END_ACTIVITIES.value: end_activities, + Outputs.MIN_TRACE_LENGTH.value: len(trace), + Outputs.TRACE.value: trace, + } + ) + + return ret diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d24e2089dd52ed121e54fa15f801e2e241163d3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/__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.discovery.footprints.petri import variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e011e0b4b16b629df3b50d816f0e4f4ec82d570 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/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.algo.discovery.footprints.petri.variants import reach_graph diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/variants/reach_graph.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/variants/reach_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..c77cd711148e18cba78ca0e622747c70afafa0b1 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/petri/variants/reach_graph.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 pm4py.objects.petri_net.utils import reachability_graph +import itertools +from enum import Enum +from typing import Optional, Dict, Any +from pm4py.objects.petri_net.obj import PetriNet, Marking + + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + TRACE = "trace" + + +def findsubsets(s, n): + return list(itertools.combinations(s, n)) + + +def apply( + net: PetriNet, im: Marking, parameters: Optional[Dict[Any, Any]] = None +) -> Dict[str, Any]: + """ + Discovers a footprint object from a Petri net + + Parameters + -------------- + net + Petri net + im + Initial marking + parameters + Parameters of the algorithm + + Returns + -------------- + footprints_obj + Footprints object + """ + if parameters is None: + parameters = {} + + incoming_transitions, outgoing_transitions, eventually_enabled = ( + reachability_graph.marking_flow_petri( + net, im, return_eventually_enabled=True, parameters=parameters + ) + ) + + sequence = set() + + s1 = set() + s2 = set() + + for m in outgoing_transitions: + input_trans = set( + x for x in incoming_transitions[m] if x.label is not None + ) + output_trans = set( + x for x in outgoing_transitions[m].keys() if x.label is not None + ) + ev_en = set(x for x in eventually_enabled[m]) + two_sets = findsubsets(output_trans, 2) + + for x, y in two_sets: + s1.add((x, y)) + s1.add((y, x)) + + for t1 in input_trans: + for t2 in ev_en: + sequence.add((t1, t2)) + for t2 in output_trans: + s2.add((t1, t2)) + + parallel = {(x, y) for (x, y) in s2 if (y, x) in s2 and (x, y) in s1} + sequence = {(x, y) for (x, y) in sequence if not (x, y) in parallel} + + parallel = {(x.label, y.label) for (x, y) in parallel} + sequence = {(x.label, y.label) for (x, y) in sequence} + + par_els = {(x[0], x[1]) for x in sequence if (x[1], x[0]) in sequence} + for el in par_els: + parallel.add(el) + sequence.remove(el) + + activities = set(x.label for x in net.transitions if x.label is not None) + start_activities = set(x.label for x in eventually_enabled[im]) + + return { + Outputs.SEQUENCE.value: sequence, + Outputs.PARALLEL.value: parallel, + Outputs.ACTIVITIES.value: activities, + Outputs.START_ACTIVITIES.value: start_activities, + } diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/powl/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/powl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/powl/__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/algo/discovery/footprints/powl/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/powl/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/powl/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/algo/discovery/footprints/powl/variants/bottomup.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/powl/variants/bottomup.py new file mode 100644 index 0000000000000000000000000000000000000000..9a20aae902b2232ba274d71efce9bbc3e3bebc1c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/powl/variants/bottomup.py @@ -0,0 +1,615 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, + Transition, + SilentTransition, + OperatorPOWL, + StrictPartialOrder, + FrequentTransition, +) +from pm4py.objects.process_tree.obj import Operator +from enum import Enum +from typing import Optional, Dict, Any, Set, Tuple + +############################################################################### +# Enums and constants +############################################################################### + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + TRACE = "trace" + +START_ACTIVITIES = Outputs.START_ACTIVITIES.value +END_ACTIVITIES = Outputs.END_ACTIVITIES.value +ACTIVITIES = Outputs.ACTIVITIES.value +SKIPPABLE = Outputs.SKIPPABLE.value +SEQUENCE = Outputs.SEQUENCE.value +PARALLEL = Outputs.PARALLEL.value +ACTIVITIES_ALWAYS_HAPPENING = Outputs.ACTIVITIES_ALWAYS_HAPPENING.value + + +############################################################################### +# Utility functions to fix parallel vs sequence footprints +############################################################################### + +def fix_fp(sequence: Set[Tuple[str, str]], parallel: Set[Tuple[str, str]]): + """ + Fix footprints: + - Remove parallel relations from the sequence relations + - If A->B and B->A both appear in sequence, that is a conflict. Turn them into parallel. + """ + # Remove from sequence any pair that also appears in parallel + sequence = sequence.difference(parallel) + + # If a pair (x,y) is in sequence and (y,x) is in sequence, they are actually parallel + conflicting = {(x[0], x[1]) for x in sequence if (x[1], x[0]) in sequence} + for el in conflicting: + parallel.add(el) + sequence.remove(el) + + return sequence, parallel + + +############################################################################### +# Combine footprints +############################################################################### + +def merge_footprints(list_of_footprints): + """ + Utility function to merge a list of footprints dictionaries in a 'parallel/AND' sense. + + Returns a dictionary that merges all sets and booleans according to the appropriate logic. + - 'activities' => union + - 'skippable' => AND + - 'start_activities' => union (will be refined later in partial order) + - 'end_activities' => union (refined later) + - 'activities_always_happening' => union for non-skippable children + - 'sequence', 'parallel' => union, then fix_fp at the end + """ + if not list_of_footprints: + return { + START_ACTIVITIES: set(), + END_ACTIVITIES: set(), + ACTIVITIES: set(), + SKIPPABLE: True, + SEQUENCE: set(), + PARALLEL: set(), + ACTIVITIES_ALWAYS_HAPPENING: set(), + } + + merged = { + START_ACTIVITIES: set(list_of_footprints[0][START_ACTIVITIES]), + END_ACTIVITIES: set(list_of_footprints[0][END_ACTIVITIES]), + ACTIVITIES: set(list_of_footprints[0][ACTIVITIES]), + SKIPPABLE: list_of_footprints[0][SKIPPABLE], + SEQUENCE: set(list_of_footprints[0][SEQUENCE]), + PARALLEL: set(list_of_footprints[0][PARALLEL]), + ACTIVITIES_ALWAYS_HAPPENING: set(list_of_footprints[0][ACTIVITIES_ALWAYS_HAPPENING]), + } + + for fp in list_of_footprints[1:]: + merged[ACTIVITIES] = merged[ACTIVITIES].union(fp[ACTIVITIES]) + merged[SKIPPABLE] = merged[SKIPPABLE] and fp[SKIPPABLE] + merged[SEQUENCE] = merged[SEQUENCE].union(fp[SEQUENCE]) + merged[PARALLEL] = merged[PARALLEL].union(fp[PARALLEL]) + if not fp[SKIPPABLE]: + merged[ACTIVITIES_ALWAYS_HAPPENING] = merged[ACTIVITIES_ALWAYS_HAPPENING].union( + fp[ACTIVITIES_ALWAYS_HAPPENING] + ) + + return merged + + +############################################################################### +# Combining minimum trace length from child footprints +############################################################################### + +def combine_min_trace_length_par(children_fps): + """ + For partial order or parallel/AND: we must execute each non-skippable submodel at least once. + So the min trace length = sum of the min lengths of non-skippable children. + """ + total = 0 + for fp in children_fps: + if not fp[SKIPPABLE]: + total += fp.get(Outputs.MIN_TRACE_LENGTH.value, 0) + return total + + +def combine_min_trace_length_xor(children_fps): + """ + For XOR/choice: min trace length = min among children. + """ + if not children_fps: + return 0 + return min(fp.get(Outputs.MIN_TRACE_LENGTH.value, 0) for fp in children_fps) + + +def combine_min_trace_length_loop(do_fp, redo_fp): + """ + For LOOP (do, redo): must do 'do' at least once, so min length = min_length(do). + """ + return do_fp.get(Outputs.MIN_TRACE_LENGTH.value, 0) + + +############################################################################### +# Handling transitions +############################################################################### + +def get_footprints_of_transition(node: Transition) -> Dict[str, Any]: + """ + Footprints for a simple Transition (labeled or silent). + """ + if node.label is None: + # Silent transition => effectively "skip" + return { + START_ACTIVITIES: set(), + END_ACTIVITIES: set(), + ACTIVITIES: set(), + SKIPPABLE: True, + SEQUENCE: set(), + PARALLEL: set(), + ACTIVITIES_ALWAYS_HAPPENING: set(), + Outputs.MIN_TRACE_LENGTH.value: 0, + } + else: + # Labeled transition => a leaf with one activity + return { + START_ACTIVITIES: {node.label}, + END_ACTIVITIES: {node.label}, + ACTIVITIES: {node.label}, + SKIPPABLE: False, + SEQUENCE: set(), + PARALLEL: set(), + ACTIVITIES_ALWAYS_HAPPENING: {node.label}, + Outputs.MIN_TRACE_LENGTH.value: 1, + } + + +############################################################################### +# Handling XOR +############################################################################### + +def get_footprints_of_xor(node: OperatorPOWL, footprints_cache: Dict[POWL, Dict[str, Any]]) -> Dict[str, Any]: + """ + Footprints for an XOR/choice node: + - start_activities = union(children.start_activities) + - end_activities = union(children.end_activities) + - activities = union + - skippable = OR of children.skippable + - activities_always_happening = intersection of all non-skippable children's AAH + - sequence = union of children + - parallel = union of children + - min_trace_length = min of children + """ + child_fps = [get_footprints_powl(ch, footprints_cache) for ch in node.children] + + start_activities = set() + end_activities = set() + activities = set() + skippable = False + sequence = set() + parallel = set() + + # Intersection of always-happening among non-skippable children + aah = None + + for fp in child_fps: + start_activities |= fp[START_ACTIVITIES] + end_activities |= fp[END_ACTIVITIES] + activities |= fp[ACTIVITIES] + skippable = skippable or fp[SKIPPABLE] + sequence |= fp[SEQUENCE] + parallel |= fp[PARALLEL] + if not fp[SKIPPABLE]: + if aah is None: + aah = set(fp[ACTIVITIES_ALWAYS_HAPPENING]) + else: + aah &= fp[ACTIVITIES_ALWAYS_HAPPENING] + + if aah is None: + aah = set() + + sequence, parallel = fix_fp(sequence, parallel) + + min_trace_length = combine_min_trace_length_xor(child_fps) + + return { + START_ACTIVITIES: start_activities, + END_ACTIVITIES: end_activities, + ACTIVITIES: activities, + SKIPPABLE: skippable, + SEQUENCE: sequence, + PARALLEL: parallel, + ACTIVITIES_ALWAYS_HAPPENING: aah, + Outputs.MIN_TRACE_LENGTH.value: min_trace_length, + } + + +############################################################################### +# Handling LOOP +############################################################################### + +def get_footprints_of_loop(node: OperatorPOWL, footprints_cache: Dict[POWL, Dict[str, Any]]) -> Dict[str, Any]: + """ + Footprints for a LOOP node: children=[do, redo]. + Similar logic as process-tree loop footprints. + """ + do_child = node.children[0] + redo_child = node.children[1] + + do_fp = get_footprints_powl(do_child, footprints_cache) + redo_fp = get_footprints_powl(redo_child, footprints_cache) + + start_activities = set(do_fp[START_ACTIVITIES]) + end_activities = set(do_fp[END_ACTIVITIES]) + activities = do_fp[ACTIVITIES] | redo_fp[ACTIVITIES] + sequence = set(do_fp[SEQUENCE]) | set(redo_fp[SEQUENCE]) + parallel = set(do_fp[PARALLEL]) | set(redo_fp[PARALLEL]) + + # skippable if 'do' is skippable + skippable = do_fp[SKIPPABLE] + + # always happening if 'do' is not skippable + aah = set() + if not do_fp[SKIPPABLE]: + aah = set(do_fp[ACTIVITIES_ALWAYS_HAPPENING]) + + # if do is skippable => can also start/end in redo + if do_fp[SKIPPABLE]: + start_activities |= redo_fp[START_ACTIVITIES] + end_activities |= redo_fp[END_ACTIVITIES] + + # Add edges do.end -> redo.start, redo.end -> do.start, etc. + for a1 in do_fp[END_ACTIVITIES]: + for a2 in redo_fp[START_ACTIVITIES]: + sequence.add((a1, a2)) + for a1 in redo_fp[END_ACTIVITIES]: + for a2 in do_fp[START_ACTIVITIES]: + sequence.add((a1, a2)) + + # If do is skippable => redo can loop with itself + if do_fp[SKIPPABLE]: + for a1 in redo_fp[END_ACTIVITIES]: + for a2 in redo_fp[START_ACTIVITIES]: + sequence.add((a1, a2)) + # If redo is skippable => do can loop with itself + if redo_fp[SKIPPABLE]: + for a1 in do_fp[END_ACTIVITIES]: + for a2 in do_fp[START_ACTIVITIES]: + sequence.add((a1, a2)) + + sequence, parallel = fix_fp(sequence, parallel) + + min_trace_length = combine_min_trace_length_loop(do_fp, redo_fp) + + return { + START_ACTIVITIES: start_activities, + END_ACTIVITIES: end_activities, + ACTIVITIES: activities, + SKIPPABLE: skippable, + SEQUENCE: sequence, + PARALLEL: parallel, + ACTIVITIES_ALWAYS_HAPPENING: aah, + Outputs.MIN_TRACE_LENGTH.value: min_trace_length, + } + + +############################################################################### +# Handling StrictPartialOrder + transitive reduction +############################################################################### + +def transitive_reduction(node: StrictPartialOrder): + """ + Applies transitive reduction on the partial order contained in `node`. + If node.partial_order has edges A->B and B->C and A->C, we remove A->C. + In general, if there's an alternative path from A to C, we remove the direct edge A->C. + """ + from collections import defaultdict, deque + + children = node.children + adjacency = {c: [] for c in children} + edges = [] + + # Build adjacency + list of edges + for c in children: + for d in children: + if node.partial_order.is_edge(c, d): + adjacency[c].append(d) + edges.append((c, d)) + + edges_to_remove = [] + for (source, target) in edges: + # Check if there's another path from source to target ignoring the direct edge + visited = set() + queue = deque([source]) + found_target = False + while queue: + current = queue.popleft() + if current == target and current != source: + # We reached target from source ignoring direct edge => it's transitive + found_target = True + break + # Traverse neighbors + for nxt in adjacency[current]: + # skip the direct edge source->target + if current == source and nxt == target: + continue + if nxt not in visited: + visited.add(nxt) + queue.append(nxt) + + if found_target: + # The direct edge source->target is implied by a longer path + edges_to_remove.append((source, target)) + + # Remove them from the partial_order + for (source, target) in edges_to_remove: + node.partial_order.remove_edge(source, target) + + +def get_footprints_of_partial_order( + node: StrictPartialOrder, footprints_cache: Dict[POWL, Dict[str, Any]] +) -> Dict[str, Any]: + """ + Footprints for a StrictPartialOrder node: + 1) Build original adjacency (before transitive reduction). + 2) Compute transitive closure for concurrency + skip logic + start/end detection. + 3) Apply transitive reduction to keep the partial order minimal. + 4) Compute footprints for each child, merge them (AND/parallel). + 5) Refine start_activities: child c is 'start' if no non-skippable p != c has c in closure[p]. + 6) Refine end_activities: child c is 'end' if no non-skippable q != c is in closure[c]. + 7) Build sequence links: + - direct edges from partial_order + - skip edges if all intermediates are skippable + 8) Concurrency detection with the closure. + 9) fix_fp(...) and set min_trace_length. + """ + from collections import defaultdict, deque + + # -------------------------------------------------------------------------- + # 1) Original adjacency + # -------------------------------------------------------------------------- + children = node.children + original_adjacency = {c: [] for c in children} + for c in children: + for d in children: + if node.partial_order.is_edge(c, d): + original_adjacency[c].append(d) + + # -------------------------------------------------------------------------- + # 2) Compute transitive closure from original adjacency + # -------------------------------------------------------------------------- + # closure[c] = set of nodes reachable from c (including c itself). + closure = {c: set() for c in children} + for c in children: + visited = set([c]) + queue = deque([c]) + while queue: + cur = queue.popleft() + for nxt in original_adjacency[cur]: + if nxt not in visited: + visited.add(nxt) + queue.append(nxt) + closure[c] = visited + + # -------------------------------------------------------------------------- + # 3) Transitive reduction => partial order is minimal + # -------------------------------------------------------------------------- + transitive_reduction(node) + + # -------------------------------------------------------------------------- + # 4) Footprints of each child, merge them + # -------------------------------------------------------------------------- + child_fps = [get_footprints_powl(c, footprints_cache) for c in children] + merged_fp = merge_footprints(child_fps) + sequence = set(merged_fp[SEQUENCE]) + parallel = set(merged_fp[PARALLEL]) + start_activities = set() + end_activities = set() + + child_index = {c: i for i, c in enumerate(children)} + + # -------------------------------------------------------------------------- + # 5) Refine START + # c is a start node if there is NO non-skippable p != c with c in closure[p]. + # i.e. c can't be preceded by a mandatory node that must happen first. + # -------------------------------------------------------------------------- + for i, c in enumerate(children): + fp_c = child_fps[i] + is_start = True + for p in children: + if p != c: + fp_p = child_fps[child_index[p]] + if not fp_p[SKIPPABLE]: + # p is mandatory + if c in closure[p]: + # means p->...->c + is_start = False + break + if is_start: + start_activities |= fp_c[START_ACTIVITIES] + + # -------------------------------------------------------------------------- + # 6) Refine END + # c is an end node if there is NO non-skippable q != c with q in closure[c]. + # i.e. c can't be followed by a mandatory node in any path. + # -------------------------------------------------------------------------- + for i, c in enumerate(children): + fp_c = child_fps[i] + is_end = True + for q in children: + if q != c: + fp_q = child_fps[child_index[q]] + if not fp_q[SKIPPABLE]: + # q is mandatory + if q in closure[c]: + # means c->...->q + is_end = False + break + if is_end: + end_activities |= fp_c[END_ACTIVITIES] + + # -------------------------------------------------------------------------- + # 7) Build sequence edges + # (a) direct edges from partial_order after reduction + # (b) skip edges if all intermediates are skippable + # -------------------------------------------------------------------------- + reduced_adjacency = defaultdict(list) + for c in children: + for d in children: + if node.partial_order.is_edge(c, d): + reduced_adjacency[c].append(d) + # direct link in footprints + fp_c = child_fps[child_index[c]] + fp_d = child_fps[child_index[d]] + for a1 in fp_c[END_ACTIVITIES]: + for a2 in fp_d[START_ACTIVITIES]: + sequence.add((a1, a2)) + + def all_paths_through_only_skippable(c, d): + """ + Return True if c can reach d (c!=d) via closure, AND + for every path c->...->d, all intermediate nodes are skippable. + Equivalently: + There's no non-skippable n != c,d with c->...->n->...->d. + If there is any mandatory n in that path, we cannot skip it. + """ + if d not in closure[c] or c == d: + return False + + for n in children: + if n != c and n != d: + fp_n = child_fps[child_index[n]] + if not fp_n[SKIPPABLE]: + # n is mandatory + # if c->n->...->d => can't skip n + if (n in closure[c]) and (d in closure[n]): + return False + return True + + # skip edges + for c in children: + fp_c = child_fps[child_index[c]] + for d in children: + if c != d: + if all_paths_through_only_skippable(c, d): + fp_d = child_fps[child_index[d]] + for a1 in fp_c[END_ACTIVITIES]: + for a2 in fp_d[START_ACTIVITIES]: + sequence.add((a1, a2)) + + # -------------------------------------------------------------------------- + # 8) Concurrency detection + # c,d concurrent if c->...->d not in closure and d->...->c not in closure + # -------------------------------------------------------------------------- + for i in range(len(children)): + for j in range(i + 1, len(children)): + c = children[i] + d = children[j] + if (d not in closure[c]) and (c not in closure[d]): + # concurrency + fp_c = child_fps[i] + fp_d = child_fps[j] + for a1 in fp_c[ACTIVITIES]: + for a2 in fp_d[ACTIVITIES]: + parallel.add((a1, a2)) + parallel.add((a2, a1)) + + # -------------------------------------------------------------------------- + # 9) fix_fp(...) and finalize + # -------------------------------------------------------------------------- + sequence, parallel = fix_fp(sequence, parallel) + + merged_fp[START_ACTIVITIES] = start_activities + merged_fp[END_ACTIVITIES] = end_activities + merged_fp[SEQUENCE] = sequence + merged_fp[PARALLEL] = parallel + # min_trace_length = sum of non-skippable children + merged_fp[Outputs.MIN_TRACE_LENGTH.value] = combine_min_trace_length_par(child_fps) + + return merged_fp + + +############################################################################### +# Recursive footprints function with memoization +############################################################################### + +def get_footprints_powl(node: POWL, footprints_cache: Dict[POWL, Dict[str, Any]]) -> Dict[str, Any]: + """ + Computes the footprints of a POWL node, caching results in footprints_cache to avoid recomputation. + """ + if node in footprints_cache: + return footprints_cache[node] + + if isinstance(node, Transition): + fp = get_footprints_of_transition(node) + + elif isinstance(node, OperatorPOWL): + if node.operator == Operator.XOR: + fp = get_footprints_of_xor(node, footprints_cache) + elif node.operator == Operator.LOOP: + fp = get_footprints_of_loop(node, footprints_cache) + else: + raise NotImplementedError(f"Unsupported Operator: {node.operator}") + + elif isinstance(node, StrictPartialOrder): + fp = get_footprints_of_partial_order(node, footprints_cache) + + else: + raise NotImplementedError(f"Unknown POWL node type: {type(node)}") + + footprints_cache[node] = fp + return fp + + +############################################################################### +# Main entry point +############################################################################### + +def apply(model: POWL, parameters: Optional[Dict[Any, Any]] = None) -> Dict[str, Any]: + """ + Main entry point to compute footprints of a POWL model. + Applies transitive reduction on any partial order, then computes standard footprints. + + The returned dictionary includes: + "start_activities", + "end_activities", + "activities", + "skippable", + "sequence", + "parallel", + "activities_always_happening", + "min_trace_length" + """ + footprints_cache = {} + footprints = get_footprints_powl(model, footprints_cache) + return footprints diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6eeea675e414c8e8da8a09e3355dbd5e2bf1cc90 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/__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.discovery.footprints.tree import variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a81062a6ceb85243f1aff249ea5d41f1efb000ad --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/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.algo.discovery.footprints.tree.variants import bottomup diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/variants/bottomup.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/variants/bottomup.py new file mode 100644 index 0000000000000000000000000000000000000000..b8d45e6a15be2af736b648d47088c563db917f58 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/footprints/tree/variants/bottomup.py @@ -0,0 +1,491 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 Operator +from pm4py.objects.process_tree.utils import bottomup as bottomup_disc +from copy import copy + +from enum import Enum +from typing import Optional, Dict, Any +from pm4py.objects.process_tree.obj import ProcessTree + + +class Outputs(Enum): + DFG = "dfg" + SEQUENCE = "sequence" + PARALLEL = "parallel" + START_ACTIVITIES = "start_activities" + END_ACTIVITIES = "end_activities" + ACTIVITIES = "activities" + SKIPPABLE = "skippable" + ACTIVITIES_ALWAYS_HAPPENING = "activities_always_happening" + MIN_TRACE_LENGTH = "min_trace_length" + MAX_TRACE_LENGTH = "max_trace_length_wo_loops" + TRACE = "trace" + + +START_ACTIVITIES = Outputs.START_ACTIVITIES.value +END_ACTIVITIES = Outputs.END_ACTIVITIES.value +ACTIVITIES = Outputs.ACTIVITIES.value +SKIPPABLE = Outputs.SKIPPABLE.value +SEQUENCE = Outputs.SEQUENCE.value +PARALLEL = Outputs.PARALLEL.value +ACTIVITIES_ALWAYS_HAPPENING = Outputs.ACTIVITIES_ALWAYS_HAPPENING.value + + +def fix_fp(sequence, parallel): + """ + Fix footprints + + Parameters + -------------- + sequence + Sequence + parallel + Parallel + + Returns + ------------- + sequence + Sequence + parallel + Parallel + """ + sequence = sequence.difference(parallel) + + par_els = {(x[0], x[1]) for x in sequence if (x[1], x[0]) in sequence} + for el in par_els: + parallel.add(el) + sequence.remove(el) + + return sequence, parallel + + +def get_footprints_leaf(node, footprints_dictio): + """ + Gets the footprints for a leaf node + + Parameters + --------------- + node + Node + footprints_dictio + Dictionary of footprints of the process tree + + Returns + --------------- + footprints + Footprints of the leaf node + """ + if node.label is None: + return { + START_ACTIVITIES: set(), + END_ACTIVITIES: set(), + ACTIVITIES: set(), + SKIPPABLE: True, + SEQUENCE: set(), + PARALLEL: set(), + ACTIVITIES_ALWAYS_HAPPENING: set(), + } + else: + return { + START_ACTIVITIES: set([node.label]), + END_ACTIVITIES: set([node.label]), + ACTIVITIES: set([node.label]), + SKIPPABLE: False, + SEQUENCE: set(), + PARALLEL: set(), + ACTIVITIES_ALWAYS_HAPPENING: set([node.label]), + } + + +def get_footprints_xor(node, footprints_dictio): + """ + Gets the footprints for the XOR node + + Parameters + --------------- + node + Node + footprints_dictio + Dictionary of footprints of the process tree + + Returns + --------------- + footprints + Footprints of the XOR node + """ + start_activities = set() + end_activities = set() + activities = set() + skippable = False + sequence = set() + parallel = set() + activities_always_happening = set() + + if node.children: + activities_always_happening = copy( + footprints_dictio[node.children[0]][ACTIVITIES_ALWAYS_HAPPENING] + ) + + for n0 in node.children: + n = footprints_dictio[n0] + start_activities = start_activities.union(n[START_ACTIVITIES]) + end_activities = end_activities.union(n[END_ACTIVITIES]) + activities = activities.union(n[ACTIVITIES]) + skippable = skippable or n[SKIPPABLE] + sequence = sequence.union(n[SEQUENCE]) + parallel = parallel.union(n[PARALLEL]) + if not n[SKIPPABLE]: + activities_always_happening = ( + activities_always_happening.intersection( + n[ACTIVITIES_ALWAYS_HAPPENING] + ) + ) + else: + activities_always_happening = set() + + sequence, parallel = fix_fp(sequence, parallel) + + return { + START_ACTIVITIES: start_activities, + END_ACTIVITIES: end_activities, + ACTIVITIES: activities, + SKIPPABLE: skippable, + SEQUENCE: sequence, + PARALLEL: parallel, + ACTIVITIES_ALWAYS_HAPPENING: activities_always_happening, + } + + +def get_footprints_parallel(node, footprints_dictio): + """ + Gets the footprints for the parallel node + + Parameters + --------------- + node + Node + footprints_dictio + Dictionary of footprints of the process tree + + Returns + --------------- + footprints + Footprints of the parallel node + """ + start_activities = set() + end_activities = set() + activities = set() + skippable = True + sequence = set() + parallel = set() + activities_always_happening = set() + + for n0 in node.children: + n = footprints_dictio[n0] + start_activities = start_activities.union(n[START_ACTIVITIES]) + end_activities = end_activities.union(n[END_ACTIVITIES]) + activities = activities.union(n[ACTIVITIES]) + skippable = skippable and n[SKIPPABLE] + sequence = sequence.union(n[SEQUENCE]) + parallel = parallel.union(n[PARALLEL]) + if not n[SKIPPABLE]: + activities_always_happening = activities_always_happening.union( + n[ACTIVITIES_ALWAYS_HAPPENING] + ) + + i = 0 + while i < len(node.children): + acti_i = list(footprints_dictio[node.children[i]][ACTIVITIES]) + j = i + 1 + while j < len(node.children): + acti_j = list(footprints_dictio[node.children[j]][ACTIVITIES]) + for a1 in acti_i: + for a2 in acti_j: + parallel.add((a1, a2)) + parallel.add((a2, a1)) + j = j + 1 + i = i + 1 + + sequence, parallel = fix_fp(sequence, parallel) + + return { + START_ACTIVITIES: start_activities, + END_ACTIVITIES: end_activities, + ACTIVITIES: activities, + SKIPPABLE: skippable, + SEQUENCE: sequence, + PARALLEL: parallel, + ACTIVITIES_ALWAYS_HAPPENING: activities_always_happening, + } + + +def get_footprints_sequence(node, footprints_dictio): + """ + Gets the footprints for the sequence + + Parameters + --------------- + node + Node + footprints_dictio + Dictionary of footprints of the process tree + + Returns + --------------- + footprints + Footprints of the sequence node + """ + start_activities = set() + end_activities = set() + activities = set() + skippable = True + sequence = set() + parallel = set() + activities_always_happening = set() + + for n0 in node.children: + n = footprints_dictio[n0] + skippable = skippable and n[SKIPPABLE] + sequence = sequence.union(n[SEQUENCE]) + parallel = parallel.union(n[PARALLEL]) + activities = activities.union(n[ACTIVITIES]) + if not n[SKIPPABLE]: + activities_always_happening = activities_always_happening.union( + n[ACTIVITIES_ALWAYS_HAPPENING] + ) + + # adds the footprints + i = 0 + while i < len(node.children) - 1: + n0 = footprints_dictio[node.children[i]] + j = i + 1 + while j < len(node.children): + n1 = footprints_dictio[node.children[j]] + n0_end_act = n0[END_ACTIVITIES] + n1_start_act = n1[START_ACTIVITIES] + for a1 in n0_end_act: + for a2 in n1_start_act: + sequence.add((a1, a2)) + if not n1[SKIPPABLE]: + break + j = j + 1 + i = i + 1 + + # adds the start activities + i = 0 + while i < len(node.children): + n = footprints_dictio[node.children[i]] + start_activities = start_activities.union(n[START_ACTIVITIES]) + if not n[SKIPPABLE]: + break + i = i + 1 + + # adds the end activities + i = len(node.children) - 1 + while i >= 0: + n = footprints_dictio[node.children[i]] + end_activities = end_activities.union(n[END_ACTIVITIES]) + if not n[SKIPPABLE]: + break + i = i - 1 + + sequence, parallel = fix_fp(sequence, parallel) + + return { + START_ACTIVITIES: start_activities, + END_ACTIVITIES: end_activities, + ACTIVITIES: activities, + SKIPPABLE: skippable, + SEQUENCE: sequence, + PARALLEL: parallel, + ACTIVITIES_ALWAYS_HAPPENING: activities_always_happening, + } + + +def get_footprints_loop(node, footprints_dictio): + """ + Gets the footprints for the loop + + Parameters + --------------- + node + Node + footprints_dictio + Dictionary of footprints of the process tree + + Returns + --------------- + footprints + Footprints of the loop node + """ + start_activities = set() + end_activities = set() + activities = set() + sequence = set() + parallel = set() + activities_always_happening = set() + + for n0 in node.children: + n = footprints_dictio[n0] + sequence = sequence.union(n[SEQUENCE]) + parallel = parallel.union(n[PARALLEL]) + activities = activities.union(n[ACTIVITIES]) + + do = footprints_dictio[node.children[0]] + redo = footprints_dictio[node.children[1]] + + skippable = do[SKIPPABLE] + + if not do[SKIPPABLE]: + activities_always_happening = copy(do[ACTIVITIES_ALWAYS_HAPPENING]) + + start_activities = start_activities.union(do[START_ACTIVITIES]) + if do[SKIPPABLE]: + start_activities = start_activities.union(redo[START_ACTIVITIES]) + + end_activities = end_activities.union(do[END_ACTIVITIES]) + if do[SKIPPABLE]: + end_activities = end_activities.union(redo[END_ACTIVITIES]) + + for a1 in do[END_ACTIVITIES]: + for a2 in redo[START_ACTIVITIES]: + sequence.add((a1, a2)) + + for a1 in redo[END_ACTIVITIES]: + for a2 in do[START_ACTIVITIES]: + sequence.add((a1, a2)) + + if do[SKIPPABLE]: + for a1 in redo[END_ACTIVITIES]: + for a2 in redo[START_ACTIVITIES]: + sequence.add((a1, a2)) + + if redo[SKIPPABLE]: + for a1 in do[END_ACTIVITIES]: + for a2 in do[START_ACTIVITIES]: + sequence.add((a1, a2)) + + sequence, parallel = fix_fp(sequence, parallel) + + return { + START_ACTIVITIES: start_activities, + END_ACTIVITIES: end_activities, + ACTIVITIES: activities, + SKIPPABLE: skippable, + SEQUENCE: sequence, + PARALLEL: parallel, + ACTIVITIES_ALWAYS_HAPPENING: activities_always_happening, + } + + +def get_footprints(node, footprints_dictio): + """ + Gets the footprints for a node (having the history of the child nodes) + + Parameters + -------------- + node + Node of the tree + footprints_dictio + Dictionary of footprints of the process tree + + Returns + -------------- + footprints + Footprints of the node (having the history of the child nodes) + """ + if len(node.children) == 0: + return get_footprints_leaf(node, footprints_dictio) + elif node.operator == Operator.XOR: + return get_footprints_xor(node, footprints_dictio) + elif node.operator == Operator.PARALLEL or node.operator == Operator.OR: + return get_footprints_parallel(node, footprints_dictio) + elif node.operator == Operator.SEQUENCE: + return get_footprints_sequence(node, footprints_dictio) + elif node.operator == Operator.LOOP: + return get_footprints_loop(node, footprints_dictio) + + +def get_all_footprints(tree, parameters=None): + """ + Gets all the footprints for the nodes of the tree + + Parameters + ----------------- + tree + Process tree + parameters + Parameters of the algorithm + + Returns + ---------------- + dictio + Dictionary that associates a footprint to each node of the tree + """ + if parameters is None: + parameters = {} + + # for each node of the bottom up, proceed to getting the footprints + bottomup = bottomup_disc.get_bottomup_nodes(tree, parameters=parameters) + footprints_dictio = {} + for i in range(len(bottomup)): + footprints_dictio[bottomup[i]] = get_footprints( + bottomup[i], footprints_dictio + ) + + return footprints_dictio + + +def apply( + tree: ProcessTree, parameters: Optional[Dict[Any, Any]] = None +) -> Dict[str, Any]: + """ + Footprints detection on process tree + + Parameters + ----------------- + tree + Process tree + parameters + Parameters of the algorithm + + Returns + ----------------- + footprints + Footprints + """ + if parameters is None: + parameters = {} + + all_footprints = get_all_footprints(tree, parameters=parameters) + root_node_footprints = all_footprints[tree] + + this_parameters = copy(parameters) + this_parameters["avoid_loops"] = True + min_trace_length = bottomup_disc.get_min_trace_length(tree, parameters=this_parameters) + max_trace_length = bottomup_disc.get_max_trace_length(tree, parameters=this_parameters) + + root_node_footprints[Outputs.MIN_TRACE_LENGTH.value] = min_trace_length + root_node_footprints[Outputs.MAX_TRACE_LENGTH.value] = max_trace_length + + return root_node_footprints diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b20698328565d6080e759feeef3dc149a4764a3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/__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.discovery.genetic import variants, algorithm diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..9173cc60c9aa179c1a8ccdf3f4798ce0c88b5205 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/algorithm.py @@ -0,0 +1,75 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.algo.discovery.genetic.variants import classic +from pm4py.objects.petri_net.obj import PetriNet, Marking +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd +from pm4py.util import constants +from typing import Union, Optional, Dict, Any, Tuple + + +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 + POPULATION_SIZE = "population_size" + ELITISM_RATE = "elitism_rate" + CROSSOVER_RATE = "crossover_rate" + MUTATION_RATE = "mutation_rate" + GENERATIONS = "generations" + ELITISM_MIN_SAMPLE = "elitism_min_sample" + LOG_CSV = "log_csv" + +class Variants(Enum): + CLASSIC = classic + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using the genetic miner. + + Parameters + --------------- + log + Event log / Event stream / Pandas dataframe + variant + Variant of the algorithm to be used, possible values: + - Variants.CLASSIC + parameters + Variant-specific parameters + + Returns + --------------- + net + Petri net + im + Initial marking + fm + Final marking + """ + return exec_utils.get_variant(variant).apply(log, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/util.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/util.py new file mode 100644 index 0000000000000000000000000000000000000000..7743420fc0b62162b357152d3a621ac009844929 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/util.py @@ -0,0 +1,102 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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) + +import random +import itertools + +# typing +from typing import Dict, FrozenSet, Iterable, List, Set, Tuple, Union +TransitionMap = Dict[str, List[FrozenSet[str]]] +InputMap = OutputMap = TransitionMap +Individual = Tuple[InputMap, OutputMap] + +class iset(frozenset): + "Indexable frozenset printing as set, i.e. without `frozenset(…)`" + def __repr__(self): + return "{" + repr(sorted(self))[1:-1] + "}" + + @staticmethod + def flat(item: Iterable) -> "iset": + return iset(itertools.chain(*item)) + +def rand_partition(pool: Iterable) -> List[Union[Set[str], FrozenSet[str]]]: + pool = set(pool) + # also ensures no activity in two partitions + # s. 4. Causal Matrix, Def. 4; https://doi.org/10.1007/11494744_5 + partition = [] + while pool: + draw = iset(random.sample( + tuple(pool), + random.randint(1, len(pool)) + )) + partition.append(draw) + pool -= draw + return partition + +def add_singleton_partition(tmap: TransitionMap, key: str, t: str): + partitions = tmap.setdefault(key, []) # tmap[key] or [] + if not any(t in partition for partition in partitions): + partitions.append(iset({t})) + +def remove_transition_from_partitions(tmap: TransitionMap, key: str, t: str): + partitions = tmap.setdefault(key, []) # tmap[key] or [] + for i,partition in enumerate(partitions): + if t in partition: + updated = iset(partition - {t}) + if updated: + partitions[i] = updated + else: + del partitions[i] + return + +def get_src_sink_sets_for_wfnet(I: InputMap, O: OutputMap, T: List[str]) -> Tuple[List[str], List[str]]: + """Determines input set and output set, which need to be connected by a place to create a WF-net""" + def add2graphs(graphs, t, nextT): + # find graph + graph = next((g for g in graphs if t in g), None) + if graph is None: + graph = [t] + graphs.append(graph) + # append plain/grouped T + successors = [] + for S in nextT[t]: + if type(S) == str: + successors.append(S) + else: + successors.extend(S) + graph += successors + # merge if path end = start + for tn in successors: # tn = end + for g2 in graphs[:]: # [:] = copy + if g2[0] == tn and g2 != graph: + graph += g2 + graphs.remove(g2) + break + return graphs + graphsI, graphsO = [], [] + for t in T: + graphsI = add2graphs(graphsI, t, I) + graphsO = add2graphs(graphsO, t, O) + sources = [g[0] for g in graphsO] # ⋃sources = ∀t reachable from O[∀sources] + sinks = [g[0] for g in graphsI] # ⋃sinks = ∀t reachable from I[∀sinks] + return sources, sinks diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0391f2a776b29aa78e3c4386c8626ffac11688ea --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/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.algo.discovery.genetic.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..cba1204726c59b6f553597b2a32aad9f59047071 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/genetic/variants/classic.py @@ -0,0 +1,395 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 csv +from datetime import datetime +import numpy +import random +import itertools + +# optional dependencies +try: + from tqdm import tqdm +except ImportError: + def tqdm(iterable=None, *args, **kwargs): + return iterable if iterable is not None else [] + +import pm4py +from pm4py.util import exec_utils, constants +from pm4py.util import xes_constants as xes +from pm4py.utils import is_polars_lazyframe +from pm4py.algo.discovery.genetic.algorithm import Parameters +from pm4py.objects.conversion.log import converter as log_converter +from pm4py.objects.conversion.genetic_matrix.variants.to_petri_net import apply as matrix2petrinet +from pm4py.algo.discovery.genetic.util import add_singleton_partition, get_src_sink_sets_for_wfnet, iset, rand_partition, remove_transition_from_partitions +from pm4py.objects.genetic_matrix.obj import GeneticMatrix + +# typing +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union +from pandas.core.frame import DataFrame +from pm4py.objects.log.obj import EventLog, EventStream +from pm4py.objects.petri_net.obj import PetriNet, Marking +from pm4py.algo.discovery.genetic.util import TransitionMap, InputMap, OutputMap, Individual + + +def apply( + log: Union[EventLog, EventStream, DataFrame], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using Genetic Miner + + Reference paper: + Maximilian Josef Frank. "Optimising and Implementing the Genetic Miner in PM4Py" (2026). + + Parameters + ------------ + log + Event log + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.POPULATION_SIZE + - Parameters.ELITISM_RATE + - Parameters.CROSSOVER_RATE + - Parameters.MUTATION_RATE + - Parameters.GENERATIONS + - Parameters.ELITISM_MIN_SAMPLE + - Parameters.LOG_CSV + + Returns + ------------ + net + Petri net + im + Initial marking + fm + Final marking + """ + if parameters is None: + parameters = {} + if is_polars_lazyframe(log): + log = log.collect().to_pandas() + if not isinstance(log, DataFrame): + log = log_converter.apply( + log, + variant=log_converter.Variants.TO_DATA_FRAME, + parameters=parameters, + ) + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + + population_size = exec_utils.get_param_value( + Parameters.POPULATION_SIZE, parameters, 500 + ) + elitism_rate = exec_utils.get_param_value( + Parameters.ELITISM_RATE, parameters, 0.01 + ) + crossover_rate = exec_utils.get_param_value( + Parameters.CROSSOVER_RATE, parameters, 1.0 + ) + mutation_rate = exec_utils.get_param_value( + Parameters.MUTATION_RATE, parameters, 0.01 + ) + generations = exec_utils.get_param_value( + Parameters.GENERATIONS, parameters, 100 + ) + elitism_min_sample = exec_utils.get_param_value( + Parameters.ELITISM_MIN_SAMPLE, parameters, 5 + ) + log_csv = exec_utils.get_param_value( + Parameters.LOG_CSV, parameters, None + ) + + # configure parameters + if population_size < 2: + raise ValueError("population_size < 2: You need at least two parents for each next generation, thus at least a population size of 2.") + if elitism_min_sample >= population_size: + elitism_min_sample = population_size - 1 + if elitism_min_sample < 1: + raise ValueError("elitism_min_sample < 1: No empty samples allowed.") + if log_csv: + log_csv = csv.writer(log_csv) + log_csv.writerow(['timestamp', 'generation'] + [f'fitness{i}' for i in range(population_size)]) + # @src 6.3. Genetic Operations; https://doi.org/10.1007/11494744_5 + T = tuple(log[activity_key].unique()) + history = [] + # initial population + population = individuals(log, population_size, T, { # [(I,O), …] + "activity_key":activity_key, "timestamp_key":timestamp_key, "case_id_key":case_id_key + }) + population, fitness = tournament(tqdm(population, f"└─Tournament {len(history)}"), log, T, sort=True) + if log_csv: + log_csv.writerow([datetime.now(), len(history)] + fitness) + # generations (generation-1 because initial population already generated) + for _ in tqdm(range(generations-1), "Genetic generations"): + if fitness[0] == 1 or (history and all(f == fitness[0] for f in history[-int(generations/2):])): + break + history.append(fitness[0]) + # elitism + next_population = population[:round(elitism_rate * population_size)] + # fill with offsprings + while len(next_population) < population_size: + parent1, parent2 = sample_parents(population, fitness, elitism_min_sample) + if random.random() < crossover_rate: + offsprings = crossover(parent1, parent2, T) + else: + offsprings = copy.deepcopy((parent1, parent2)) + for offspring in offsprings: + if len(next_population) < population_size: + offspring = mutate(offspring, mutation_rate) + next_population.append(offspring) + # sorts population by fitness + population, fitness = tournament(tqdm(next_population, f"└─Tournament {len(history)}"), log, T, sort=True) + if log_csv: + log_csv.writerow([datetime.now(), len(history)] + fitness) + return matrix2petrinet(GeneticMatrix(*population[0], T)) + +def individuals(log: Union[DataFrame, EventLog], sample_size=1, T=None, keys: Dict[str, str] = {"activity_key":xes.DEFAULT_NAME_KEY, "timestamp_key":xes.DEFAULT_TIMESTAMP_KEY, "case_id_key":constants.CASE_CONCEPT_NAME}) -> List[Individual]: + if not T: + T = tuple(log[keys['activity_key']].unique()) + # polyfill for itertools.pairwise (requires Python 3.10+) + # @src https://docs.python.org/3/library/itertools.html#itertools.pairwise + def pairwise(iterable): + # pairwise('ABCDEFG') → AB BC CD DE EF FG + iterator = iter(iterable) + a = next(iterator, None) + for b in iterator: + yield a, b + a = b + # @src 6.1. Initial Population; https://doi.org/10.1007/11494744_5 + # create matrix C + C = numpy.zeros((len(T), len(T))) + for _,group in tqdm(log.sort_values(keys['timestamp_key'], ascending=True).groupby(keys['case_id_key']), desc="Find consecutive activities"): + for row1,row2 in pairwise(map(lambda r: r[1], group.iterrows())): + i = T.index(row1[keys['activity_key']]) + o = T.index(row2[keys['activity_key']]) + C[i,o] += 1 + Cn = numpy.nan_to_num(C / C.sum(axis=1)[:,None]) # normalise row-wise + samples = [] + for _ in tqdm(range(sample_size), "Initial population"): + I,O = defaultdict(list), defaultdict(list) + for i,o in numpy.ndindex(C.shape): + if random.random() < Cn[i,o]: # [0,1[ < [0,1]; 0 < 0 = false + O[T[i]].append(T[o]) + I[T[o]].append(T[i]) + I,O = repair(I, O, C, T) + # partitioning already ensures no T in >1 partitions + # see 4. Causal Matrix, Def. 4; https://doi.org/10.1007/11494744_5 + for i in I.keys(): + I[i] = rand_partition(I[i]) + for o in O.keys(): + O[o] = rand_partition(O[o]) + samples.append((I,O)) + return samples + +def tournament( + population: List[Individual], + log: Union[DataFrame, EventLog], + T, + sort=True, + activity_key: str = xes.DEFAULT_NAME_KEY, + timestamp_key: str = xes.DEFAULT_TIMESTAMP_KEY, + case_id_key: str = constants.CASE_CONCEPT_NAME, +) -> Tuple[List[Individual], List[float]]: + """sort=True: sort descending by fitness (i.e. best first)""" + # @src 6.2. Fitness Calculation; https://doi.org/10.1007/11494744_5 + fitness = [] + for i,(I,O) in enumerate(population): + model = matrix2petrinet(GeneticMatrix(I,O,T)) + metrics = pm4py.fitness_token_based_replay( + log, + *model, + activity_key=activity_key, + timestamp_key=timestamp_key, + case_id_key=case_id_key, + ) + fitness.append( + 0.4 * metrics['average_trace_fitness'] + # @see https://pm4py-source.readthedocs.io/en/stable/_modules/pm4py/algo/evaluation/replay_fitness/variants/token_replay.html#evaluate + # average_fitness = sum_fitness / #traces + # = ∑ fitness per trace / #traces + # ∑ fitness per trace * len(log)/#traces + # = –––––––––––––––––––––––––––––––––––––– + # #traces * len(log)/#traces + # ∑ fitness per row in log ∑ fitness per activity + # = –––––––––––––––––––––––– = –––––––––––––––––––––– + # len(log) len(log) + + + 0.6 * metrics['percentage_of_fitting_traces']/100 + ) + if sort: + population, fitness = zip(*sorted( + zip(population, fitness), + key=lambda obj: obj[1], + reverse=True + )) + population, fitness = list(population), list(fitness) + return (population, fitness) + +def sample_parents(population: List[Individual], fitness: List[float], elitism_min_sample: int): + population_fitness = tuple(zip(population, fitness)) + parent1 = sorted( + random.sample(population_fitness, k=elitism_min_sample), + key=lambda obj: obj[1], + reverse=True + )[0][0] + parent2 = sorted( + random.sample( + [(i,f) for i,f in population_fitness if i!=parent1], + k=elitism_min_sample + ), + key=lambda obj: obj[1], + reverse=True + )[0][0] + return (parent1, parent2) + +def crossover(parent1: Individual, parent2: Individual, T: List[str]) -> Tuple[Individual, Individual]: + # @src 6.3. Genetic Operations: Crossover; https://doi.org/10.1007/11494744_5 + # 1. cross-over point + t = random.choice(T) + # 2. clone parents + I1,O1 = offspring1 = copy.deepcopy(parent1) + I2,O2 = offspring2 = copy.deepcopy(parent2) + # 3. swap and recombine + if I1[t] and I2[t]: + swap_point = random.randrange(min(len(I1[t]), len(I2[t]))) + toI1, toI2 = I2[t][swap_point:], I1[t][swap_point:] + # no T can exist twice in I/O[t], see Def. 4; https://doi.org/10.1007/11494744_5 + # COPY of I_i, else not properly removed in opposite I_j + I1_flat = iset.flat(I1[t][:swap_point]) + toI1_dedup = [iset(S - I1_flat) for S in toI1 if S - I1_flat] # skips {} + I2_flat = iset.flat(I2[t][:swap_point]) + toI2_dedup = [iset(S - I2_flat) for S in toI2 if S - I2_flat] # skips {} + # merge + old_I1 = iset.flat(I1[t]) + old_I2 = iset.flat(I2[t]) + I1[t], I2[t] = I1[t][:swap_point] + toI1_dedup, I2[t][:swap_point] + toI2_dedup + # @src 6.3. Genetic Operations: Update Related Elements; https://doi.org/10.1007/11494744_5 + new_I1 = iset.flat(I1[t]) + new_I2 = iset.flat(I2[t]) + for c in new_I1 - old_I1: + add_singleton_partition(O1, c, t) + for c in old_I1 - new_I1: + remove_transition_from_partitions(O1, c, t) + for c in new_I2 - old_I2: + add_singleton_partition(O2, c, t) + for c in old_I2 - new_I2: + remove_transition_from_partitions(O2, c, t) + if O1[t] and O2[t]: + swap_point = random.randrange(min(len(O1[t]), len(O2[t]))) + toO1, toO2 = O2[t][swap_point:], O1[t][swap_point:] + # no T can exist twice in I/O[t], see Def. 4; https://doi.org/10.1007/11494744_5 + # COPY of I_i, else not properly removed in opposite I_j + O1_flat = iset.flat(O1[t][:swap_point]) + toO1_dedup = [iset(S - O1_flat) for S in toO1 if S - O1_flat] # skips {} + O2_flat = iset.flat(O2[t][:swap_point]) + toO2_dedup = [iset(S - O2_flat) for S in toO2 if S - O2_flat] # skips {} + # merge + old_O1 = iset.flat(O1[t]) + old_O2 = iset.flat(O2[t]) + O1[t], O2[t] = O1[t][:swap_point] + toO1_dedup, O2[t][:swap_point] + toO2_dedup + # @src 6.3. Genetic Operations: Update Related Elements; https://doi.org/10.1007/11494744_5 + for c in iset.flat(O1[t]) - old_O1: + add_singleton_partition(I1, c, t) + for c in old_O1 - iset.flat(O1[t]): + remove_transition_from_partitions(I1, c, t) + for c in iset.flat(O2[t]) - old_O2: + add_singleton_partition(I2, c, t) + for c in old_O2 - iset.flat(O2[t]): + remove_transition_from_partitions(I2, c, t) + return (offspring1, offspring2) # = (I1,O1),(I2,O2) by reference + +def mutate(individual: Individual, rate: float = 0.01) -> Individual: + # @src 6.3. Genetic Operations: Mutation; https://doi.org/10.1007/11494744_5 + I,O = individual + for t in I.keys(): + if random.random() < rate: + I[t] = rand_partition(itertools.chain(*I[t])) + for t in O.keys(): + if random.random() < rate: + O[t] = rand_partition(itertools.chain(*O[t])) + return (I,O) + +def repair(I: InputMap, O: OutputMap, C: numpy.ndarray, T: List[str]) -> Individual: + """ + Merging partitions until petri-net is (coherent) workflow net + see last requirement in 4. Causal Matrix, Def. 4; https://doi.org/10.1007/11494744_5 + """ + # WF-Net Definition: each node on path from i to o + # → re-connect partitions of each I and O, not I and O together + left = set(T) + partitions = [] + while left: + partition = set() + Tn = {left.pop()} + while Tn: + t = Tn.pop() # also removes from Tn + left.discard(t) # remove without Exception (see initial Tn) + partition.add(t) + Tn |= (set(I[t]) | set(O[t])) & left + partitions.append(partition) + T_idx = {t:i for i,t in enumerate(T)} # faster than T.index(t) + + def rand_connect_one(I: InputMap, O: OutputMap, Ti: Iterable[str], To: Iterable[str], C: numpy.ndarray) -> Individual: + comb = tuple(itertools.product(Ti, To)) + try: + ti,to = random.choices( + comb, + weights = [ C[T_idx[ti], T_idx[to]] for ti,to in comb ], + k=1 + )[0] + except ValueError: + ti,to = random.choice(comb) + O[ti].append(to) + I[to].append(ti) + return I,O + + while len(partitions) > 1: + random.shuffle(partitions) + # merge Ti / To of partition to other partition + sources, sinks = get_src_sink_sets_for_wfnet(I, O, partitions[1]) + for i in sources: + # connect any→i + I,O = rand_connect_one(I, O, partitions[0], [i], C) + for o in sinks: + # connect o→any + I,O = rand_connect_one(I, O, [o], partitions[0], C) + # pop first + merge with new first (i.e. old second) + merging = partitions.pop(0) + partitions[0] |= merging + return (I,O) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c42f9dbe513974a35477dcfaa9a79d9429e410 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/__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.discovery.heuristics import variants, algorithm diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..2e8b4221b4408f1702e78cab895b05cf079ad759 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/algorithm.py @@ -0,0 +1,268 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.algo.discovery.heuristics.variants import classic, plusplus +from pm4py.objects.conversion.log import converter as log_conversion +from pm4py.objects.heuristics_net.obj import HeuristicsNet +from pm4py.util import exec_utils, pandas_utils +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd +from pm4py.objects.petri_net.obj import PetriNet, Marking + + +class Variants(Enum): + CLASSIC = classic + PLUSPLUS = plusplus + + +CLASSIC = Variants.CLASSIC +DEFAULT_VARIANT = CLASSIC + +VERSIONS = {CLASSIC} + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + parameters: Optional[Dict[Any, Any]] = None, + variant=CLASSIC, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using Heuristics Miner. + + Parameters + ---------- + log + Event log + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH variant Variant of the algorithm: + - Variants.CLASSIC + - Variants.PLUSPLUS + + Returns + ------- + net + Petri net + im + Initial marking + fm + Final marking + + """ + if pandas_utils.check_is_pandas_dataframe(log): + return exec_utils.get_variant(variant).apply_pandas( + log, parameters=parameters + ) + + return exec_utils.get_variant(variant).apply( + log_conversion.apply( + log, + variant=log_conversion.Variants.TO_EVENT_LOG, + parameters=parameters, + ), + parameters=parameters, + ) + + +def apply_dfg( + dfg: Dict[Tuple[str, str], int], + activities=None, + activities_occurrences=None, + start_activities=None, + end_activities=None, + parameters=None, + variant=CLASSIC, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using Heuristics Miner. + + Parameters + ---------- + dfg + Directly-Follows Graph + activities + (If provided) list of activities of the log + activities_occurrences + (If provided) dictionary of activities occurrences + start_activities + (If provided) dictionary of start activities occurrences + end_activities + (If provided) dictionary of end activities occurrences + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH variant Variant of the algorithm: + - Variants.CLASSIC + + Returns + ----------------- + net + Petri net + im + Initial marking + fm + Final marking + + """ + return exec_utils.get_variant(variant).apply_dfg( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + parameters=parameters, + ) + + +def apply_heu( + log: Union[EventLog, EventStream, pd.DataFrame], + parameters: Optional[Dict[Any, Any]] = None, + variant=CLASSIC, +) -> HeuristicsNet: + """ + Discovers an Heuristics Net using Heuristics Miner. + + Parameters + ---------- + log + Event log + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + + variant + Variant of the algorithm: + + - Variants.CLASSIC + + Returns + ------------ + net + Petri net + im + Initial marking + fm + Final marking + + """ + return exec_utils.get_variant(variant).apply_heu( + log_conversion.apply( + log, + variant=log_conversion.Variants.TO_EVENT_LOG, + parameters=parameters, + ), + parameters=parameters, + ) + + +def apply_heu_dfg( + dfg: Dict[Tuple[str, str], int], + activities=None, + activities_occurrences=None, + start_activities=None, + end_activities=None, + parameters=None, + variant=CLASSIC, +) -> HeuristicsNet: + """ + Discovers an Heuristics Net using Heuristics Miner. + + Parameters + ---------- + dfg + Directly-Follows Graph + activities + (If provided) list of activities of the log + activities_occurrences + (If provided) dictionary of activities occurrences + start_activities + (If provided) dictionary of start activities occurrences + end_activities + (If provided) dictionary of end activities occurrences + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + + variant + Variant of the algorithm: + + - Variants.CLASSIC + + Returns + ------------ + net + Petri net + im + Initial marking + fm + Final marking + + """ + return exec_utils.get_variant(variant).apply_heu_dfg( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + parameters=parameters, + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6888246d5a790f167da6428e84309704be4b383c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/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.algo.discovery.heuristics.variants import classic, plusplus diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..a2778172886fc809dce3e887c7649787f3889696 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/classic.py @@ -0,0 +1,797 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 enum import Enum + +from pm4py.algo.discovery.dfg import algorithm as dfg_alg +from pm4py.algo.filtering.dfg.dfg_filtering import ( + clean_dfg_based_on_noise_thresh, +) +from pm4py.objects.conversion.heuristics_net import converter as hn_conv_alg +from pm4py.objects.heuristics_net import defaults +from pm4py.objects.heuristics_net.node import Node +from pm4py.statistics.attributes.log import get as log_attributes +from pm4py.statistics.end_activities.log import get as log_ea_filter +from pm4py.statistics.start_activities.log import get as log_sa_filter +from pm4py.util import constants +from pm4py.util import exec_utils +from pm4py.util import xes_constants as xes +from typing import Optional, Dict, Any, Union, Tuple +from pm4py.objects.log.obj import EventLog +from pm4py.objects.petri_net.obj import PetriNet, Marking +import pandas as pd +from pm4py.objects.heuristics_net.obj import HeuristicsNet + + +class Parameters(Enum): + 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 + 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" + HEU_NET_DECORATION = "heu_net_decoration" + + +def is_polars_lazyframe(df: Any) -> bool: + """Return True if the provided dataframe is a Polars LazyFrame.""" + df_type = str(type(df)).lower() + return "polars" in df_type and "lazyframe" in df_type + + +def apply( + log: EventLog, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using Heuristics Miner. + + Parameters + ---------- + log + Event log + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + + Returns + ------------ + net + Petri net + im + Initial marking + fm + Final marking + + """ + if parameters is None: + parameters = {} + + heu_net = apply_heu(log, parameters=parameters) + net, im, fm = hn_conv_alg.apply(heu_net, parameters=parameters) + + return net, im, fm + + +def apply_pandas( + df: pd.DataFrame, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using Heuristics Miner + + Parameters + ------------ + df + Pandas dataframe + parameters + Possible parameters of the algorithm, + including: activity_key, case_id_glue, timestamp_key, + dependency_thresh, and_measure_thresh, min_act_count, min_dfg_occurrences, dfg_pre_cleaning_noise_thresh, + loops_length_two_thresh + + Returns + ------------ + net + Petri net + im + Initial marking + fm + Final marking + """ + if parameters is None: + parameters = {} + + heu_net = apply_heu_pandas(df, parameters=parameters) + + return hn_conv_alg.apply(heu_net, parameters=parameters) + + +def apply_dfg( + dfg: Dict[Tuple[str, str], int], + activities=None, + activities_occurrences=None, + start_activities=None, + end_activities=None, + parameters: Optional[Dict[Any, Any]] = None, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using Heuristics Miner. + + Parameters + ---------- + dfg + Directly-Follows Graph + activities + (If provided) list of activities of the log + activities_occurrences + (If provided) dictionary of activities occurrences + start_activities + (If provided) dictionary of start activities occurrences + end_activities + (If provided) dictionary of end activities occurrences + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + + Returns + ------------ + net + Petri net + im + Initial marking + fm + Final marking + + """ + if parameters is None: + parameters = {} + + heu_net = apply_heu_dfg( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + parameters=parameters, + ) + net, im, fm = hn_conv_alg.apply(heu_net, parameters=parameters) + + return net, im, fm + + +def apply_heu( + log: EventLog, parameters: Optional[Dict[Any, Any]] = None +) -> HeuristicsNet: + """ + Discovers an Heuristics Net using Heuristics Miner. + + Parameters + ---------- + log + Event log + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + + Returns + ----------------- + heu + Heuristics Net + + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + heu_net_decoration = exec_utils.get_param_value( + Parameters.HEU_NET_DECORATION, parameters, "frequency" + ) + + start_activities = log_sa_filter.get_start_activities( + log, parameters=parameters + ) + end_activities = log_ea_filter.get_end_activities( + log, parameters=parameters + ) + activities_occurrences = log_attributes.get_attribute_values( + log, activity_key, parameters=parameters + ) + activities = list(activities_occurrences.keys()) + dfg = dfg_alg.apply(log, parameters=parameters) + parameters_w2 = deepcopy(parameters) + parameters_w2["window"] = 2 + dfg_window_2 = dfg_alg.apply(log, parameters=parameters_w2) + freq_triples = dfg_alg.apply( + log, parameters=parameters, variant=dfg_alg.Variants.FREQ_TRIPLES + ) + performance_dfg = None + if heu_net_decoration == "performance": + performance_dfg = dfg_alg.apply( + log, variant=dfg_alg.Variants.PERFORMANCE, parameters=parameters + ) + + return apply_heu_dfg( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + dfg_window_2=dfg_window_2, + freq_triples=freq_triples, + performance_dfg=performance_dfg, + parameters=parameters, + ) + + +def apply_heu_pandas( + df: pd.DataFrame, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> HeuristicsNet: + """ + Discovers an Heuristics Net using Heuristics Miner. + + Parameters + ---------- + df + Pandas dataframe + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + + Returns + ------------ + heu + Heuristics Net + + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + case_id_glue = 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, None + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + + if is_polars_lazyframe(df): + from pm4py.algo.discovery.dfg.adapters.polars import ( + df_statistics, + freq_triples as get_freq_triples, + ) + from pm4py.statistics.attributes.polars import get as pd_attributes + from pm4py.statistics.start_activities.polars import get as pd_sa_filter + from pm4py.statistics.end_activities.polars import get as pd_ea_filter + else: + from pm4py.algo.discovery.dfg.adapters.pandas import ( + df_statistics, + freq_triples as get_freq_triples, + ) + from pm4py.statistics.attributes.pandas import get as pd_attributes + from pm4py.statistics.start_activities.pandas import get as pd_sa_filter + from pm4py.statistics.end_activities.pandas import get as pd_ea_filter + + start_activities = pd_sa_filter.get_start_activities( + df, parameters=parameters + ) + end_activities = pd_ea_filter.get_end_activities(df, parameters=parameters) + activities_occurrences = pd_attributes.get_attribute_values( + df, activity_key, parameters=parameters + ) + activities = list(activities_occurrences.keys()) + heu_net_decoration = exec_utils.get_param_value( + Parameters.HEU_NET_DECORATION, parameters, "frequency" + ) + + if timestamp_key in df: + dfg = df_statistics.get_dfg_graph( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + timestamp_key=timestamp_key, + start_timestamp_key=start_timestamp_key, + ) + dfg_window_2 = df_statistics.get_dfg_graph( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + timestamp_key=timestamp_key, + window=2, + start_timestamp_key=start_timestamp_key, + ) + frequency_triples = get_freq_triples.get_freq_triples( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + timestamp_key=timestamp_key, + ) + + else: + dfg = df_statistics.get_dfg_graph( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + sort_timestamp_along_case_id=False, + ) + dfg_window_2 = df_statistics.get_dfg_graph( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + sort_timestamp_along_case_id=False, + window=2, + ) + frequency_triples = get_freq_triples.get_freq_triples( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + timestamp_key=timestamp_key, + sort_timestamp_along_case_id=False, + ) + + performance_dfg = None + if heu_net_decoration == "performance": + performance_dfg = df_statistics.get_dfg_graph( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + timestamp_key=timestamp_key, + start_timestamp_key=start_timestamp_key, + measure="performance", + ) + + heu_net = apply_heu_dfg( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + dfg_window_2=dfg_window_2, + freq_triples=frequency_triples, + performance_dfg=performance_dfg, + parameters=parameters, + ) + + return heu_net + + +def apply_heu_dfg( + dfg, + activities=None, + activities_occurrences=None, + start_activities=None, + end_activities=None, + dfg_window_2=None, + freq_triples=None, + performance_dfg=None, + parameters=None, +) -> HeuristicsNet: + """ + Discovers an Heuristics Net using Heuristics Miner. + + Parameters + ---------- + dfg + Directly-Follows Graph + activities + (If provided) list of activities of the log + activities_occurrences + (If provided) dictionary of activities occurrences + start_activities + (If provided) dictionary of start activities occurrences + end_activities + (If provided) dictionary of end activities occurrences + dfg_window_2 + (If provided) DFG of window 2 + freq_triples + (If provided) Frequency triples + performance_dfg + (If provided) Performance DFG + parameters + Possible parameters of the algorithm, + including: + + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.DFG_PRE_CLEANING_NOISE_THRESH + - Parameters.LOOP_LENGTH_TWO_THRESH + + Returns + ------------ + heu + Heuristics Net + + """ + if parameters is None: + parameters = {} + + dependency_thresh = exec_utils.get_param_value( + Parameters.DEPENDENCY_THRESH, + parameters, + defaults.DEFAULT_DEPENDENCY_THRESH, + ) + and_measure_thresh = exec_utils.get_param_value( + Parameters.AND_MEASURE_THRESH, + parameters, + defaults.DEFAULT_AND_MEASURE_THRESH, + ) + min_act_count = exec_utils.get_param_value( + Parameters.MIN_ACT_COUNT, parameters, defaults.DEFAULT_MIN_ACT_COUNT + ) + min_dfg_occurrences = exec_utils.get_param_value( + Parameters.MIN_DFG_OCCURRENCES, + parameters, + defaults.DEFAULT_MIN_DFG_OCCURRENCES, + ) + dfg_pre_cleaning_noise_thresh = exec_utils.get_param_value( + Parameters.DFG_PRE_CLEANING_NOISE_THRESH, + parameters, + defaults.DEFAULT_DFG_PRE_CLEANING_NOISE_THRESH, + ) + loops_length_two_thresh = exec_utils.get_param_value( + Parameters.LOOP_LENGTH_TWO_THRESH, + parameters, + defaults.DEFAULT_LOOP_LENGTH_TWO_THRESH, + ) + heu_net = HeuristicsNet( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + dfg_window_2=dfg_window_2, + freq_triples=freq_triples, + performance_dfg=performance_dfg, + ) + heu_net = calculate( + heu_net, + 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, + loops_length_two_thresh=loops_length_two_thresh, + ) + + return heu_net + + +def calculate( + heu_net, + dependency_thresh=defaults.DEFAULT_DEPENDENCY_THRESH, + and_measure_thresh=defaults.DEFAULT_AND_MEASURE_THRESH, + min_act_count=defaults.DEFAULT_MIN_ACT_COUNT, + min_dfg_occurrences=defaults.DEFAULT_MIN_DFG_OCCURRENCES, + dfg_pre_cleaning_noise_thresh=defaults.DEFAULT_DFG_PRE_CLEANING_NOISE_THRESH, + loops_length_two_thresh=defaults.DEFAULT_LOOP_LENGTH_TWO_THRESH, + parameters=None, +): + """ + Calculate the dependency matrix, populate the nodes + + Parameters + ------------- + dependency_thresh + (Optional) dependency threshold + and_measure_thresh + (Optional) AND measure threshold + min_act_count + (Optional) minimum number of occurrences of an activity + min_dfg_occurrences + (Optional) minimum dfg occurrences + dfg_pre_cleaning_noise_thresh + (Optional) DFG pre cleaning noise threshold + loops_length_two_thresh + (Optional) loops length two threshold + parameters + Other parameters of the algorithm + """ + if parameters is None: + parameters = {} + heu_net.min_dfg_occurrences = min_dfg_occurrences + heu_net.dependency_matrix = None + heu_net.dependency_matrix = {} + heu_net.dfg_matrix = None + heu_net.dfg_matrix = {} + heu_net.performance_matrix = None + heu_net.performance_matrix = {} + if dfg_pre_cleaning_noise_thresh > 0.0: + heu_net.dfg = clean_dfg_based_on_noise_thresh( + heu_net.dfg, + heu_net.activities, + dfg_pre_cleaning_noise_thresh, + parameters=parameters, + ) + if heu_net.dfg_window_2 is not None: + for el in heu_net.dfg_window_2: + act1 = el[0] + act2 = el[1] + value = heu_net.dfg_window_2[el] + if act1 not in heu_net.dfg_window_2_matrix: + heu_net.dfg_window_2_matrix[act1] = {} + heu_net.dfg_window_2_matrix[act1][act2] = value + if heu_net.freq_triples is not None: + for el in heu_net.freq_triples: + act1 = el[0] + act2 = el[1] + act3 = el[2] + value = heu_net.freq_triples[el] + # avoid to consider self-loops + if act1 == act3 and not act1 == act2: + if act1 not in heu_net.freq_triples_matrix: + heu_net.freq_triples_matrix[act1] = {} + heu_net.freq_triples_matrix[act1][act2] = value + for el in heu_net.dfg: + act1 = el[0] + act2 = el[1] + value = heu_net.dfg[el] + perf_value = ( + heu_net.performance_dfg[el] + if heu_net.performance_dfg is not None + else heu_net.dfg[el] + ) + if act1 not in heu_net.dependency_matrix: + heu_net.dependency_matrix[act1] = {} + heu_net.dfg_matrix[act1] = {} + heu_net.performance_matrix[act1] = {} + heu_net.dfg_matrix[act1][act2] = value + heu_net.performance_matrix[act1][act2] = perf_value + if not act1 == act2: + inv_couple = (act2, act1) + c1 = value + if inv_couple in heu_net.dfg: + c2 = heu_net.dfg[inv_couple] + dep = (c1 - c2) / (c1 + c2 + 1) + else: + dep = c1 / (c1 + 1) + else: + dep = value / (value + 1) + heu_net.dependency_matrix[act1][act2] = dep + for n1 in heu_net.dependency_matrix: + for n2 in heu_net.dependency_matrix[n1]: + condition1 = ( + n1 in heu_net.activities_occurrences + and heu_net.activities_occurrences[n1] >= min_act_count + ) + condition2 = ( + n2 in heu_net.activities_occurrences + and heu_net.activities_occurrences[n2] >= min_act_count + ) + condition3 = heu_net.dfg_matrix[n1][n2] >= min_dfg_occurrences + condition4 = heu_net.dependency_matrix[n1][n2] >= dependency_thresh + condition = condition1 and condition2 and condition3 and condition4 + if condition: + if n1 not in heu_net.nodes: + heu_net.nodes[n1] = Node( + heu_net, + n1, + heu_net.activities_occurrences[n1], + is_start_node=(n1 in heu_net.start_activities), + is_end_node=(n1 in heu_net.end_activities), + default_edges_color=heu_net.default_edges_color[0], + node_type=heu_net.node_type, + net_name=heu_net.net_name[0], + nodes_dictionary=heu_net.nodes, + ) + if n2 not in heu_net.nodes: + heu_net.nodes[n2] = Node( + heu_net, + n2, + heu_net.activities_occurrences[n2], + is_start_node=(n2 in heu_net.start_activities), + is_end_node=(n2 in heu_net.end_activities), + default_edges_color=heu_net.default_edges_color[0], + node_type=heu_net.node_type, + net_name=heu_net.net_name[0], + nodes_dictionary=heu_net.nodes, + ) + + repr_value = heu_net.performance_matrix[n1][n2] + heu_net.nodes[n1].add_output_connection( + heu_net.nodes[n2], + heu_net.dependency_matrix[n1][n2], + heu_net.dfg_matrix[n1][n2], + repr_value=repr_value, + ) + heu_net.nodes[n2].add_input_connection( + heu_net.nodes[n1], + heu_net.dependency_matrix[n1][n2], + heu_net.dfg_matrix[n1][n2], + repr_value=repr_value, + ) + for node in heu_net.nodes: + heu_net.nodes[node].calculate_and_measure_out( + and_measure_thresh=and_measure_thresh + ) + heu_net.nodes[node].calculate_and_measure_in( + and_measure_thresh=and_measure_thresh + ) + heu_net.nodes[node].calculate_loops_length_two( + heu_net.dfg_matrix, + heu_net.freq_triples_matrix, + loops_length_two_thresh=loops_length_two_thresh, + ) + nodes = list(heu_net.nodes.keys()) + added_loops = set() + for n1 in nodes: + for n2 in heu_net.nodes[n1].loop_length_two: + if ( + n1 in heu_net.dfg_matrix + and n2 in heu_net.dfg_matrix[n1] + and heu_net.dfg_matrix[n1][n2] >= min_dfg_occurrences + and n1 in heu_net.activities_occurrences + and heu_net.activities_occurrences[n1] >= min_act_count + and n2 in heu_net.activities_occurrences + and heu_net.activities_occurrences[n2] >= min_act_count + ): + if not ( + ( + n1 in heu_net.dependency_matrix + and n2 in heu_net.dependency_matrix[n1] + and heu_net.dependency_matrix[n1][n2] + >= dependency_thresh + ) + or ( + n2 in heu_net.dependency_matrix + and n1 in heu_net.dependency_matrix[n2] + and heu_net.dependency_matrix[n2][n1] + >= dependency_thresh + ) + ): + if n2 not in heu_net.nodes: + heu_net.nodes[n2] = Node( + heu_net, + n2, + heu_net.activities_occurrences[n2], + is_start_node=(n2 in heu_net.start_activities), + is_end_node=(n2 in heu_net.end_activities), + default_edges_color=heu_net.default_edges_color[0], + node_type=heu_net.node_type, + net_name=heu_net.net_name[0], + nodes_dictionary=heu_net.nodes, + ) + v_n1_n2 = ( + heu_net.dfg_matrix[n1][n2] + if n1 in heu_net.dfg_matrix + and n2 in heu_net.dfg_matrix[n1] + else 0 + ) + v_n2_n1 = ( + heu_net.dfg_matrix[n2][n1] + if n2 in heu_net.dfg_matrix + and n1 in heu_net.dfg_matrix[n2] + else 0 + ) + + if (n1, n2) not in added_loops: + repr_value = ( + heu_net.performance_matrix[n1][n2] + if n1 in heu_net.performance_matrix + and n2 in heu_net.performance_matrix[n1] + else 0 + ) + added_loops.add((n1, n2)) + heu_net.nodes[n1].add_output_connection( + heu_net.nodes[n2], + 0, + v_n1_n2, + repr_value=repr_value, + ) + heu_net.nodes[n2].add_input_connection( + heu_net.nodes[n1], + 0, + v_n2_n1, + repr_value=repr_value, + ) + + if (n2, n1) not in added_loops: + repr_value = ( + heu_net.performance_matrix[n2][n1] + if n2 in heu_net.performance_matrix + and n1 in heu_net.performance_matrix[n2] + else 0 + ) + added_loops.add((n2, n1)) + heu_net.nodes[n2].add_output_connection( + heu_net.nodes[n1], + 0, + v_n2_n1, + repr_value=repr_value, + ) + heu_net.nodes[n1].add_input_connection( + heu_net.nodes[n2], + 0, + v_n1_n2, + repr_value=repr_value, + ) + if len(heu_net.nodes) == 0: + for act in heu_net.activities: + heu_net.nodes[act] = Node( + heu_net, + act, + heu_net.activities_occurrences[act], + is_start_node=(act in heu_net.start_activities), + is_end_node=(act in heu_net.end_activities), + default_edges_color=heu_net.default_edges_color[0], + node_type=heu_net.node_type, + net_name=heu_net.net_name[0], + nodes_dictionary=heu_net.nodes, + ) + + return heu_net diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/plusplus.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/plusplus.py new file mode 100644 index 0000000000000000000000000000000000000000..b30d06a75d96c8a7bca027bc99ecba108f0de1c2 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/heuristics/variants/plusplus.py @@ -0,0 +1,818 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 + +import pandas as pd + +from pm4py.algo.discovery.dfg import algorithm as dfg_alg +from pm4py.objects.conversion.heuristics_net import converter as hn_conv_alg +from pm4py.objects.conversion.log import converter as log_converter +from pm4py.objects.heuristics_net import defaults +from pm4py.objects.heuristics_net.obj import HeuristicsNet +from pm4py.objects.heuristics_net.node import Node +from pm4py.objects.log.obj import EventLog +from pm4py.objects.log.util import interval_lifecycle +from pm4py.objects.petri_net.obj import PetriNet, Marking +from pm4py.statistics.attributes.log import get as log_attributes +from pm4py.statistics.concurrent_activities.log import get as conc_act_get +from pm4py.statistics.end_activities.log import get as log_ea +from pm4py.statistics.eventually_follows.log import get as efg_get +from pm4py.statistics.service_time.log import get as soj_get +from pm4py.statistics.start_activities.log import get as log_sa +from pm4py.util import exec_utils, constants, xes_constants as xes + + +class Parameters(Enum): + 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 + DEPENDENCY_THRESH = "dependency_thresh" + AND_MEASURE_THRESH = "and_measure_thresh" + MIN_ACT_COUNT = "min_act_count" + MIN_DFG_OCCURRENCES = "min_dfg_occurrences" + HEU_NET_DECORATION = "heu_net_decoration" + +def is_polars_lazyframe(df: Any) -> bool: + """Return True if the provided dataframe is a Polars LazyFrame.""" + df_type = str(type(df)).lower() + return "polars" in df_type and "lazyframe" in df_type + + +def apply( + log: EventLog, parameters: Optional[Dict[Any, Any]] = None +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using the Heuristics Miner ++ algorithm + + Implements the approach described in + Burattin, Andrea, and Alessandro Sperduti. "Heuristics Miner for Time Intervals." ESANN. 2010. + + https://andrea.burattin.net/public-files/publications/2010-esann-slides.pdf + + Parameters + -------------- + log + Event log + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.START_TIMESTAMP_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.HEU_NET_DECORATION + + Returns + -------------- + net + Petri net + im + Initial marking + fm + Final marking + """ + heu_net = apply_heu(log, parameters=parameters) + net, im, fm = hn_conv_alg.apply(heu_net, parameters=parameters) + return net, im, fm + + +def apply_pandas( + df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using the Heuristics Miner ++ algorithm + + Implements the approach described in + Burattin, Andrea, and Alessandro Sperduti. "Heuristics Miner for Time Intervals." ESANN. 2010. + + https://andrea.burattin.net/public-files/publications/2010-esann-slides.pdf + + Parameters + -------------- + df + Dataframe + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.START_TIMESTAMP_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.HEU_NET_DECORATION + + Returns + -------------- + net + Petri net + im + Initial marking + fm + Final marking + """ + heu_net = apply_heu_pandas(df, parameters=parameters) + net, im, fm = hn_conv_alg.apply(heu_net, parameters=parameters) + return net, im, fm + + +def apply_heu( + log: EventLog, parameters: Optional[Dict[Any, Any]] = None +) -> HeuristicsNet: + """ + Discovers an heuristics net using the Heuristics Miner ++ algorithm + + Implements the approach described in + Burattin, Andrea, and Alessandro Sperduti. "Heuristics Miner for Time Intervals." ESANN. 2010. + + https://andrea.burattin.net/public-files/publications/2010-esann-slides.pdf + + Parameters + -------------- + log + Event log + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.START_TIMESTAMP_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.HEU_NET_DECORATION + + Returns + -------------- + heu_net + Heuristics net + """ + if parameters is None: + parameters = {} + + log = log_converter.apply( + log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters + ) + log = interval_lifecycle.to_interval(log, parameters=parameters) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, parameters, None + ) + if start_timestamp_key is None: + start_timestamp_key = xes.DEFAULT_START_TIMESTAMP_KEY + parameters = copy(parameters) + parameters[Parameters.START_TIMESTAMP_KEY] = start_timestamp_key + ( + start_activities, + end_activities, + activities_occurrences, + dfg, + performance_dfg, + sojourn_time, + concurrent_activities, + ) = discover_abstraction_log(log, parameters=parameters) + return discover_heu_net_plus_plus( + start_activities, + end_activities, + activities_occurrences, + dfg, + performance_dfg, + sojourn_time, + concurrent_activities, + parameters=parameters, + ) + + +def discover_abstraction_log( + log: EventLog, parameters: Optional[Dict[Any, Any]] = None +) -> Tuple[Any, Any, Any, Any, Any, Any, Any]: + """ + Discovers an abstraction from a log that is useful for the Heuristics Miner ++ algorithm + + Parameters + -------------- + log + Event log + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.START_TIMESTAMP_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + + Returns + -------------- + start_activities + Start activities + end_activities + End activities + activities_occurrences + Activities along with their number of occurrences + dfg + Directly-follows graph + performance_dfg + (Performance) Directly-follows graph + sojourn_time + Sojourn time for each activity + concurrent_activities + Concurrent activities + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + start_activities = log_sa.get_start_activities(log, parameters=parameters) + end_activities = log_ea.get_end_activities(log, parameters=parameters) + activities_occurrences = log_attributes.get_attribute_values( + log, activity_key, parameters=parameters + ) + efg_parameters = copy(parameters) + efg_parameters[efg_get.Parameters.KEEP_FIRST_FOLLOWING] = True + dfg = efg_get.apply(log, parameters=efg_parameters) + performance_dfg = dfg_alg.apply( + log, variant=dfg_alg.Variants.PERFORMANCE, parameters=parameters + ) + sojourn_time = soj_get.apply(log, parameters=parameters) + concurrent_activities = conc_act_get.apply(log, parameters=parameters) + return ( + start_activities, + end_activities, + activities_occurrences, + dfg, + performance_dfg, + sojourn_time, + concurrent_activities, + ) + + +def apply_heu_pandas( + df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None +) -> HeuristicsNet: + """ + Discovers an heuristics net using the Heuristics Miner ++ algorithm + + Implements the approach described in + Burattin, Andrea, and Alessandro Sperduti. "Heuristics Miner for Time Intervals." ESANN. 2010. + + https://andrea.burattin.net/public-files/publications/2010-esann-slides.pdf + + Parameters + -------------- + df + Dataframe + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.START_TIMESTAMP_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.HEU_NET_DECORATION + + Returns + -------------- + heu_net + Heuristics net + """ + if parameters is None: + parameters = {} + ( + start_activities, + end_activities, + activities_occurrences, + dfg, + performance_dfg, + sojourn_time, + concurrent_activities, + ) = discover_abstraction_dataframe(df, parameters=parameters) + return discover_heu_net_plus_plus( + start_activities, + end_activities, + activities_occurrences, + dfg, + performance_dfg, + sojourn_time, + concurrent_activities, + parameters=parameters, + ) + + +def discover_abstraction_dataframe( + df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None +) -> Tuple[Any, Any, Any, Any, Any, Any, Any]: + """ + Discovers an abstraction from a dataframe that is useful for the Heuristics Miner ++ algorithm + + Parameters + -------------- + df + Dataframe + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.START_TIMESTAMP_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + + Returns + -------------- + start_activities + Start activities + end_activities + End activities + activities_occurrences + Activities along with their number of occurrences + dfg + Directly-follows graph + performance_dfg + (Performance) Directly-follows graph + sojourn_time + Sojourn time for each activity + concurrent_activities + Concurrent activities + """ + if parameters is None: + parameters = {} + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + start_timestamp_key = exec_utils.get_param_value( + Parameters.START_TIMESTAMP_KEY, parameters, None + ) + if start_timestamp_key is None: + start_timestamp_key = xes.DEFAULT_START_TIMESTAMP_KEY + parameters = copy(parameters) + parameters[Parameters.START_TIMESTAMP_KEY] = start_timestamp_key + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + case_id_glue = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + + if is_polars_lazyframe(df): + from pm4py.algo.discovery.dfg.adapters.polars import df_statistics + from pm4py.statistics.attributes.polars import get as pd_attributes + from pm4py.statistics.concurrent_activities.polars import get as pd_conc_act + from pm4py.statistics.end_activities.polars import get as pd_ea + from pm4py.statistics.eventually_follows.polars import get as pd_efg + from pm4py.statistics.service_time.polars import get as pd_soj_time + from pm4py.statistics.start_activities.polars import get as pd_sa + else: + from pm4py.algo.discovery.dfg.adapters.pandas import df_statistics + from pm4py.statistics.attributes.pandas import get as pd_attributes + from pm4py.statistics.concurrent_activities.pandas import get as pd_conc_act + from pm4py.statistics.end_activities.pandas import get as pd_ea + from pm4py.statistics.eventually_follows.pandas import get as pd_efg + from pm4py.statistics.service_time.pandas import get as pd_soj_time + from pm4py.statistics.start_activities.pandas import get as pd_sa + + start_activities = pd_sa.get_start_activities(df, parameters=parameters) + end_activities = pd_ea.get_end_activities(df, parameters=parameters) + activities_occurrences = pd_attributes.get_attribute_values( + df, activity_key, parameters=parameters + ) + efg_parameters = copy(parameters) + efg_parameters[pd_efg.Parameters.KEEP_FIRST_FOLLOWING] = True + dfg = pd_efg.apply(df, parameters=efg_parameters) + performance_dfg = df_statistics.get_dfg_graph( + df, + case_id_glue=case_id_glue, + activity_key=activity_key, + timestamp_key=timestamp_key, + start_timestamp_key=start_timestamp_key, + measure="performance", + ) + sojourn_time = pd_soj_time.apply(df, parameters=parameters) + concurrent_activities = pd_conc_act.apply(df, parameters=parameters) + return ( + start_activities, + end_activities, + activities_occurrences, + dfg, + performance_dfg, + sojourn_time, + concurrent_activities, + ) + + +def discover_heu_net_plus_plus( + start_activities, + end_activities, + activities_occurrences, + dfg, + performance_dfg, + sojourn_time, + concurrent_activities, + parameters: Optional[Dict[Any, Any]] = None, +): + """ + Discovers an heuristics net using the Heuristics Miner ++ algorithm + + Implements the approach described in + Burattin, Andrea, and Alessandro Sperduti. "Heuristics Miner for Time Intervals." ESANN. 2010. + + https://andrea.burattin.net/public-files/publications/2010-esann-slides.pdf + + Parameters + -------------- + start_activities + Start activities + end_activities + End activities + activities_occurrences + Activities along with their number of occurrences + dfg + Directly-follows graph + performance_dfg + (Performance) Directly-follows graph + sojourn_time + Sojourn time for each activity + concurrent_activities + Concurrent activities + parameters + Parameters of the algorithm, including: + - Parameters.DEPENDENCY_THRESH + - Parameters.AND_MEASURE_THRESH + - Parameters.MIN_ACT_COUNT + - Parameters.MIN_DFG_OCCURRENCES + - Parameters.HEU_NET_DECORATION + + Returns + -------------- + heu_net + Heuristics net + """ + if parameters is None: + parameters = {} + dependency_thresh = exec_utils.get_param_value( + Parameters.DEPENDENCY_THRESH, + parameters, + defaults.DEFAULT_DEPENDENCY_THRESH, + ) + and_measure_thresh = exec_utils.get_param_value( + Parameters.AND_MEASURE_THRESH, + parameters, + defaults.DEFAULT_AND_MEASURE_THRESH, + ) + min_act_count = exec_utils.get_param_value( + Parameters.MIN_ACT_COUNT, parameters, defaults.DEFAULT_MIN_ACT_COUNT + ) + min_dfg_occurrences = exec_utils.get_param_value( + Parameters.MIN_DFG_OCCURRENCES, + parameters, + defaults.DEFAULT_MIN_DFG_OCCURRENCES, + ) + heu_net_decoration = exec_utils.get_param_value( + Parameters.HEU_NET_DECORATION, parameters, "frequency" + ) + + # filter on activity and paths occurrence + activities_occurrences = { + x: y for x, y in activities_occurrences.items() if y >= min_act_count + } + dfg = { + x: y + for x, y in dfg.items() + if y >= min_dfg_occurrences + and x[0] in activities_occurrences + and x[1] in activities_occurrences + } + performance_dfg = {x: y for x, y in performance_dfg.items() if x in dfg} + start_activities = { + x: y + for x, y in start_activities.items() + if x in activities_occurrences + } + end_activities = { + x: y for x, y in end_activities.items() if x in activities_occurrences + } + activities = list(activities_occurrences.keys()) + if heu_net_decoration == "frequency": + heu_net = HeuristicsNet( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + ) + else: + heu_net = HeuristicsNet( + dfg, + activities=activities, + activities_occurrences=activities_occurrences, + start_activities=start_activities, + end_activities=end_activities, + performance_dfg=performance_dfg, + ) + heu_net.min_dfg_occurrences = min_dfg_occurrences + heu_net.sojourn_times = sojourn_time + heu_net.concurrent_activities = concurrent_activities + return calculate( + heu_net, dependency_thresh, and_measure_thresh, heu_net_decoration + ) + + +def calculate( + heu_net: HeuristicsNet, + dependency_thresh: float, + and_measure_thresh: float, + heu_net_decoration: str, +) -> HeuristicsNet: + """ + Calculates the dependency matrix and the AND measures using the Heuristics Miner ++ formulas + + Parameters + ---------------- + heu_net + Heuristics net + dependency_thresh + Dependency threshold + and_measure_thresh + AND measure threshold + heu_net_decoration + Decoration to use (frequency/performance) + + Returns + ---------------- + heu_net + Heuristics net + """ + heu_net.performance_matrix = {} + heu_net.dependency_matrix = {} + heu_net.dfg_matrix = {} + for el in heu_net.dfg: + act1 = el[0] + act2 = el[1] + if act1 not in heu_net.dfg_matrix: + heu_net.dfg_matrix[act1] = {} + heu_net.dependency_matrix[act1] = {} + heu_net.performance_matrix[act1] = {} + heu_net.dfg_matrix[act1][act2] = heu_net.dfg[el] + heu_net.dependency_matrix[act1][act2] = -1 + heu_net.performance_matrix[act1][act2] = ( + heu_net.performance_dfg[el] + if heu_net.performance_dfg and el in heu_net.performance_dfg + else 0.0 + ) + for act1 in heu_net.activities: + heu_net.nodes[act1] = Node( + heu_net, + act1, + heu_net.activities_occurrences[act1], + node_type=heu_net.node_type, + ) + # calculates the dependencies between the activities + heu_net = calculate_dependency( + heu_net, dependency_thresh, heu_net_decoration + ) + # calculates the AND measure for outgoing edges (e.g. which activities + # happen in parallel after a given activity) + heu_net = calculate_and_out_measure(heu_net, and_measure_thresh) + # calculates the AND measure for ingoing edges (e.g. which activities + # happen in parallel before a given activity) + heu_net = calculate_and_in_measure(heu_net, and_measure_thresh) + return heu_net + + +def calculate_dependency( + heu_net: HeuristicsNet, dependency_thresh: float, heu_net_decoration: str +) -> HeuristicsNet: + """ + Calculates the dependency matrix using the Heuristics Miner ++ formula + + Parameters + -------------- + heu_net + Heuristics net + dependency_thresh + Dependency threshold + heu_net_decoration + Decoration to include (frequency/performance) + + Returns + --------------- + heu_net + Heuristics net (enriched) + """ + for act1 in heu_net.activities: + if act1 in heu_net.dfg_matrix: + for act2 in heu_net.dfg_matrix[act1]: + v1 = heu_net.dfg_matrix[act1][act2] + v2 = ( + heu_net.dfg_matrix[act2][act1] + if act2 in heu_net.dfg_matrix + and act1 in heu_net.dfg_matrix[act2] + else 0.0 + ) + tup = tuple(sorted((act1, act2))) + # added term for Heuristics Miner ++ + v3 = ( + heu_net.concurrent_activities[tup] + if tup in heu_net.concurrent_activities + else 0.0 + ) + dep = (v1 - v2) / (v1 + v2 + v3) + heu_net.dependency_matrix[act1][act2] = dep + if dep > dependency_thresh: + repr_value = ( + v1 + if heu_net_decoration == "frequency" + else heu_net.performance_matrix[act1][act2] + ) + heu_net.nodes[act1].add_output_connection( + heu_net.nodes[act2], dep, v1, repr_value=repr_value + ) + heu_net.nodes[act2].add_input_connection( + heu_net.nodes[act1], dep, v1, repr_value=repr_value + ) + return heu_net + + +def calculate_and_out_measure( + heu_net: HeuristicsNet, and_measure_thresh: float +) -> HeuristicsNet: + """ + Calculates the AND measure for outgoing edges using the Heuristics Miner ++ formula + + Parameters + --------------- + heu_net + Heuristics net + and_measure_thresh + And measure threshold + + Returns + --------------- + heu_net + Heuristics net (enriched) + """ + for act in heu_net.nodes: + nodes = sorted( + x.node_name for x in heu_net.nodes[act].output_connections + ) + i = 0 + while i < len(nodes): + n1 = nodes[i] + v3 = ( + heu_net.dfg_matrix[act][n1] + if act in heu_net.dfg_matrix and n1 in heu_net.dfg_matrix[act] + else 0.0 + ) + j = i + 1 + while j < len(nodes): + n2 = nodes[j] + tup = tuple(sorted((n1, n2))) + v1 = ( + heu_net.dfg_matrix[n1][n2] + if n1 in heu_net.dfg_matrix + and n2 in heu_net.dfg_matrix[n1] + else 0.0 + ) + v2 = ( + heu_net.dfg_matrix[n2][n1] + if n2 in heu_net.dfg_matrix + and n1 in heu_net.dfg_matrix[n2] + else 0.0 + ) + v4 = ( + heu_net.dfg_matrix[act][n2] + if act in heu_net.dfg_matrix + and n2 in heu_net.dfg_matrix[act] + else 0.0 + ) + # added term for Heuristics Miner ++ + v5 = ( + heu_net.concurrent_activities[tup] + if tup in heu_net.concurrent_activities + else 0.0 + ) + this_value = (v1 + v2 + v5) / (v3 + v4) + if this_value > and_measure_thresh: + if n1 not in heu_net.nodes[act].and_measures_out: + heu_net.nodes[act].and_measures_out[n1] = {} + heu_net.nodes[act].and_measures_out[n1][n2] = this_value + j = j + 1 + i = i + 1 + return heu_net + + +def calculate_and_in_measure( + heu_net: HeuristicsNet, and_measure_thresh: float +) -> HeuristicsNet: + """ + Calculates the AND measure for incoming edges using the Heuristics Miner ++ formula + + Parameters + --------------- + heu_net + Heuristics net + and_measure_thresh + And measure threshold + + Returns + --------------- + heu_net + Heuristics net (enriched) + """ + for act in heu_net.nodes: + nodes = sorted( + x.node_name for x in heu_net.nodes[act].input_connections + ) + i = 0 + while i < len(nodes): + n1 = nodes[i] + v3 = ( + heu_net.dfg_matrix[n1][act] + if n1 in heu_net.dfg_matrix and act in heu_net.dfg_matrix[n1] + else 0.0 + ) + j = i + 1 + while j < len(nodes): + n2 = nodes[j] + tup = tuple(sorted((n1, n2))) + v1 = ( + heu_net.dfg_matrix[n1][n2] + if n1 in heu_net.dfg_matrix + and n2 in heu_net.dfg_matrix[n1] + else 0.0 + ) + v2 = ( + heu_net.dfg_matrix[n2][n1] + if n2 in heu_net.dfg_matrix + and n1 in heu_net.dfg_matrix[n2] + else 0.0 + ) + v4 = ( + heu_net.dfg_matrix[n2][act] + if n2 in heu_net.dfg_matrix + and act in heu_net.dfg_matrix[n2] + else 0.0 + ) + # added term for Heuristics Miner ++ + v5 = ( + heu_net.concurrent_activities[tup] + if tup in heu_net.concurrent_activities + else 0.0 + ) + this_value = (v1 + v2 + v5) / (v3 + v4) + if this_value > and_measure_thresh: + if n1 not in heu_net.nodes[act].and_measures_in: + heu_net.nodes[act].and_measures_in[n1] = {} + heu_net.nodes[act].and_measures_in[n1][n2] = this_value + j = j + 1 + i = i + 1 + return heu_net + + +def apply_dfg( + dfg, + activities=None, + activities_occurrences=None, + start_activities=None, + end_activities=None, + parameters=None, +): + raise Exception("not implemented for plusplus version") + + +def apply_heu_dfg( + dfg, + activities=None, + activities_occurrences=None, + start_activities=None, + end_activities=None, + dfg_window_2=None, + freq_triples=None, + parameters=None, +): + raise Exception("not implemented for plusplus version") diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..163fbfda7e3eccdb67297b34aad6e3e7d2327dac --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/__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.discovery.ilp import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..c16ce14ac8af9d44b5069e982dea9eac9a444588 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/algorithm.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 enum import Enum +from pm4py.util import exec_utils +from pm4py.algo.discovery.ilp.variants import classic +from typing import Union, Optional, Dict, Any, Tuple +from pm4py.objects.petri_net.obj import PetriNet, Marking +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd + + +class Variants(Enum): + CLASSIC = classic + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using the ILP miner. + + Parameters + --------------- + log + Event log / Event stream / Pandas dataframe + variant + Variant of the algorithm to be used, possible values: + - Variants.CLASSIC + parameters + Variant-specific parameters + + Returns + --------------- + net + Petri net + im + Initial marking + fm + Final marking + """ + return exec_utils.get_variant(variant).apply(log, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f535f0d7124eafba4862552fb32282922bd08dc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/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.algo.discovery.ilp.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..98744248910f4b8ad65dd8beb6dbb62326b961b1 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ilp/variants/classic.py @@ -0,0 +1,414 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 import nx_utils + +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd +from typing import Union, Optional, Dict, Any, Tuple, List +from pm4py.objects.petri_net.obj import PetriNet, Marking +from enum import Enum +from pm4py.util import exec_utils, xes_constants, constants +import warnings +from pm4py.objects.conversion.log import converter as log_converter +from pm4py.objects.log.util import filtering_utils +from pm4py.util.lp import solver as lp_solver +from pm4py.objects.petri_net.utils import petri_utils +from pm4py.objects.log.util import artificial +from copy import copy, deepcopy +from pm4py.algo.discovery.causal import algorithm as causal_discovery +from pm4py.algo.discovery.dfg import algorithm as dfg_discovery +from pm4py.objects.petri_net.utils import murata +from pm4py.objects.petri_net.utils import reduction +import importlib.util + + +class Parameters(Enum): + 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 + CAUSAL_RELATION = "causal_relation" + SHOW_PROGRESS_BAR = "show_progress_bar" + ALPHA = "alpha" + + +def __transform_log_to_matrix( + log: EventLog, activities: List[str], activity_key: str +): + """ + Internal method + Transforms the event log in a numeric matrix that is used to construct the linear problem. + """ + matr = [] + for trace in log: + vect = [] + rep = np.array([0] * len(activities)) + for i in range(len(trace)): + repi = rep.copy() + repi[activities.index(trace[i][activity_key])] += 1 + vect.append(repi) + rep = repi + matr.append(vect) + return matr + + +def __manage_solution( + sol, added_places, explored_solutions, net, activities, trans_map +): + """ + Internal method. + Manages the solution of the linear problem and possibly adds it as a place of the Petri net + """ + if sol.success: + sol = lp_solver.get_points_from_sol(sol, variant=lp_solver.SCIPY) + sol = [round(x) for x in sol] + + if tuple(sol) not in added_places: + added_places.add(tuple(sol)) + sol = np.array(sol) + + x0 = np.array(sol[: len(activities)]) + y0 = np.array(sol[len(activities): 2 * len(activities)]) + + if max(x0) > 0 and max(y0) > 0: + place = PetriNet.Place(str(len(net.places))) + net.places.add(place) + i = 0 + while i < len(activities): + if sol[i] == 1: + petri_utils.add_arc_from_to( + trans_map[activities[i]], place, net + ) + i = i + 1 + while i < 2 * len(activities): + if sol[i] == 1: + petri_utils.add_arc_from_to( + place, + trans_map[activities[i - len(activities)]], + net, + ) + i = i + 1 + vec = x0.tolist() + (y0 - 1).tolist() + [sol[-1]] + b = sol[-1] - 1 + x0.sum() + + explored_solutions.add((tuple(vec), b)) + + return vec, b + + return None, None + + +def apply( + log0: Union[EventLog, EventStream, pd.DataFrame], + parameters: Optional[Dict[Any, Any]] = None, +) -> Tuple[PetriNet, Marking, Marking]: + """ + Discovers a Petri net using the ILP miner. + + The implementation follows what is described in the scientific paper: + van Zelst, Sebastiaan J., et al. + "Discovering workflow nets using integer linear programming." Computing 100.5 (2018): 529-556. + + Parameters + --------------- + log0 + Event log / Event stream / Pandas dataframe + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY => the attribute to be used as activity + - Parameters.SHOW_PROGRESS_BAR => decides if the progress bar should be shown + + Returns + --------------- + net + Petri net + im + Initial marking + fm + Final marking + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_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, + ) + show_progress_bar = exec_utils.get_param_value( + Parameters.SHOW_PROGRESS_BAR, parameters, constants.SHOW_PROGRESS_BAR + ) + + log0 = log_converter.apply( + log0, + variant=log_converter.Variants.TO_EVENT_LOG, + parameters=parameters, + ) + log0 = filtering_utils.keep_one_trace_per_variant( + log0, parameters=parameters + ) + log = artificial.insert_artificial_start_end( + deepcopy(log0), parameters=parameters + ) + # use the ALPHA causal relation if none is provided as parameter + causal = exec_utils.get_param_value( + Parameters.CAUSAL_RELATION, + parameters, + causal_discovery.apply( + dfg_discovery.apply(log, parameters=parameters) + ), + ) + # noise threshold for the sequence encoding graph (when alpha=1, no + # filtering is applied; when alpha=0, the greatest filtering is applied) + alpha = exec_utils.get_param_value(Parameters.ALPHA, parameters, 1.0) + + activities = sorted( + list(set(x[activity_key] for trace in log for x in trace)) + ) + + # check if the causal relation satisfy the criteria for relaxed sound + # WF-nets + G = nx_utils.DiGraph() + for ca in causal: + G.add_edge(ca[0], ca[1]) + + desc_start = set(nx_utils.descendants(G, artificial_start_activity)) + anc_end = set(nx_utils.ancestors(G, artificial_end_activity)) + + if ( + artificial_start_activity in desc_start + or artificial_end_activity in anc_end + or len( + desc_start.union({artificial_start_activity}).difference( + activities + ) + ) + > 0 + or len(anc_end.union({artificial_end_activity}).difference(activities)) + > 0 + ): + if constants.SHOW_INTERNAL_WARNINGS: + warnings.warn( + "The conditions needed to ensure a relaxed sound WF-net as output are not satisfied." + ) + + matr = __transform_log_to_matrix(log, activities, activity_key) + + net = PetriNet("ilp") + im = Marking() + fm = Marking() + source = PetriNet.Place("source") + sink = PetriNet.Place("sink") + net.places.add(source) + net.places.add(sink) + im[source] = 1 + fm[sink] = 1 + trans_map = {} + + # STEP A) construction of the transitions of the Petri net. + # the source and sink place are connected respectively to the artificial + # start/end activities + for act in activities: + label = ( + act + if act not in [artificial_start_activity, artificial_end_activity] + else None + ) + trans_map[act] = PetriNet.Transition(act, label) + net.transitions.add(trans_map[act]) + + if act == artificial_start_activity: + petri_utils.add_arc_from_to(source, trans_map[act], net) + elif act == artificial_end_activity: + petri_utils.add_arc_from_to(trans_map[act], sink, net) + + # STEP B) construction of the sequence encoding graph + seq_enc_graph = {} + for j in range(len(matr)): + trace = matr[j] + trace_occ = log0[j].attributes["@@num_traces"] + for i in range(len(trace)): + prev = -trace[i - 1] if i > 0 else np.zeros(len(activities)) + curr = trace[i] + prev = tuple(prev) + curr = tuple(curr) + if prev not in seq_enc_graph: + seq_enc_graph[prev] = {} + if curr not in seq_enc_graph[prev]: + seq_enc_graph[prev][curr] = 0 + seq_enc_graph[prev][curr] += trace_occ + max_child_seq_enc_graph = { + x: max(y.values()) for x, y in seq_enc_graph.items() + } + + # STEP C) construction of the base linear problem + # which will be 'extended' in each step + c = np.zeros(2 * len(activities)) + Aub = [] + bub = [] + Aeq = [] + beq = [] + + added_rows_Aub = set() + added_rows_Aeq = set() + + for trace in matr: + for i in range(len(trace)): + row1 = -trace[i - 1] if i > 0 else np.zeros(len(activities)) + row2 = trace[i] + prev = tuple(row1) + curr = tuple(row2) + + if ( + seq_enc_graph[prev][curr] + >= (1 - alpha) * max_child_seq_enc_graph[prev] + ): + row = row1.tolist() + row2.tolist() + [-1] + if i < len(trace) - 1: + if tuple(row) not in added_rows_Aub: + added_rows_Aub.add(tuple(row)) + Aub.append(row) + bub.append(0) + else: + if tuple(row) not in added_rows_Aeq: + # deviation 1: impose that the place is empty at the + # end of every trace of the log + added_rows_Aeq.add(tuple(row)) + Aeq.append(row) + beq.append(0) + + crow = row2.tolist() + (-row2).tolist() + c += crow + else: + # break not only the current node but all his children + break + + Aub.append([-1] * (2 * len(activities)) + [0]) + bub.append(-1) + + for i in range(2 * len(activities) + 1): + row1 = [0] * (2 * len(activities) + 1) + row1[i] = -1 + Aub.append(row1) + bub.append(0) + row2 = [0] * (2 * len(activities) + 1) + row2[i] = 1 + Aub.append(row2) + bub.append(1) + + # deviation 2: seek only for places that contains initially 0 tokens + const = [0] * (2 * len(activities)) + [1] + Aub.append(const) + bub.append(0) + + c = c.tolist() + c.append(1) + + integrality = [1] * (2 * len(activities) + 1) + + ite = 0 + added_places = set() + explored_solutions = set() + + progress = None + if ( + importlib.util.find_spec("tqdm") + and show_progress_bar + and len(causal) > 1 + ): + from tqdm.auto import tqdm + + progress = tqdm( + total=len(causal), + desc="discovering Petri net using ILP miner, completed causal relations :: ", + ) + + # STEP D) explore all the causal relations in the log + # to find places + for ca in causal: + Aeq1 = copy(Aeq) + beq1 = copy(beq) + + const1 = [0] * (2 * len(activities) + 1) + const1[activities.index(ca[0])] = 1 + Aeq1.append(const1) + beq1.append(1) + + const2 = [0] * (2 * len(activities) + 1) + const2[len(activities) + activities.index(ca[1])] = 1 + Aeq1.append(const2) + beq1.append(1) + + sol = lp_solver.apply( + c, + Aub, + bub, + Aeq1, + beq1, + variant=lp_solver.SCIPY, + parameters={"integrality": integrality}, + ) + __manage_solution( + sol, added_places, explored_solutions, net, activities, trans_map + ) + + ite += 1 + + if progress is not None: + progress.update() + + # gracefully close progress bar + if progress is not None: + progress.close() + del progress + + # here, we also implement the extensive research for places (closing the LP space to previous solutions) + # as described in the paper (possible STEP D) + """for tup in explored_solutions: + Aub.append(list(tup[0])) + bub.append(tup[1]) + while True: + sol = lp_solver.apply(c, Aub, bub, Aeq, beq, variant=lp_solver.SCIPY, parameters={"integrality": integrality}) + + vec, b = __manage_solution(sol, added_places, explored_solutions, net, activities, trans_map) + + if vec is not None: + Aub.append(vec) + bub.append(b) + ite += 1 + if ite >= 25: + break""" + + # STEP E) apply the reduction on the implicit places and on the invisible + # transitions + net, im, fm = murata.apply_reduction(net, im, fm) + net = reduction.apply_simple_reduction(net) + + return net, im, fm diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..955548d8aadf7b5bc4fbf02edc57146f22e59ade --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/__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.discovery.inductive import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..cb77c35a6f0e32a1b4c5c5413cfca940106a273e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/algorithm.py @@ -0,0 +1,115 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 + +import pandas as pd + +from pm4py import util as pmutil +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.algo.discovery.inductive.variants.im import IMUVCL +from pm4py.algo.discovery.inductive.variants.imf import IMFUVCL +from pm4py.algo.discovery.inductive.variants.imd import IMD +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.dfg.obj import DFG +from pm4py.objects.log.obj import EventLog +from pm4py.objects.process_tree.obj import ProcessTree +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 constants +import warnings +from pm4py.util import exec_utils +from pm4py.util import xes_constants as xes_util +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL + + +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 + + +class Variants(Enum): + IM = IMInstance.IM + IMf = IMInstance.IMf + IMd = IMInstance.IMd + + +def apply( + obj: Union[EventLog, pd.DataFrame, DFG, UVCL], + parameters: Optional[Dict[Any, Any]] = None, + variant=Variants.IM, +) -> ProcessTree: + if parameters is None: + parameters = {} + ack = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + tk = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY + ) + cidk = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, pmutil.constants.CASE_CONCEPT_NAME + ) + + process_tree = ProcessTree() + if type(obj) is DFG: + if variant is not Variants.IMd: + if constants.SHOW_INTERNAL_WARNINGS: + warnings.warn( + "Inductive Miner Variant requested for DFG artefact is not IMD, resorting back to IMD" + ) + imd = IMD(parameters) + idfg = InductiveDFG(dfg=obj, skip=False) + process_tree = imd.apply(IMDataStructureDFG(idfg), parameters) + else: + if type(obj) in [UVCL]: + uvcl = obj + else: + uvcl = comut.get_variants( + comut.project_univariate( + obj, key=ack, df_glue=cidk, df_sorting_criterion_key=tk + ) + ) + + if variant is Variants.IM: + im = IMUVCL(parameters) + process_tree = im.apply(IMDataStructureUVCL(uvcl), parameters) + if variant is Variants.IMf: + imf = IMFUVCL(parameters) + process_tree = imf.apply(IMDataStructureUVCL(uvcl), parameters) + if variant is Variants.IMd: + imd = IMD(parameters) + idfg = InductiveDFG( + dfg=comut.discover_dfg_uvcl(uvcl), skip=() in uvcl + ) + process_tree = imd.apply(IMDataStructureDFG(idfg), parameters) + + process_tree = pt_util.fold(process_tree) + tree_sort(process_tree) + + return process_tree diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ab0f9cc1f63cabe718dc2bd9c5f8f2d6623fdad1 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/__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.algo.discovery.inductive.base_case import ( + abc, + empty_log, + factory, + single_activity, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..de5668bae793ded5863cf414a149f966c9d1b20c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/abc.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 +''' +from abc import ABC, abstractmethod +from typing import Union, TypeVar, Generic, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructure +from pm4py.objects.process_tree.obj import ProcessTree + +T = TypeVar("T", bound=Union[IMDataStructure]) + + +class BaseCase(ABC, Generic[T]): + + @classmethod + def apply( + cls, obj=T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[ProcessTree]: + return ( + cls.leaf(obj, parameters) if cls.holds(obj, parameters) else None + ) + + @classmethod + @abstractmethod + def holds(cls, obj=T, parameters: Optional[Dict[str, Any]] = None) -> bool: + pass + + @classmethod + @abstractmethod + def leaf( + cls, obj=T, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/empty_log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/empty_log.py new file mode 100644 index 0000000000000000000000000000000000000000..deacafa42fe9cd1d011b01e60fedf4c505c2922b --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/empty_log.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 +''' +from abc import ABC +from typing import Generic, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.base_case.abc import BaseCase, T +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.objects.process_tree.obj import ProcessTree + + +class EmptyLogBaseCase(BaseCase[T], ABC, Generic[T]): + + @classmethod + def leaf( + cls, obj=T, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + return ProcessTree() + + +class EmptyLogBaseCaseUVCL(EmptyLogBaseCase[IMDataStructureUVCL]): + + @classmethod + def holds( + cls, + obj=IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return len(obj.data_structure) == 0 + + +class EmptyLogBaseCaseDFG(EmptyLogBaseCase[IMDataStructureDFG]): + + @classmethod + def holds( + cls, + obj=IMDataStructureDFG, + parameters: Optional[Dict[str, Any]] = None, + ): + dfg = obj.dfg + return ( + len(dfg.graph) == 0 + and len(dfg.start_activities) == 0 + and len(dfg.end_activities) == 0 + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..af194fc40ae0c724b43883c58e66b13bb25daa71 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/factory.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 typing import List, TypeVar, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.base_case.abc import BaseCase +from pm4py.algo.discovery.inductive.base_case.empty_log import ( + EmptyLogBaseCaseUVCL, + EmptyLogBaseCaseDFG, +) +from pm4py.algo.discovery.inductive.base_case.single_activity import ( + SingleActivityBaseCaseUVCL, + SingleActivityBaseCaseDFG, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructure, + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.process_tree.obj import ProcessTree + +T = TypeVar("T", bound=IMDataStructure) +S = TypeVar("S", bound=BaseCase) + + +class BaseCaseFactory: + + @classmethod + def get_base_cases( + cls, + obj: T, + inst: IMInstance, + parameters: Optional[Dict[str, Any]] = None, + ) -> List[S]: + if inst is IMInstance.IM or inst is IMInstance.IMf: + if type(obj) is IMDataStructureUVCL: + return [EmptyLogBaseCaseUVCL, SingleActivityBaseCaseUVCL] + if inst is IMInstance.IMd: + if type(obj) is IMDataStructureDFG: + return [EmptyLogBaseCaseDFG, SingleActivityBaseCaseDFG] + return [] + + @classmethod + def apply_base_cases( + cls, + obj: T, + inst: IMInstance, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[ProcessTree]: + for b in BaseCaseFactory.get_base_cases(obj, inst): + r = b.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/single_activity.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/single_activity.py new file mode 100644 index 0000000000000000000000000000000000000000..e1323c108b7e8f2a35cde4051ab69fe4bc351f9b --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/base_case/single_activity.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.algo.discovery.inductive.base_case.abc import BaseCase +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.objects.process_tree.obj import ProcessTree, Operator +from typing import Optional, Dict, Any + + +class SingleActivityBaseCaseUVCL(BaseCase[IMDataStructureUVCL]): + @classmethod + def holds( + cls, + obj=IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + if len(obj.data_structure.keys()) != 1: + return False + if len(list(obj.data_structure.keys())[0]) > 1: + return False + return True + + @classmethod + def leaf( + cls, + obj=IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> ProcessTree: + for t in obj.data_structure: + if t: + return ProcessTree(label=t[0]) + else: + return ProcessTree() + + +class SingleActivityBaseCaseDFG(BaseCase[IMDataStructureDFG]): + + @classmethod + def holds( + cls, + obj=IMDataStructureDFG, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return ( + len(obj.dfg.graph) == 0 + and len( + set(obj.dfg.start_activities).union(obj.dfg.end_activities) + ) + == 1 + ) + + @classmethod + def leaf( + cls, + obj=IMDataStructureDFG, + parameters: Optional[Dict[str, Any]] = None, + ) -> ProcessTree: + leaf = ProcessTree(label=list(obj.dfg.start_activities)[0]) + return leaf diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..51f4bd264880ed0f6d8690781cd8a91fd75b2e2f --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/__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.algo.discovery.inductive.cuts import ( + sequence, + xor, + concurrency, + loop, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..a70fc31f0c15afce1608d5264bda0302e4e5764a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/abc.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 abc import ABC, abstractmethod +from typing import ( + Optional, + List, + Collection, + Any, + Tuple, + Generic, + TypeVar, + Dict, +) + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructure +from pm4py.objects.process_tree.obj import ProcessTree + +T = TypeVar("T", bound=IMDataStructure) + + +class Cut(ABC, Generic[T]): + + @classmethod + @abstractmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + pass + + @classmethod + @abstractmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + pass + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[ProcessTree, List[T]]]: + g = cls.holds(obj, parameters) + return ( + (cls.operator(), cls.project(obj, g, parameters)) + if g is not None + else g + ) + + @classmethod + @abstractmethod + def project( + cls, + obj: T, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[T]: + """ + Projection of the given data object (Generic type T). + Returns a corresponding process tree and the projected sub logs according to the identified groups. + A precondition of the project function is that it holds on the object for the given Object + """ + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/concurrency.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..6883fa3765e23f7cdc0b123cdb6fdf691ce8613b --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/concurrency.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 abc import ABC +from collections import Counter +from typing import List, Collection, Any, Optional, Generic, Dict + +from pm4py.algo.discovery.inductive.cuts.abc import Cut, T +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.objects.dfg import util as dfu +from pm4py.objects.dfg.obj import DFG +from pm4py.objects.process_tree.obj import Operator, ProcessTree + + +class ConcurrencyCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + return ProcessTree(operator=Operator.PARALLEL) + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + dfg = obj.dfg + alphabet = dfu.get_vertices(dfg) + alphabet = sorted(list(alphabet)) + edges = dfu.get_edges(dfg) + edges = sorted(list(edges)) + + groups = [{a} for a in alphabet] + if len(groups) == 0: + return None + + cont = True + while cont: + cont = False + i = 0 + while i < len(groups): + j = i + 1 + while j < len(groups): + for act1 in groups[i]: + for act2 in groups[j]: + if (act1, act2) not in edges or ( + act2, + act1, + ) not in edges: + groups[i] = groups[i].union(groups[j]) + del groups[j] + cont = True + break + if cont: + break + if cont: + break + j = j + 1 + if cont: + break + i = i + 1 + + groups = list(sorted(groups, key=lambda g: len(g))) + i = 0 + while i < len(groups) and len(groups) > 1: + if ( + len(groups[i].intersection(set(dfg.start_activities.keys()))) + > 0 + and len(groups[i].intersection(set(dfg.end_activities.keys()))) + > 0 + ): + i += 1 + continue + group = groups[i] + del groups[i] + if i == 0: + groups[i].update(group) + else: + groups[i - 1].update(group) + + return groups if len(groups) > 1 else None + + +class ConcurrencyCutUVCL(ConcurrencyCut[IMDataStructureUVCL]): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + r = list() + for g in groups: + c = Counter() + for t in obj.data_structure: + c[tuple(filter(lambda e: e in g, t))] += obj.data_structure[t] + r.append(c) + return list(map(lambda l: IMDataStructureUVCL(l), r)) + + +class ConcurrencyCutDFG(ConcurrencyCut[IMDataStructureDFG]): + + @classmethod + def project( + cls, + obj: IMDataStructureDFG, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureDFG]: + dfgs = [] + skippable = [] + for g in groups: + dfn = DFG() + for a in obj.dfg.start_activities: + if a in g: + dfn.start_activities[a] = obj.dfg.start_activities[a] + for a in obj.dfg.end_activities: + if a in g: + dfn.end_activities[a] = obj.dfg.end_activities[a] + for a, b in obj.dfg.graph: + if a in g and b in g: + dfn.graph[(a, b)] = obj.dfg.graph[(a, b)] + skippable.append(False) + dfgs.append(dfn) + r = list() + [ + r.append( + IMDataStructureDFG( + InductiveDFG(dfg=dfgs[i], skip=skippable[i]) + ) + ) + for i in range(len(dfgs)) + ] + return r diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..9c802e883097e4cb6709f53f8e203cf8d9e678b7 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/factory.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 typing import List, Optional, Tuple, TypeVar, Dict, Any + +from pm4py.algo.discovery.inductive.cuts.abc import Cut +from pm4py.algo.discovery.inductive.cuts.concurrency import ( + ConcurrencyCutUVCL, + ConcurrencyCutDFG, +) +from pm4py.algo.discovery.inductive.cuts.loop import LoopCutUVCL, LoopCutDFG +from pm4py.algo.discovery.inductive.cuts.sequence import ( + StrictSequenceCutUVCL, + StrictSequenceCutDFG, + SequenceCutUVCL, + SequenceCutDFG, +) +from pm4py.algo.discovery.inductive.cuts.xor import ( + ExclusiveChoiceCutUVCL, + ExclusiveChoiceCutDFG, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructure, + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.process_tree.obj import ProcessTree +from pm4py.util import exec_utils +from enum import Enum + + +T = TypeVar("T", bound=IMDataStructure) +S = TypeVar("S", bound=Cut) + + +class Parameters(Enum): + DISABLE_STRICT_SEQUENCE_CUT = "disable_strict_sequence_cut" + + +class CutFactory: + + @classmethod + def get_cuts( + cls, + obj: T, + inst: IMInstance, + parameters: Optional[Dict[str, Any]] = None, + ) -> List[S]: + if parameters is None: + parameters = {} + + disable_strict_sequence_cut = exec_utils.get_param_value( + Parameters.DISABLE_STRICT_SEQUENCE_CUT, parameters, False + ) + + if inst is IMInstance.IM or inst is IMInstance.IMf: + if type(obj) is IMDataStructureUVCL: + sequence_cut = StrictSequenceCutUVCL + if disable_strict_sequence_cut: + sequence_cut = SequenceCutUVCL + return [ + ExclusiveChoiceCutUVCL, + sequence_cut, + ConcurrencyCutUVCL, + LoopCutUVCL, + ] + if inst is IMInstance.IMd: + if type(obj) is IMDataStructureDFG: + sequence_cut = StrictSequenceCutDFG + if disable_strict_sequence_cut: + sequence_cut = SequenceCutDFG + return [ + ExclusiveChoiceCutDFG, + sequence_cut, + ConcurrencyCutDFG, + LoopCutDFG, + ] + return list() + + @classmethod + def find_cut( + cls, + obj: IMDataStructure, + inst: IMInstance, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[T]]]: + for c in CutFactory.get_cuts(obj, inst, parameters): + r = c.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/loop.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/loop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d4bf907c42a17e184a98e5fa4185cc8cdc05271 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/loop.py @@ -0,0 +1,346 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +from abc import ABC +from collections import Counter +from typing import List, Optional, Collection, Any, Tuple, Generic, Dict + +from pm4py.util import nx_utils + +from pm4py.algo.discovery.inductive.cuts.abc import Cut, T +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.objects.dfg import util as dfu +from pm4py.objects.dfg.obj import DFG +from pm4py.objects.process_tree.obj import Operator, ProcessTree +from pm4py.util.compression.dtypes import UVCL + + +class LoopCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + return ProcessTree(operator=Operator.LOOP) + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + """ + Finds a loop cut in the DFG and returns exactly two groups: + - groups[0]: the 'do' group (start ∪ end activities plus merged components as per checks) + - groups[1]: a single 'redo' group obtained by merging all remaining non-empty groups + + If no non-empty redo part remains, returns None. + """ + dfg = obj.dfg + start_activities = set(dfg.start_activities.keys()) + end_activities = set(dfg.end_activities.keys()) + if len(dfg.graph) == 0: + return None + + # Initial groups: do-part is start ∪ end; other parts are connected components after removing boundaries + groups = [start_activities.union(end_activities)] + for c in cls._compute_connected_components(dfg, start_activities, end_activities): + groups.append(set(c.nodes)) + + # Apply the original reachability/completeness checks + groups = cls._exclude_sets_non_reachable_from_start(dfg, start_activities, end_activities, groups) + groups = cls._exclude_sets_no_reachable_from_end(dfg, start_activities, end_activities, groups) + groups = cls._check_start_completeness(dfg, start_activities, end_activities, groups) + groups = cls._check_end_completeness(dfg, start_activities, end_activities, groups) + + # Keep only non-empty groups + groups = [set(g) for g in groups if len(g) > 0] + + # Require at least a do group and something to redo + if len(groups) <= 1: + return None + + # Merge all remaining non-empty groups (from the second to the last) into a single redo group + redo_merged = set() + for g in groups[1:]: + redo_merged.update(g) + + return [set(groups[0]), redo_merged] + + @classmethod + def _check_start_completeness( + cls, + dfg: DFG, + start_activities: Collection[Any], + end_activities: Collection[Any], + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[Collection[Any]]: + i = 1 + while i < len(groups): + merge = False + for a in groups[i]: + if merge: + break + for x, b in dfg.graph: + if x == a and b in start_activities: + for s in start_activities: + if (a, s) not in dfg.graph: + merge = True + if merge: + groups[0] = set(groups[0]).union(groups[i]) + del groups[i] + continue + i = i + 1 + return groups + + @classmethod + def _check_end_completeness( + cls, + dfg: DFG, + start_activities: Collection[Any], + end_activities: Collection[Any], + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[Collection[Any]]: + i = 1 + while i < len(groups): + merge = False + for a in groups[i]: + if merge: + break + for b, x in dfg.graph: + if x == a and b in end_activities: + for e in end_activities: + if (e, a) not in dfg.graph: + merge = True + if merge: + groups[0] = set(groups[0]).union(groups[i]) + del groups[i] + continue + i = i + 1 + return groups + + @classmethod + def _exclude_sets_non_reachable_from_start( + cls, + dfg: DFG, + start_activities: Collection[Any], + end_activities: Collection[Any], + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[Collection[Any]]: + for a in set(start_activities).difference(set(end_activities)): + for x, b in dfg.graph: + if x == a: + group_a, group_b = None, None + for group in groups: + group_a = group if a in group else group_a + group_b = group if b in group else group_b + groups = [ + group + for group in groups + if group != group_a and group != group_b + ] + # we are always merging on the do-part + groups.insert(0, group_a.union(group_b)) + return groups + + @classmethod + def _exclude_sets_no_reachable_from_end( + cls, + dfg: DFG, + start_activities: Collection[Any], + end_activities: Collection[Any], + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[Collection[Any]]: + for b in set(end_activities).difference(start_activities): + for a, x in dfg.graph: + if x == b: + group_a, group_b = None, None + for group in groups: + group_a = group if a in group else group_a + group_b = group if b in group else group_b + groups = [ + group + for group in groups + if group != group_a and group != group_b + ] + groups.insert(0, group_a.union(group_b)) + return groups + + @classmethod + def _compute_connected_components( + cls, + dfg: DFG, + start_activities: Collection[Any], + end_activities: Collection[Any], + parameters: Optional[Dict[str, Any]] = None, + ): + nxd = dfu.as_nx_graph(dfg) + [ + nxd.remove_edge(a, b) + for (a, b) in dfg.graph + if a in start_activities + or a in end_activities + or b in start_activities + or b in end_activities + ] + [nxd.remove_node(a) for a in start_activities if nxd.has_node(a)] + [nxd.remove_node(a) for a in end_activities if nxd.has_node(a)] + nxu = nxd.to_undirected() + return [ + nxd.subgraph(c).copy() for c in nx_utils.connected_components(nxu) + ] + + +class LoopCutUVCL(LoopCut[IMDataStructureUVCL]): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + """ + Split the (compressed) log into one 'do' log and N 'redo' logs. + Traces are segmented into do/redo slices; redo slices are routed to the + redo log whose activity set overlaps most with the slice. + """ + do = set(groups[0]) + redo_groups = [set(g) for g in groups[1:]] + + # For quick membership checks + redo_activities = set().union(*redo_groups) if redo_groups else set() + + do_log = Counter() + redo_logs = [Counter() for _ in redo_groups] + + for t, card in obj.data_structure.items(): + do_trace: Tuple[Any, ...] = tuple() + redo_trace: Tuple[Any, ...] = tuple() + + for e in t: + if e in do: + do_trace += (e,) + # flush redo if we were inside a redo slice + if redo_trace: + redo_logs = cls._append_trace_to_redo_log( + redo_trace, redo_logs, redo_groups, card + ) + redo_trace = tuple() + elif e in redo_activities: + redo_trace += (e,) + # flush do if we were inside a do slice + if do_trace: + do_log.update({do_trace: card}) + do_trace = tuple() + else: + # Safety: if an event is in neither do nor any redo group, + # flush any current slice and ignore the event + if do_trace: + do_log.update({do_trace: card}) + do_trace = tuple() + if redo_trace: + redo_logs = cls._append_trace_to_redo_log( + redo_trace, redo_logs, redo_groups, card + ) + redo_trace = tuple() + + # Flush tail slices + if redo_trace: + redo_logs = cls._append_trace_to_redo_log( + redo_trace, redo_logs, redo_groups, card + ) + do_log.update({do_trace: card}) # keep empty do slices, consistent with original + + logs = [do_log] + redo_logs + return [IMDataStructureUVCL(l) for l in logs] + + @classmethod + def _append_trace_to_redo_log( + cls, + redo_trace: Tuple[Any, ...], + redo_logs: List[UVCL], + redo_groups: List[Collection[Any]], + cardinality: int, + parameters: Optional[Dict[str, Any]] = None, + ) -> List[UVCL]: + """ + Append a redo slice to the best matching redo log (largest activity overlap). + """ + if not redo_logs: + return redo_logs + + activities = set(redo_trace) + overlaps = [ + (i, len(activities.intersection(set(redo_groups[i])))) + for i in range(len(redo_groups)) + ] + overlaps.sort(key=lambda x: (x[1], x[0]), reverse=True) + target = overlaps[0][0] + redo_logs[target].update({redo_trace: cardinality}) + return redo_logs + + +class LoopCutDFG(LoopCut[IMDataStructureDFG]): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureDFG]: + dfg = obj.dfg + dfgs = [] + skippable = [False, False] + for gind, g in enumerate(groups): + dfn = DFG() + for a, b in dfg.graph: + if a in g and b in g: + dfn.graph[(a, b)] = dfg.graph[(a, b)] + if b in dfg.start_activities and a in dfg.end_activities: + skippable[1] = True + if gind == 0: + for a in dfg.start_activities: + if a in g: + dfn.start_activities[a] = dfg.start_activities[a] + else: + skippable[0] = True + for a in dfg.end_activities: + if a in g: + dfn.end_activities[a] = dfg.end_activities[a] + else: + skippable[0] = True + elif gind == 1: + for a in g: + dfn.start_activities[a] = 1 + dfn.end_activities[a] = 1 + dfgs.append(dfn) + return [ + IMDataStructureDFG(InductiveDFG(dfg=dfgs[i], skip=skippable[i])) + for i in range(len(dfgs)) + ] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/sequence.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..5d0b01fb88a3d18b21c3d4ad2f4bd548364153d4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/sequence.py @@ -0,0 +1,384 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 itertools +import sys +from abc import ABC +from collections import Counter +from typing import Collection, Any, List, Optional, Generic, Dict +from typing import Tuple + +from pm4py.algo.discovery.inductive.cuts.abc import Cut +from pm4py.algo.discovery.inductive.cuts.abc import T +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.objects.dfg import util as dfu +from pm4py.objects.dfg.obj import DFG +from pm4py.objects.process_tree.obj import Operator, ProcessTree + + +class SequenceCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + return ProcessTree(operator=Operator.SEQUENCE) + + @staticmethod + def check_merge_condition(g1, g2, trans_succ): + for a1 in g1: + for a2 in g2: + if (a2 in trans_succ[a1] and a1 in trans_succ[a2]) or ( + a2 not in trans_succ[a1] and a1 not in trans_succ[a2] + ): + return True + return False + + @staticmethod + def merge_groups(groups, trans_succ): + i = 0 + while i < len(groups): + j = i + 1 + while j < len(groups): + if SequenceCut.check_merge_condition( + groups[i], groups[j], trans_succ + ): + groups[i] = groups[i].union(groups[j]) + del groups[j] + continue + j = j + 1 + i = i + 1 + return groups + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + """ + This method finds a sequence cut in the dfg. + Implementation follows function sequence on page 188 of + "Robust Process Mining with Guarantees" by Sander J.J. Leemans (ISBN: 978-90-386-4257-4) + + Basic Steps: + 1. create a group per activity + 2. merge pairwise reachable nodes (based on transitive relations) + 3. merge pairwise unreachable nodes (based on transitive relations) + 4. sort the groups based on their reachability + """ + dfg = obj.dfg + alphabet = dfu.get_vertices(dfg) + transitive_predecessors, transitive_successors = ( + dfu.get_transitive_relations(dfg) + ) + groups = [{a} for a in alphabet] + if len(groups) == 0: + return None + + old_size = None + while old_size != len(groups): + old_size = len(groups) + groups = SequenceCut.merge_groups(groups, transitive_successors) + + groups = list( + sorted( + groups, + key=lambda g: len(transitive_predecessors[next(iter(g))]) + + (len(alphabet) - len(transitive_successors[next(iter(g))])), + ) + ) + + return groups if len(groups) > 1 else None + + +class StrictSequenceCut(SequenceCut[T], ABC, Generic[T]): + + @classmethod + def _skippable( + cls, + p: int, + dfg: DFG, + start: Collection[Any], + end: Collection[Any], + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + """ + This method implements the function SKIPPABLE as defined on page 233 of + "Robust Process Mining with Guarantees" by Sander J.J. Leemans (ISBN: 978-90-386-4257-4) + The function is used as a helper function for the strict sequence cut detection mechanism, which detects + larger groups of skippable activities. + """ + for i, j in itertools.product(range(0, p), range(p + 1, len(groups))): + for a, b in itertools.product(groups[i], groups[j]): + if (a, b) in dfg.graph: + return True + for i in range(p + 1, len(groups)): + for a in groups[i]: + if a in start: + return True + for i in range(0, p): + for a in groups[i]: + if a in end: + return True + return False + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + """ + This method implements the strict sequence cut as defined on page 233 of + "Robust Process Mining with Guarantees" by Sander J.J. Leemans (ISBN: 978-90-386-4257-4) + The function merges groups that together can be skipped. + """ + dfg = obj.dfg + c = SequenceCut.holds(obj) + start = set(dfg.start_activities.keys()) + end = set(dfg.end_activities.keys()) + if c is not None: + mf = [ + ( + -1 * sys.maxsize + if len(set(G).intersection(start)) > 0 + else sys.maxsize + ) + for G in c + ] + mt = [ + ( + sys.maxsize + if len(set(G).intersection(end)) > 0 + else -1 * sys.maxsize + ) + for G in c + ] + cmap = cls._construct_alphabet_cluster_map(c) + for a, b in dfg.graph: + mf[cmap[b]] = min(mf[cmap[b]], cmap[a]) + mt[cmap[a]] = max(mt[cmap[a]], cmap[b]) + + for p in range(0, len(c)): + if cls._skippable(p, dfg, start, end, c): + q = p - 1 + while q >= 0 and mt[q] <= p: + c[p] = c[p].union(c[q]) + c[q] = set() + q -= 1 + q = p + 1 + while q < len(mf) and mf[q] >= p: + c[p] = c[p].union(c[q]) + c[q] = set() + q += 1 + return list(filter(lambda g: len(g) > 0, c)) + return None + + @classmethod + def _construct_alphabet_cluster_map( + cls, + c: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ): + map = dict() + for i in range(0, len(c)): + for a in c[i]: + map[a] = i + return map + + +class SequenceCutUVCL(SequenceCut[IMDataStructureUVCL]): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + logs = [Counter() for g in groups] + for t in obj.data_structure: + i = 0 + split_point = 0 + act_union = set() + while i < len(groups): + new_split_point = cls._find_split_point( + t, groups[i], split_point, act_union + ) + trace_i = tuple() + j = split_point + while j < new_split_point: + if t[j] in groups[i]: + trace_i = trace_i + (t[j],) + j = j + 1 + logs[i].update({trace_i: obj.data_structure[t]}) + split_point = new_split_point + act_union = act_union.union(set(groups[i])) + i = i + 1 + return list(map(lambda l: IMDataStructureUVCL(l), logs)) + + @classmethod + def _find_split_point( + cls, + t: Tuple[Any], + group: Collection[Any], + start: int, + ignore: Collection[Any], + parameters: Optional[Dict[str, Any]] = None, + ) -> int: + least_cost = 0 + position_with_least_cost = start + cost = 0 + i = start + while i < len(t): + if t[i] in group: + cost = cost - 1 + elif t[i] not in ignore: + cost = cost + 1 + + if cost < least_cost: + least_cost = cost + position_with_least_cost = i + 1 + + i = i + 1 + + return position_with_least_cost + + +class StrictSequenceCutUVCL( + StrictSequenceCut[IMDataStructureUVCL], SequenceCutUVCL +): + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + return StrictSequenceCut.holds(obj, parameters) + + +class SequenceCutDFG(SequenceCut[IMDataStructureDFG]): + + @classmethod + def project( + cls, + obj: IMDataStructureDFG, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureDFG]: + dfg = obj.dfg + start_activities = [] + end_activities = [] + activities = [] + dfgs = [] + skippable = [] + for g in groups: + skippable.append(False) + activities_idx = {} + for gind, g in enumerate(groups): + for act in g: + activities_idx[act] = int(gind) + i = 0 + while i < len(groups): + to_succ_arcs = Counter() + from_prev_arcs = Counter() + if i < len(groups) - 1: + for a, b in dfg.graph: + if a in groups[i] and b in groups[i + 1]: + to_succ_arcs[a] += dfg.graph[(a, b)] + + if i > 0: + for a, b in dfg.graph: + if a in groups[i - 1] and b in groups[i]: + from_prev_arcs[b] += dfg.graph[(a, b)] + + if i == 0: + start_activities.append({}) + for a in dfg.start_activities: + if a in groups[i]: + start_activities[i][a] = dfg.start_activities[a] + else: + j = i + while j < activities_idx[a]: + skippable[j] = True + j = j + 1 + else: + start_activities.append(from_prev_arcs) + + if i == len(groups) - 1: + end_activities.append({}) + for a in dfg.end_activities: + if a in groups[i]: + end_activities[i][a] = dfg.end_activities[a] + else: + j = activities_idx[a] + 1 + while j <= i: + skippable[j] = True + j = j + 1 + else: + end_activities.append(to_succ_arcs) + + activities.append({}) + act_count = dfu.get_vertex_frequencies(dfg) + for a in groups[i]: + activities[i][a] = act_count[a] + dfgs.append({}) + for a, b in dfg.graph: + if a in groups[i] and b in groups[i]: + dfgs[i][(a, b)] = dfg.graph[(a, b)] + i = i + 1 + i = 0 + while i < len(dfgs): + dfi = DFG() + [dfi.graph.update({(a, b): dfgs[i][(a, b)]}) for (a, b) in dfgs[i]] + [ + dfi.start_activities.update({a: start_activities[i][a]}) + for a in start_activities[i] + ] + [ + dfi.end_activities.update({a: end_activities[i][a]}) + for a in end_activities[i] + ] + dfgs[i] = dfi + i = i + 1 + for a, b in dfg.graph: + z = activities_idx[b] + j = activities_idx[a] + 1 + while j < z: + skippable[j] = True + j = j + 1 + + return [ + IMDataStructureDFG(InductiveDFG(dfg=dfgs[i], skip=skippable[i])) + for i in range(len(dfgs)) + ] + + +class StrictSequenceCutDFG( + StrictSequenceCut[IMDataStructureDFG], SequenceCutDFG +): + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + return StrictSequenceCut.holds(obj, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a74a34cff6260611395359780d39fc718beaffd6 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/utils.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 +''' +def merge_groups_based_on_activities(a, b, groups): + group_a = None + group_b = None + for group in groups: + if a in group: + group_a = group + if b in group: + group_b = group + groups = [ + group for group in groups if group != group_a and group != group_b + ] + groups.append(group_a.union(group_b)) + return groups + + +def merge_lists_based_on_activities(a, b, groups): + group_a = [] + group_b = [] + for group in groups: + if a in group: + group_a = group + if b in group: + group_b = group + if group_a is group_b: + return groups + groups = [ + group for group in groups if group != group_a and group != group_b + ] + groups.append(group_a + group_b) + return groups diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/xor.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/xor.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e351e14b5cb5612f2f1ca6cce689b2c101cb93 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/cuts/xor.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 abc import ABC +from collections import Counter +from typing import Optional, List, Collection, Any, Generic, Dict + +from pm4py.util import nx_utils + +from pm4py.algo.discovery.inductive.cuts.abc import Cut, T +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.objects.dfg import util as dfu +from pm4py.objects.dfg.obj import DFG +from pm4py.objects.process_tree.obj import Operator, ProcessTree + + +class ExclusiveChoiceCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + return ProcessTree(operator=Operator.XOR) + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[List[Collection[Any]]]: + """ + This method finds a xor cut in the dfg. + Implementation follows function XorCut on page 188 of + "Robust Process Mining with Guarantees" by Sander J.J. Leemans (ISBN: 978-90-386-4257-4) + + Basic Steps: + 1.) the dfg is transformed to its undirected equivalent. + 2.) we detect the connected components in the graph. + 3.) if there are more than one connected components, the cut exists and is non-minimal. + """ + nx_dfg = dfu.as_nx_graph(obj.dfg) + nx_und = nx_dfg.to_undirected() + conn_comps = [ + nx_und.subgraph(c).copy() + for c in nx_utils.connected_components(nx_und) + ] + if len(conn_comps) > 1: + cuts = list() + for comp in conn_comps: + cuts.append(set(comp.nodes)) + # Projection breaks tied event counts by group index, so keep the + # group order independent of graph traversal and Python's hash seed. + return sorted(cuts, key=lambda group: sorted(map(str, group))) + else: + return None + + +class ExclusiveChoiceCutUVCL(ExclusiveChoiceCut[IMDataStructureUVCL]): + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + logs = [Counter() for g in groups] + for t in obj.data_structure: + count = {i: 0 for i in range(len(groups))} + for index, group in enumerate(groups): + for e in t: + if e in group: + count[index] += 1 + count = sorted( + list((x, y) for x, y in count.items()), + key=lambda x: (x[1], x[0]), + reverse=True, + ) + new_trace = tuple() + for e in t: + if e in groups[count[0][0]]: + new_trace = new_trace + (e,) + logs[count[0][0]].update({new_trace: obj.data_structure[t]}) + return list(map(lambda l: IMDataStructureUVCL(l), logs)) + + +class ExclusiveChoiceCutDFG(ExclusiveChoiceCut[IMDataStructureDFG]): + + @classmethod + def project( + cls, + obj: IMDataStructureDFG, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureDFG]: + dfg = obj.dfg + dfgs = [] + for g in groups: + dfg_new = DFG() + for a in dfg.start_activities: + if a in g: + dfg_new.start_activities[a] = dfg.start_activities[a] + for a in dfg.end_activities: + if a in g: + dfg_new.end_activities[a] = dfg.end_activities[a] + for a, b in dfg.graph: + if a in g and b in g: + dfg_new.graph[(a, b)] = dfg.graph[(a, b)] + dfgs.append(dfg_new) + return list( + map( + lambda d: IMDataStructureDFG(InductiveDFG(dfg=d, skip=False)), + dfgs, + ) + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f6141a3c84c60a34a6339c840ca3c89c331e21 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/__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.discovery.inductive.dtypes import im_ds, im_dfg diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/im_dfg.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/im_dfg.py new file mode 100644 index 0000000000000000000000000000000000000000..494353b33830ebb165c62bef190cbd0005dd36cc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/im_dfg.py @@ -0,0 +1,37 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.obj import DFG + + +class InductiveDFG: + + def __init__(self, dfg: DFG, skip: bool = False): + self._dfg = dfg + self._skip = skip + + @property + def dfg(self) -> DFG: + return self._dfg + + @property + def skip(self) -> bool: + return self._skip diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/im_ds.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/im_ds.py new file mode 100644 index 0000000000000000000000000000000000000000..829d73961febd10034a5b6acd8172c3740afbbdc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/dtypes/im_ds.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 abc import ABC +from typing import TypeVar, Generic, Optional + +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG +from pm4py.objects.dfg.obj import DFG +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL + +T = TypeVar("T") + + +class IMDataStructure(ABC, Generic[T]): + """ + The IMDataStructure is a helper class that unifies all possible data structures (typically logs or dfgs) that can + be used for the classical Inductive Miner. The generic TypeVar 'T' is supposed to be the underlying data object + used, and, should always be able to construct a DFG object. For example, T can be a dataframe, some other + object representing an event log or a DFG itself. + """ + + def __init__(self, obj: T): + self._obj = obj + + @property + def dfg(self) -> DFG: + pass + + @property + def data_structure(self) -> T: + return self._obj + + +class IMDataStructureLog(IMDataStructure[T], ABC, Generic[T]): + """ + Generic class intended to represent that any subclass carries information that is captured in an event log. + """ + + +class IMDataStructureUVCL(IMDataStructureLog[UVCL]): + """ + Log-Based data structure class that represents the event log as a 'Univariate Variant Compressed Log (UVCL)' + """ + + def __init__(self, obj: UVCL, dfg: Optional[DFG] = None): + super().__init__(obj) + if dfg is None: + self._dfg = comut.discover_dfg_uvcl(self._obj) + else: + self._dfg = dfg + + @property + def dfg(self) -> DFG: + return self._dfg + + +class IMDataStructureDFG(IMDataStructure[InductiveDFG]): + """ + DFG-Based data structure class + """ + + @property + def dfg(self) -> DFG: + return self._obj.dfg diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9f0a4d5fafa2186ba71c03ca80ae4a544760b3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/__init__.py @@ -0,0 +1,30 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.inductive.fall_through import ( + abc, + activity_concurrent, + activity_once_per_trace, + empty_traces, + flower, + strict_tau_loop, + tau_loop, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..56ef9d03efaaf7330c6b1ff4f5cbcf3cf635fb09 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/abc.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 abc import ABC, abstractmethod +from typing import Generic, TypeVar, Tuple, List, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructure +from pm4py.objects.process_tree.obj import ProcessTree + +T = TypeVar("T", bound=IMDataStructure) + + +class FallThrough(ABC, Generic[T]): + + @classmethod + @abstractmethod + def holds(cls, t: T, parameters: Optional[Dict[str, Any]] = None) -> bool: + pass + + @classmethod + @abstractmethod + def apply( + cls, + t: T, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[T]]]: + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/activity_concurrent.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/activity_concurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7a9616d71eae77682a9b43dcbaaf7928c3ce66 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/activity_concurrent.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 collections import Counter +from typing import Optional, Tuple, List, Any, Dict + +from pm4py.algo.discovery.inductive.cuts.factory import CutFactory +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.inductive.fall_through.abc import FallThrough +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.process_tree.obj import ProcessTree, Operator +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL +from enum import Enum +from pm4py.util import exec_utils, constants + + +class Parameters(Enum): + MULTIPROCESSING = "multiprocessing" + + +class ActivityConcurrentUVCL(FallThrough[IMDataStructureUVCL]): + MULTI_PROCESSING_LOWER_BOUND = 20 + + @classmethod + def _process_candidate( + cls, + c: Any, + log: UVCL, + queue=None, + ev=None, + parameters: Optional[Dict[str, Any]] = None, + ): + l_alt = Counter() + for t in log: + l_alt[tuple(filter(lambda e: e != c, t))] = log[t] + cut = cls._find_cut( + IMDataStructureUVCL(l_alt), ev, parameters=parameters + ) + if queue is not None: + queue.put((c, cut)) + return cut if cut is not None else None + + @classmethod + def _get_candidate( + cls, + obj: IMDataStructureUVCL, + pool, + manager, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Any]: + if parameters is None: + parameters = {} + + enable_multiprocessing = exec_utils.get_param_value( + Parameters.MULTIPROCESSING, + parameters, + constants.ENABLE_MULTIPROCESSING_DEFAULT, + ) + + log = obj.data_structure + candidates = sorted(list(comut.get_alphabet(log))) + if ( + pool is None + or manager is None + or not enable_multiprocessing + or len(candidates) + <= ActivityConcurrentUVCL.MULTI_PROCESSING_LOWER_BOUND + ): + for a in candidates: + cut = cls._process_candidate(a, log, parameters=parameters) + if cut is not None: + return a + else: + q = manager.Queue() + ev = manager.Event() + # avoid dangerous freealloc from Python's garbage collector + manager.support_list.append(q) + manager.support_list.append(ev) + + for a in candidates: + pool.apply_async( + cls._process_candidate, (a, log, q, ev, parameters) + ) + potentials = set(candidates) + while len(potentials) > 0: + (c, cut) = q.get(block=True) + if cut is None: + potentials.remove(c) + else: + ev.set() + return c + + return None + + @classmethod + def _find_cut( + cls, + obj: IMDataStructureUVCL, + ev, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[IMDataStructureUVCL]]]: + for c in CutFactory.get_cuts( + obj, IMInstance.IM, parameters=parameters + ): + if ev is not None and ev.is_set(): + return None + r = c.apply(obj, parameters) + if r is not None: + return r + return None + + @classmethod + def holds( + cls, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return cls._get_candidate(obj, None, None, parameters) is not None + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[IMDataStructureUVCL]]]: + candidate = cls._get_candidate(obj, pool, manager, parameters) + if candidate is None: + return None + log = obj.data_structure + l_a = Counter() + l_other = Counter() + for t in log: + l_a.update({tuple(filter(lambda e: e == candidate, t)): log[t]}) + l_other.update( + {tuple(filter(lambda e: e != candidate, t)): log[t]} + ) + return ProcessTree(operator=Operator.PARALLEL), [ + IMDataStructureUVCL(l_a), + IMDataStructureUVCL(l_other), + ] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/activity_once_per_trace.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/activity_once_per_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..92e7cac063c82c7a2df95a5034a7372dfc909aa0 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/activity_once_per_trace.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 collections import Counter +from typing import Any, Optional, Dict +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.inductive.fall_through.activity_concurrent import ( + ActivityConcurrentUVCL, +) +from pm4py.util.compression import util as comut + + +class ActivityOncePerTraceUVCL(ActivityConcurrentUVCL): + @classmethod + def _get_candidate( + cls, + obj: IMDataStructureUVCL, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Any]: + # Initialize candidates as a set of all activities + candidates = set(comut.get_alphabet(obj.data_structure)) + + for t in obj.data_structure: + # Use a Counter to count occurrences of each activity in the trace + activity_counts = Counter(t) + # Create a set of activities that occur exactly once in the trace + activities_once = { + activity + for activity, count in activity_counts.items() + if count == 1 + } + # Intersect with the existing candidates + candidates &= activities_once + # Early exit if no candidates remain + if not candidates: + return None + + # Return any one of the remaining candidates + candidates = sorted(list(candidates)) + return candidates[0] if candidates else None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/empty_traces.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/empty_traces.py new file mode 100644 index 0000000000000000000000000000000000000000..ee33247b8529c9eab6a4b818cb244992c287689f --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/empty_traces.py @@ -0,0 +1,103 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, List, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.algo.discovery.inductive.fall_through.abc import FallThrough +from pm4py.objects.process_tree.obj import ProcessTree, Operator +from pm4py.objects.dfg.obj import DFG +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG +from copy import copy + + +class EmptyTracesUVCL(FallThrough[IMDataStructureUVCL]): + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[IMDataStructureUVCL]]]: + if cls.holds(obj, parameters): + data_structure = copy(obj.data_structure) + del data_structure[()] + if data_structure: + return ProcessTree(operator=Operator.XOR), [ + IMDataStructureUVCL(Counter()), + IMDataStructureUVCL(data_structure), + ] + else: + return ProcessTree(), [] + else: + return None + + @classmethod + def holds( + cls, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return len(list(filter(lambda t: len(t) == 0, obj.data_structure))) > 0 + + +class EmptyTracesDFG(FallThrough[IMDataStructureDFG]): + @classmethod + def apply( + cls, + obj: IMDataStructureDFG, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[IMDataStructureDFG]]]: + if cls.holds(obj, parameters): + # If the DFG itself is empty, the log contains only empty traces -> just τ + dfg = obj.data_structure.dfg + is_empty = ( + len(dfg.graph) == 0 + and len(dfg.start_activities) == 0 + and len(dfg.end_activities) == 0 + ) + + if is_empty: + return ProcessTree(), [] + # Otherwise, split: XOR(τ, non-empty part) + + return ProcessTree(operator=Operator.XOR), [ + IMDataStructureDFG(InductiveDFG(DFG())), + # note: skip intentionally False here; τ is already handled on the XOR + IMDataStructureDFG(InductiveDFG(obj.data_structure.dfg)), + ] + return None + + @classmethod + def holds( + cls, + obj: IMDataStructureDFG, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return obj.data_structure.skip diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..e6db3f0485920a515a132231f0fed77b652e0646 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/factory.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 typing import List, TypeVar, Tuple, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructure, + IMDataStructureUVCL, +) +from pm4py.algo.discovery.inductive.fall_through.abc import FallThrough +from pm4py.algo.discovery.inductive.fall_through.activity_concurrent import ( + ActivityConcurrentUVCL, +) +from pm4py.algo.discovery.inductive.fall_through.activity_once_per_trace import ( + ActivityOncePerTraceUVCL, ) +from pm4py.algo.discovery.inductive.fall_through.empty_traces import ( + EmptyTracesUVCL, + EmptyTracesDFG, +) +from pm4py.algo.discovery.inductive.fall_through.flower import ( + FlowerModelUVCL, + FlowerModelDFG, +) +from pm4py.algo.discovery.inductive.fall_through.strict_tau_loop import ( + StrictTauLoopUVCL, +) +from pm4py.algo.discovery.inductive.fall_through.tau_loop import TauLoopUVCL +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.process_tree.obj import ProcessTree +from pm4py.util import exec_utils +from enum import Enum + + +T = TypeVar("T", bound=IMDataStructure) +S = TypeVar("S", bound=FallThrough) + + +class Parameters(Enum): + DISABLE_FALLTHROUGHS = "disable_fallthroughs" + + +class FallThroughFactory: + + @classmethod + def get_fall_throughs( + cls, + obj: T, + inst: IMInstance, + parameters: Optional[Dict[str, Any]] = None, + ) -> List[S]: + if parameters is None: + parameters = {} + + disable_fallthroughs = exec_utils.get_param_value( + Parameters.DISABLE_FALLTHROUGHS, parameters, False + ) + + if inst is IMInstance.IM or inst is IMInstance.IMf: + if type(obj) is IMDataStructureUVCL: + if disable_fallthroughs: + return [EmptyTracesUVCL, FlowerModelUVCL] + else: + return [ + EmptyTracesUVCL, + ActivityOncePerTraceUVCL, + ActivityConcurrentUVCL, + StrictTauLoopUVCL, + TauLoopUVCL, + FlowerModelUVCL, + ] + if inst is IMInstance.IMd: + if disable_fallthroughs: + return [EmptyTracesDFG, FlowerModelDFG] + else: + return [EmptyTracesDFG, FlowerModelDFG] + return list() + + @classmethod + def fall_through( + cls, + obj: T, + inst: IMInstance, + pool, + manager, + parameters: Optional[Dict[str, Any]] = None, + ) -> Tuple[ProcessTree, List[T]]: + for f in FallThroughFactory.get_fall_throughs(obj, inst, parameters): + r = f.apply(obj, pool, manager, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/flower.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/flower.py new file mode 100644 index 0000000000000000000000000000000000000000..b030f06c0f7ca9b1e4538aebb2e635da7fc66043 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/flower.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 typing import Optional, Tuple, List, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureDFG, +) +from pm4py.algo.discovery.inductive.fall_through.abc import FallThrough +from pm4py.algo.discovery.inductive.fall_through.empty_traces import ( + EmptyTracesUVCL, +) +from pm4py.objects.process_tree.obj import ProcessTree, Operator +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL +from pm4py.objects.dfg.obj import DFG +from pm4py.algo.discovery.inductive.dtypes.im_dfg import InductiveDFG + + +class FlowerModelUVCL(FallThrough[IMDataStructureUVCL]): + + @classmethod + def holds( + cls, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return not EmptyTracesUVCL.holds(obj, parameters) + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[IMDataStructureUVCL]]]: + log = obj.data_structure + uvcl_redo = UVCL() + for a in sorted(list(comut.get_alphabet(log))): + uvcl_redo[(a,)] = 1 + uvcl_do = UVCL() + im_uvcl_do = IMDataStructureUVCL(uvcl_do) + im_uvcl_redo = IMDataStructureUVCL(uvcl_redo) + return ProcessTree(operator=Operator.LOOP), [im_uvcl_do, im_uvcl_redo] + + +class FlowerModelDFG(FallThrough[IMDataStructureDFG]): + @classmethod + def holds( + cls, + obj: IMDataStructureDFG, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return True + + @classmethod + def apply( + cls, + obj: IMDataStructureDFG, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[IMDataStructureDFG]]]: + activities = ( + set(obj.dfg.start_activities) + .union(set(obj.dfg.end_activities)) + .union(set(x[0] for x in obj.dfg.graph)) + .union(set(x[1] for x in obj.dfg.graph)) + ) + dfg_redo = DFG() + for a in activities: + dfg_redo.start_activities[a] = 1 + dfg_redo.end_activities[a] = 1 + dfg_do = DFG() + im_dfg_do = IMDataStructureDFG(InductiveDFG(dfg_do)) + im_dfg_redo = IMDataStructureDFG(InductiveDFG(dfg_redo)) + return ProcessTree(operator=Operator.LOOP), [im_dfg_do, im_dfg_redo] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/strict_tau_loop.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/strict_tau_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..4788d316bb2a2d2427ecd39fd07d91f48fabac46 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/strict_tau_loop.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 collections import Counter +from typing import Optional, Tuple, List, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.inductive.fall_through.abc import FallThrough +from pm4py.objects.process_tree.obj import ProcessTree, Operator +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL + + +class StrictTauLoopUVCL(FallThrough[IMDataStructureUVCL]): + + @classmethod + def _get_projected_log( + cls, log: UVCL, parameters: Optional[Dict[str, Any]] = None + ) -> UVCL: + start_activities = comut.get_start_activities(log) + end_activities = comut.get_end_activities(log) + proj = Counter() + for t in log: + x = 0 + for i in range(1, len(t)): + if t[i] in start_activities and t[i - 1] in end_activities: + proj.update({t[x:i]: log[t]}) + x = i + proj.update({t[x: len(t)]: log[t]}) + return proj + + @classmethod + def holds( + cls, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + log = obj.data_structure + return sum(cls._get_projected_log(log).values()) > sum(log.values()) + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[ProcessTree, List[IMDataStructureUVCL]]]: + log = obj.data_structure + proj = cls._get_projected_log(log) + if sum(proj.values()) > sum(log.values()): + return ProcessTree(operator=Operator.LOOP), [ + IMDataStructureUVCL(proj), + IMDataStructureUVCL(Counter()), + ] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/tau_loop.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/tau_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..00f57ed290fdaaf82519a91aab28911b934b7f9e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/fall_through/tau_loop.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 collections import Counter +from typing import Optional, Dict, Any + +from pm4py.algo.discovery.inductive.fall_through.strict_tau_loop import ( + StrictTauLoopUVCL, +) +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL + + +class TauLoopUVCL(StrictTauLoopUVCL): + + @classmethod + def _get_projected_log( + cls, log: UVCL, parameters: Optional[Dict[str, Any]] = None + ) -> UVCL: + start_activities = comut.get_start_activities(log) + proj = Counter() + for t in log: + x = 0 + for i in range(1, len(t)): + if t[i] in start_activities: + proj.update({t[x:i]: log[t]}) + x = i + proj.update({t[x: len(t)]: log[t]}) + return proj diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a9d8fcbe6d37b49802c908909934155a1cd556 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/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.algo.discovery.inductive.variants import abc, im, imd, imf diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d6abd2505f1640005d2f27e3b0deeb0f03ac19 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/abc.py @@ -0,0 +1,125 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 os +from abc import abstractmethod, ABC +from typing import Optional, Tuple, List, TypeVar, Generic, Dict, Any + +from pm4py.algo.discovery.inductive.base_case.factory import BaseCaseFactory +from pm4py.algo.discovery.inductive.cuts.factory import CutFactory +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructure +from pm4py.algo.discovery.inductive.fall_through.factory import ( + FallThroughFactory, +) +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.process_tree.obj import ProcessTree +from enum import Enum +from pm4py.util import exec_utils, constants + + +T = TypeVar("T", bound=IMDataStructure) + + +class Parameters(Enum): + MULTIPROCESSING = "multiprocessing" + + +class InductiveMinerFramework(ABC, Generic[T]): + """ + Base Class Implementing the Inductive Miner Framework. + How to Extend: + 1. Create a dedicated IMDataStructure class (see pm4py.algo.discovery.inductive.dtypes.im_ds.py) + 2. Create dedicated Base Cases, Cuts and Fall Throughs for the newly constructed IMDataStructure + 3. Extend the BaseCaseFactory, CutFactory and FallThroughFactory with the newly created functions + 4. Create a subclass of this class indicating the type on which it is defined and the corresponding IMInstance. + """ + + def __init__(self, parameters: Optional[Dict[str, Any]] = None): + if parameters is None: + parameters = {} + + enable_multiprocessing = exec_utils.get_param_value( + Parameters.MULTIPROCESSING, + parameters, + constants.ENABLE_MULTIPROCESSING_DEFAULT, + ) + + if enable_multiprocessing: + from multiprocessing import Pool, Manager + + self._pool = Pool(os.cpu_count() - 1) + self._manager = Manager() + self._manager.support_list = [] + else: + self._pool = None + self._manager = None + + def apply_base_cases( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[ProcessTree]: + return BaseCaseFactory.apply_base_cases( + obj, self.instance(), parameters=parameters + ) + + def find_cut( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[ProcessTree, List[T]]]: + return CutFactory.find_cut(obj, self.instance(), parameters=parameters) + + def fall_through( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Tuple[ProcessTree, List[T]]: + return FallThroughFactory.fall_through( + obj, + self.instance(), + self._pool, + self._manager, + parameters=parameters, + ) + + def apply( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> ProcessTree: + tree = self.apply_base_cases(obj, parameters) + if tree is None: + cut = self.find_cut(obj, parameters) + if cut is not None: + tree = self._recurse(cut[0], cut[1], parameters=parameters) + if tree is None: + ft = self.fall_through(obj, parameters) + tree = self._recurse(ft[0], ft[1], parameters=parameters) + return tree + + def _recurse( + self, + tree: ProcessTree, + objs: List[T], + parameters: Optional[Dict[str, Any]] = None, + ): + children = [self.apply(obj, parameters=parameters) for obj in objs] + for c in children: + c.parent = tree + tree.children.extend(children) + return tree + + @abstractmethod + def instance(self) -> IMInstance: + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/im.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/im.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb7d87882b8de4ba4356581ccc1db274606713c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/im.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 typing import TypeVar, Generic, Dict, Any, Optional + +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureLog, +) +from pm4py.algo.discovery.inductive.fall_through.empty_traces import ( + EmptyTracesUVCL, +) +from pm4py.algo.discovery.inductive.variants.abc import InductiveMinerFramework +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.process_tree.obj import ProcessTree + +T = TypeVar("T", bound=IMDataStructureLog) + + +class IM(Generic[T], InductiveMinerFramework[T]): + + def instance(self) -> IMInstance: + return IMInstance.IM + + +class IMUVCL(IM[IMDataStructureUVCL]): + def apply( + self, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> ProcessTree: + empty_traces = EmptyTracesUVCL.apply(obj, parameters) + if empty_traces is not None: + return self._recurse(empty_traces[0], empty_traces[1], parameters) + return super().apply(obj, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/imd.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/imd.py new file mode 100644 index 0000000000000000000000000000000000000000..14adb19b5fe7d4f6b30230ff74031b4d252cfcaf --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/imd.py @@ -0,0 +1,44 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.algo.discovery.inductive.dtypes.im_ds import IMDataStructureDFG +from pm4py.algo.discovery.inductive.variants.abc import InductiveMinerFramework +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.algo.discovery.inductive.fall_through.empty_traces import EmptyTracesDFG +from pm4py.objects.process_tree.obj import ProcessTree + +class IMD(InductiveMinerFramework[IMDataStructureDFG]): + + def instance(self) -> IMInstance: + return IMInstance.IMd + + + def apply( + self, + obj: IMDataStructureDFG, + parameters: Optional[Dict[str, Any]] = None, + ) -> ProcessTree: + # Handle empty traces FIRST (so τ is not lost if a base case/cut triggers) + empty_traces = EmptyTracesDFG.apply(obj, parameters=parameters) + if empty_traces is not None: + return self._recurse(empty_traces[0], empty_traces[1], parameters) + return super().apply(obj, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/imf.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/imf.py new file mode 100644 index 0000000000000000000000000000000000000000..2babaad9ad4ecc77b3bf115217c675238d7dab61 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/imf.py @@ -0,0 +1,146 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 TypeVar, Generic, Dict, Any, Optional + +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructureUVCL, + IMDataStructureLog, +) +from pm4py.algo.discovery.inductive.fall_through.empty_traces import ( + EmptyTracesUVCL, +) +from pm4py.algo.discovery.inductive.variants.abc import InductiveMinerFramework +from pm4py.algo.discovery.inductive.variants.instances import IMInstance +from pm4py.objects.process_tree.obj import ProcessTree +from pm4py.objects.dfg.obj import DFG +from copy import copy +from enum import Enum +from pm4py.util import exec_utils + + +T = TypeVar("T", bound=IMDataStructureLog) + + +class IMFParameters(Enum): + NOISE_THRESHOLD = "noise_threshold" + + +class IMF(Generic[T], InductiveMinerFramework[T]): + + def instance(self) -> IMInstance: + return IMInstance.IMf + + +class IMFUVCL(IMF[IMDataStructureUVCL]): + def apply( + self, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + second_iteration: bool = False, + ) -> ProcessTree: + noise_threshold = exec_utils.get_param_value( + IMFParameters.NOISE_THRESHOLD, parameters, 0.0 + ) + + empty_traces = EmptyTracesUVCL.apply(obj, parameters) + if empty_traces is not None and empty_traces[1]: + number_original_traces = sum( + y for y in obj.data_structure.values() + ) + number_filtered_traces = sum( + y for y in empty_traces[1][1].data_structure.values() + ) + + if ( + number_original_traces - number_filtered_traces + > noise_threshold * number_original_traces + ): + return self._recurse( + empty_traces[0], empty_traces[1], parameters + ) + else: + obj = empty_traces[1][1] + + tree = self.apply_base_cases(obj, parameters) + if tree is None: + cut = self.find_cut(obj, parameters) + if cut is not None: + tree = self._recurse(cut[0], cut[1], parameters=parameters) + if tree is None: + if not second_iteration: + filtered_ds = self.__filter_dfg_noise(obj, noise_threshold) + tree = self.apply( + filtered_ds, + parameters=parameters, + second_iteration=True, + ) + if tree is None: + ft = self.fall_through(obj, parameters) + tree = self._recurse( + ft[0], ft[1], parameters=parameters + ) + return tree + + def __filter_dfg_noise(self, obj, noise_threshold): + start_activities = copy(obj.dfg.start_activities) + end_activities = copy(obj.dfg.end_activities) + dfg = copy(obj.dfg.graph) + outgoing_max_occ = {} + for x, y in dfg.items(): + act = x[0] + if act not in outgoing_max_occ: + outgoing_max_occ[act] = y + else: + outgoing_max_occ[act] = max(y, outgoing_max_occ[act]) + if act in end_activities: + outgoing_max_occ[act] = max( + outgoing_max_occ[act], end_activities[act] + ) + dfg_list = sorted( + [(x, y) for x, y in dfg.items()], + key=lambda x: (x[1], x[0]), + reverse=True, + ) + dfg_list = [ + x + for x in dfg_list + if x[1] > noise_threshold * outgoing_max_occ[x[0][0]] + ] + dfg_list = [x[0] for x in dfg_list] + # filter the elements in the DFG + graph = {x: y for x, y in dfg.items() if x in dfg_list} + + # apply filtering to start activities + start_max_occ = max(start_activities.values()) + start_activities = {x: y for x, y in start_activities.items() + if y >= start_max_occ * noise_threshold + } + + dfg = DFG() + for sa in start_activities: + dfg.start_activities[sa] = start_activities[sa] + for ea in end_activities: + dfg.end_activities[ea] = end_activities[ea] + for act in graph: + dfg.graph[act] = graph[act] + + return IMDataStructureUVCL(obj.data_structure, dfg) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/instances.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/instances.py new file mode 100644 index 0000000000000000000000000000000000000000..274e84b7a131ffab1385b8efa82f15260785f290 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/inductive/variants/instances.py @@ -0,0 +1,30 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, auto + + +class IMInstance(Enum): + IM = auto() + IMd = auto() + IMf = auto() + IMa = auto() + IMi = auto() diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe564208570d05b9f7675a4719b60e31797e2fa9 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/__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.algo.discovery.local_process_models import ( + algorithm, + metrics, + variants, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..f72a10c09e564c915392813f822d3a9d2482084a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/algorithm.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, Union, Tuple, List + +import pandas as pd + +from pm4py import ProcessTree +from pm4py.algo.discovery.local_process_models.metrics.quality_metrics import LocalProcessModelStats +from pm4py.algo.discovery.local_process_models.variants import classic +from pm4py.objects.log.obj import EventLog +from pm4py.util import exec_utils + + +class Variants(Enum): + CLASSIC = classic + + +def find_local_process_models( + log: Union[EventLog, pd.DataFrame], + selected_activities: Union[None, list] = None, + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> List[Tuple[ProcessTree, LocalProcessModelStats]]: + return exec_utils.get_variant(variant).apply(log, selected_activities, parameters) + diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/metrics/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/metrics/__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/algo/discovery/local_process_models/metrics/quality_metrics.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/metrics/quality_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..786f50a14e3a24dd6498fd1a08c2115db7b173a5 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/metrics/quality_metrics.py @@ -0,0 +1,260 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 statistics import harmonic_mean + +import pm4py.algo.simulation.playout.petri_net.variants.extensive as extensive_playout +from pm4py import filter_event_attribute_values, get_event_attribute_values, convert_to_dataframe +from pm4py import get_variants +from pm4py.algo.conformance.alignments.petri_net.algorithm import apply_trace, VERSION_STATE_EQUATION_A_STAR +from pm4py.algo.simulation.playout.petri_net import algorithm as playout_algo +from pm4py.convert import convert_to_petri_net +from pm4py.objects.log.obj import Trace, Event +from pm4py.objects.petri_net.obj import PetriNet +from pm4py.objects.petri_net.semantics import enabled_transitions, execute +from pm4py.objects.petri_net.utils.petri_utils import add_arc_from_to +from pm4py.util import constants + + +class LocalProcessModelStats(object): + + def __init__(self, frequency, determinism, confidence, language_fit, coverage, number_of_activities): + self.frequency = frequency + self.determinism = determinism + self.confidence = confidence + self.language_fit = language_fit + self.coverage = coverage + self.number_of_activities = number_of_activities + + +""" +Evaluates the quality of the local process model based on the 5 quality metrics. +Returns true if the tree should be extended, otherwise false. +If all 5 quality thresholds are met, the tree along with its stats is added to return_lpms. +""" +def evaluate_tree(log, + tree, + activities_used_in_model, + projected_log_variants_cache, + activity_key, + timestamp_key, + case_id_key, + iteration, + frequency_threshold, confidence_threshold, determinism_threshold, + language_fit_threshold, coverage_threshold, + return_lpms) -> bool: + # we have only one final marking per petri net so we need to only add one transition + ev_pn, ev_im, ev_fm, backloop_transition_name = __build_lpn_evaluation_petri_net(tree) + + variants, activity_occurrences, num_events = __get_projected_log_variants_and_metrics( + projected_log_variants_cache, frozenset(activities_used_in_model), + log, activity_key, timestamp_key, case_id_key) + + frequency, confidence, determinism, segments = __compute_freq_conf_det( + ev_pn, + ev_im, + ev_fm, + backloop_transition_name, + activities_used_in_model, + activity_key, timestamp_key, case_id_key, + variants, + activity_occurrences) + + if frequency < frequency_threshold or determinism < determinism_threshold: + return False + + number_of_events_in_log = sum(len(trace) for trace in log) + coverage = num_events / number_of_events_in_log + if coverage < coverage_threshold or confidence < confidence_threshold: + return True # no need to calculate language fit if coverage or confidence is already insufficient + + pn, im, fm = convert_to_petri_net(tree) + language_fit = compute_language_fit(pn, im, fm, iteration, segments) + + if language_fit >= language_fit_threshold: + stats = LocalProcessModelStats(frequency, determinism, confidence, + language_fit, coverage, iteration) + return_lpms.append((tree, stats)) + + return True + + +def __build_lpn_evaluation_petri_net(tree): + pn, im, fm = convert_to_petri_net(tree) + + backloop_transition_name = str(uuid.uuid4()) + loop_back_transition = PetriNet.Transition( + backloop_transition_name, None + ) + + pn.transitions.add(loop_back_transition) + for start_place in im.keys(): + add_arc_from_to(loop_back_transition, start_place, pn) + + for final_place in fm.keys(): + add_arc_from_to(final_place, loop_back_transition, pn) + + return pn, im, im, backloop_transition_name + + +def __compute_freq_conf_det(ev_pn, ev_im, ev_fm, backloop_transition_name, + activities_used_in_model, + activity_key, timestamp_key, case_id_key, + variants, + projected_log_activity_occurrences): + + + parameters = { + "case_id_key": case_id_key, + "activity_key": activity_key, + constants.PARAMETER_CONSTANT_ACTIVITY_KEY: activity_key, + "timestamp_key": timestamp_key, + "return_diagnostics_dataframe": False, + "ret_tuple_as_trans_desc": True, + "model_cost_function": {transition: 0 if transition.label is None else 99999999 for transition in ev_pn.transitions}, + "event_cost_function": {activity: 1 for activity in activities_used_in_model}, + "sync_cost_function": {t: 0 for t in ev_pn.transitions}, + "show_progress_bar": False, + } + + alignments = [] + for trace, num in variants: + alignment = apply_trace( + trace, + ev_pn, + ev_im, + ev_fm, + parameters=parameters, + variant=VERSION_STATE_EQUATION_A_STAR + ) + alignments.append((alignment, num)) + + number_of_model_executions = 0 + activities_occurences_in_model = {a: 0 for a in activities_used_in_model} + + seen_model_segments = set() + + for alignment, trace_count in alignments: + current_segment = [] + num_segments = 0 + for step in alignment["alignment"]: + (_, model_transition), (log_activity, model_activity) = step + + if model_activity != ">>" and log_activity == model_activity: + activities_occurences_in_model[log_activity] += trace_count + current_segment.append(log_activity) + + elif model_activity is None: + if model_transition is backloop_transition_name: + if len(current_segment): + seen_model_segments.add(tuple(current_segment)) + num_segments += 1 + current_segment = [] + + if len(current_segment) > 0: + seen_model_segments.add(tuple(current_segment)) + num_segments += 1 + number_of_model_executions += num_segments * trace_count + + confidence_per_activity = [activities_occurences_in_model[a] / projected_log_activity_occurrences[i] + if projected_log_activity_occurrences[i] != 0 + else 0 + for i, a in enumerate(activities_used_in_model)] + + if any(map(lambda c: c == 0, confidence_per_activity)): + confidence = 0 + else: + confidence = harmonic_mean(confidence_per_activity) + + num_enabled_transitions = 0 + num_fired_transitions = 0 + for alignment, trace_count in alignments: + current_marking = ev_im + for step in alignment["alignment"]: + (_, model_transition), (log_activity, model_activity) = step + if model_activity != ">>": + all_enabled = enabled_transitions(ev_pn, current_marking) + fired_transition = next((t for t in all_enabled if t.name == model_transition), None) + + num_enabled_transitions += len(all_enabled) * trace_count + num_fired_transitions += trace_count + + current_marking = execute(fired_transition, ev_pn, current_marking) + + determinism = num_fired_transitions / num_enabled_transitions if num_enabled_transitions > 0 else 0 + + return number_of_model_executions, confidence, determinism, seen_model_segments + + +def compute_language_fit(pn, im, fm, iteration, traces_executed_during_alignments): + n = iteration * 2 # should be greater or equal to iteration + + parameters = { + extensive_playout.Parameters.MAX_TRACE_LENGTH: n + } + + simulated_log = playout_algo.apply( + pn, + im, + fm, + variant=playout_algo.Variants.EXTENSIVE, + parameters=parameters + ) + + allowed_variants = get_variants(simulated_log) + total_traces = len(allowed_variants) + + match_count = 0 + for allowed_trace in allowed_variants: + if allowed_trace in traces_executed_during_alignments: + match_count += 1 + + return match_count / total_traces if total_traces > 0 else 0 + + +def __get_projected_log_variants_and_metrics(projected_log_variants_cache, activities_used_in_model, log, activity_key, + timestamp_key, case_id_key): + if frozenset(activities_used_in_model) in projected_log_variants_cache: + return projected_log_variants_cache[frozenset(activities_used_in_model)] + else: + projected_log = filter_event_attribute_values(log, + case_id_key=case_id_key, + attribute_key=activity_key, + values=activities_used_in_model, + level="event") + + # this is a workaround since get_variants has an unexpected return value when passing EventLog types + projected_log = convert_to_dataframe(projected_log) + + variants = [(Trace([Event({activity_key: e}) for e in trace]), num) + for trace, num in get_variants(projected_log, + case_id_key=case_id_key, + activity_key=activity_key, + timestamp_key=timestamp_key).items()] + + all_counts = get_event_attribute_values(projected_log, activity_key) + activity_occurrences = [all_counts.get(a, 0) for a in activities_used_in_model] + num_events = sum(activity_occurrences) + + projected_log_variants_cache[frozenset(activities_used_in_model)] = variants, activity_occurrences, num_events + + return variants, activity_occurrences, num_events \ No newline at end of file diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63a8fbe4dbb1705fd6426a5b6ca2a8553349dcee --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/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.algo.discovery.local_process_models.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..f38594af795e3e09eea4e6ac7db35938e23ac0a0 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/local_process_models/variants/classic.py @@ -0,0 +1,510 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 importlib.util +import time +from enum import Enum +from typing import Tuple, List, Union, Dict, Any, Optional +import importlib.util +import multiprocessing as mp +import pandas as pd + +from pm4py import util as pmutil, ProcessTree +from pm4py.algo.discovery.local_process_models.metrics.quality_metrics import evaluate_tree, LocalProcessModelStats +from pm4py.objects.log.obj import EventLog +from pm4py.objects.process_tree.obj import Operator +from pm4py.stats import get_event_attribute_values +from pm4py.util import constants +from pm4py.util import exec_utils +from pm4py.util import xes_constants as xes_util + + +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 + + FREQUENCY_THRESHOLD = "lpm_frequency_threshold" + DETERMINISM_THRESHOLD = "lpm_determinism_threshold" + + CONFIDENCE_THRESHOLD = "lpm_confidence_threshold" + LANGUAGE_FIT_THRESHOLD = "lpm_language_fit_threshold" + COVERAGE_THRESHOLD = "lpm_coverage_threshold" + + MAX_ITERATIONS = "max_iterations" + MAX_NUMBER_OF_MODELS = "max_number_of_models" + TIME_LIMIT = "time_limit" + + MULTI_PROCESSING = "multi_processing" + PROGRESS_BAR_TYPE = "progress_bar_type" + +def apply( + log: Union[EventLog, pd.DataFrame], + selected_activities: Union[None, list], + parameters: Optional[Dict[Any, Any]] +) -> List[Tuple[ProcessTree, LocalProcessModelStats]]: + """ + Discovers Local Process Models with the algorithm described in [1]_. + + Local Process Models aim to find frequent and recurring patterns + describing parts the event log, usually focusing on a subset of activities. + + In contrast to episode and sequential pattern mining, Local Process Models + are represented by Process Trees and can therefore model loops and + exclusive choices alongside sequences and concurrency which the Episode Miner + can find as well [2]_. + + The algorithm returns multiple Local Process Models that can be evaluated + based on the five quality metrics introduced in the paper. + The values of all five metrics are between 0 and 1. + Here, instead of relying on the support metric, which scales the + frequency to [0, 1), we instead directly expose the frequency. + + - **Frequency**: Measures how often a Local Process Model is executed in the event log. Note that per trace the model can be executed multiple times. + - **Confidence**: Measures, per activity in the model, the ratio of events which are part of model executions. The harmonic mean over all activities in the model in returned. + - **Language fit**: Describes the precision of the model by calculating how many of the allowed traces in the Local Process Model are actually executed. + - **Determinism**: Measures the amount of choices in the state space of the model. Fewer choices lead to higher determinism values. + - **Coverage**: The ratio of events in the log that stem from activities used in the model. + + Notes + ----- + + Evaluating a large amount of these process models is costly. + Limiting the allowed activities in the Local Process Models leads to a smaller search space and + can lead to better performance. + Additionally, the search space can be pruned based on support and determinism. + Increasing the thresholds for these values can speed up the algorithm. + Moreover, the maximum number of Local Process Models to be returned can be + specified, providing a cut-off for the algorithm. + + The unpruned search space 's' in iteration 'i' grows polynomially in the number of selected activities 'a' + (to the power of i) and exponentially in the iteration 'i': :math:`s = a^i 6^{i-1} (i-1)!` + + + + Parameters + ---------- + log: :class:`pm4py.log.log.EventLog` + Event log to use + selected_activities: list + Activities to consider when building Local Process Models, default is None, in which case all activities are used. + parameters: + Parameters of the algorithm, including: + + - CASE_ID_KEY : str, optional + Key used to correlate events into cases. + By default, the value 'case:concept:name' is used. + - ACTIVITY_KEY : str, optional + Key to use within events to identify the underlying activity. + By default, the value 'concept:name' is used. + - FREQUENCY_THRESHOLD : int, optional + Positive integer frequency threshold, default is 20. + - CONFIDENCE_THRESHOLD : float, optional + Confidence threshold between 0 and 1, default is 0.7. + - DETERMINISM_THRESHOLD : float, optional + Determinism threshold between 0 and 1, default is 0.5. + - LANGUAGE_FIT_THRESHOLD : float, optional + Language fit threshold between 0 and 1, default is 0.3. + - COVERAGE_THRESHOLD : float, optional + Coverage threshold between 0 and 1, default is 0. + - MAX_ITERATIONS : int, optional + Maximum number of iterations of the search algorithm. In each iteration 'i' Process Trees with exactly 'i' activities are considered, default is 3 + - MAX_NUMBER_OF_MODELS : int, optional + The maximum number of models to be returned. Can be used to restrict the solve time. Default is None. + - MULTI_PROCESSING : boolean, optional + Whether to use multiprocessing, default is False. + - TIME_LIMIT : float, optional + Time limit for the computation, default is None. This is not a hard limit. The evaluation of the current model is finished or if multiprocessing + is enabled the evaluation of the current batch is finished before the time limit stops the process. + - PROGRESS_BAR_TYPE : string, optional + Default value `explored_lpms` shows the number of explored LPMs in each iteration. + Use `found_lpms` to show a progress bar for the number of LPMs found so far in relation to MAX_NUMBER_OF_MODELS. + Otherwise, use None to hide the progress bar. + + Returns + ------- + lpms : list of tuple + A list of tuples, where each tuple contains a + ``pm4py.objects.process_tree.obj.ProcessTree`` and its corresponding + ``pm4py.algo.discovery.local_process_models.metrics.quality_metrics.LocalProcessModelStats``. + + References + ---------- + .. [1] Tax, N., Sidorova, N., Haakma, R., & van der Aalst, W. M. (2016). + Mining local process models. Journal of Innovation in Digital Ecosystems, 3(2), 183-196. + + .. [2] Leemans, M., & van der Aalst, W. M. (2014, November). Discovery of frequent episodes in event logs. + In International symposium on data-driven process discovery and analysis (pp. 1-31). Cham: Springer International Publishing. + + """ + + if parameters is None: + parameters = {} + case_id_glue = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, pmutil.constants.CASE_CONCEPT_NAME + ) + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY + ) + + activity_counts = get_event_attribute_values(log, activity_key) + log_activities = list(activity_counts.keys()) + if selected_activities is None: + selected_activities = log_activities + elif not set(selected_activities).issubset(set(log_activities)): + raise ValueError(f"Not all selected activities are present in the log.\n" + f"Activities in log: {log_activities}.\n" + f"Selected activities: {selected_activities}") + + frequency_threshold = exec_utils.get_param_value( + Parameters.FREQUENCY_THRESHOLD, parameters, 20 + ) + + determinism_threshold = exec_utils.get_param_value( + Parameters.DETERMINISM_THRESHOLD, parameters, 0.5 + ) + + confidence_threshold = exec_utils.get_param_value( + Parameters.CONFIDENCE_THRESHOLD, parameters, 0.7 + ) + + language_fit_threshold = exec_utils.get_param_value( + Parameters.LANGUAGE_FIT_THRESHOLD, parameters, 0.3 + ) + + coverage_threshold = exec_utils.get_param_value( + Parameters.COVERAGE_THRESHOLD, parameters, 0 + ) + + max_iterations = exec_utils.get_param_value( + Parameters.MAX_ITERATIONS, parameters, 3 + ) + + max_number_of_models = exec_utils.get_param_value( + Parameters.MAX_NUMBER_OF_MODELS, parameters, None + ) + + multi_processing = exec_utils.get_param_value( + Parameters.MULTI_PROCESSING, parameters, False + ) + + time_limit = exec_utils.get_param_value( + Parameters.TIME_LIMIT, parameters, None + ) + + progress_bar_type = exec_utils.get_param_value( + Parameters.PROGRESS_BAR_TYPE, parameters, "explored_lpms" + ) + + start_time = time.time() + return_lpms = [] + trees_to_expand = [] + projected_log_cache = dict() + i = 1 + while i <= max_iterations: + if i == 1: + candidates = __generate_initial_trees(selected_activities) + else: + candidates = __expand_trees(trees_to_expand, selected_activities, i == 2) + + trees_to_expand = __evaluate_trees(log, + candidates, + activity_key, + timestamp_key, + case_id_glue, + i, + frequency_threshold, + confidence_threshold, + determinism_threshold, + language_fit_threshold, + coverage_threshold, + progress_bar_type, + multi_processing, + max_number_of_models, + projected_log_cache, + start_time, + time_limit, + return_lpms) + + if not len(trees_to_expand): + return return_lpms + + i += 1 + + return return_lpms + + +def __generate_initial_trees(selected_activities): + return [(ProcessTree(operator=None, parent=None, label=activity), {activity}) for activity in selected_activities] + + +def __expand_trees(base_trees, selected_activities, is_first_expansion): + expanded_trees = [] + for tree, used_activities in base_trees: + current = [(0, tree)] + while len(current) > 0: + idx, node = current.pop() + if len(node.children) == 0: + for activity in selected_activities: # paper suggests that we iterate over all activities, including ones already used in the pattern + parent_operator = node.parent.operator if node.parent else None + __add_expanded_tree_variants(expanded_trees, tree, used_activities, node.label, activity, parent_operator, idx, is_first_expansion) + else: + current.extend(enumerate(node.children)) + + return expanded_trees + + +def __add_expanded_tree_variants(expanded_trees, tree, used_activities, existing_activity, new_activity, parent_operator, child_index, is_first_expansion): + new_used_activities = used_activities.union({new_activity}) + if parent_operator is not Operator.SEQUENCE or child_index == 0: # symmetry pruning not mentioned in paper + seq1 = _get_expanded_tree_variant(tree, existing_activity, + Operator.SEQUENCE, existing_activity, new_activity) + expanded_trees.append((seq1, new_used_activities)) + + if existing_activity != new_activity and not is_first_expansion: + seq2 = _get_expanded_tree_variant(tree, existing_activity, + Operator.SEQUENCE, new_activity, existing_activity) + expanded_trees.append((seq2, new_used_activities)) + + if existing_activity != new_activity and (not is_first_expansion and hash(existing_activity) < hash(new_activity)): + + # symmetry pruning: if parent operator is equal to this operator only extend first child + if parent_operator is not Operator.XOR or child_index == 0: + xor = _get_expanded_tree_variant(tree, existing_activity, + Operator.XOR, existing_activity, new_activity) + expanded_trees.append((xor, new_used_activities)) + + # symmetry pruning: if parent operator is equal to this operator only extend first child + if parent_operator is not Operator.PARALLEL or child_index == 0: + parallel = _get_expanded_tree_variant(tree, existing_activity, + Operator.PARALLEL, existing_activity, new_activity) + expanded_trees.append((parallel, new_used_activities)) + + loop1 = _get_expanded_tree_variant(tree, existing_activity, + Operator.LOOP, existing_activity, new_activity) + expanded_trees.append((loop1, new_used_activities)) + + if existing_activity != new_activity and not is_first_expansion: + loop2 = _get_expanded_tree_variant(tree, existing_activity, + Operator.LOOP, new_activity, existing_activity) + expanded_trees.append((loop2, new_used_activities)) + + +def _get_expanded_tree_variant(original_tree, leaf_activity_name, operator, activity1, activity2): + copied_tree, leaf_node = __deep_copy_and_get_leaf_ref_by_activity(original_tree, leaf_activity_name) + parent = leaf_node.parent + new_operator_node = ProcessTree(operator=operator, parent=parent) + new_leaves = [ProcessTree(operator=None, parent=new_operator_node, label=activity1), + ProcessTree(operator=None, parent=new_operator_node, label=activity2)] + new_operator_node.children = new_leaves + + if parent is not None: + parent.children.remove(leaf_node) + parent.children.append(new_operator_node) + else: + copied_tree = new_operator_node + + del leaf_node + return copied_tree + + +def __deep_copy_and_get_leaf_ref_by_activity(tree_node, activity): + cloned_node = ProcessTree( + operator=tree_node.operator, + label=tree_node.label + ) + + cloned_node._properties = copy.deepcopy(tree_node._properties) + + activity_leaf_node = None + if not tree_node.children: + if tree_node.label == activity: + activity_leaf_node = cloned_node + else: + cloned_children = [] + for child in tree_node.children: + cloned_child, maybe_leaf_node = __deep_copy_and_get_leaf_ref_by_activity(child, activity) + + cloned_child.parent = cloned_node + cloned_children.append(cloned_child) + + if maybe_leaf_node is not None: + activity_leaf_node = maybe_leaf_node + + cloned_node.children = cloned_children + + return cloned_node, activity_leaf_node + + +_lpm_worker_state = {} +def __init_worker(log, projected_log_cache, activity_key, timestamp_key, case_id_key, iteration, + frequency_threshold, confidence_threshold, determinism_threshold, + language_fit_threshold, coverage_threshold): + global _lpm_worker_state + _lpm_worker_state['log'] = log + _lpm_worker_state['projected_log_cache'] = projected_log_cache + _lpm_worker_state['activity_key'] = activity_key + _lpm_worker_state['timestamp_key'] = timestamp_key + _lpm_worker_state['case_id_key'] = case_id_key + _lpm_worker_state['iteration'] = iteration + _lpm_worker_state['frequency_threshold'] = frequency_threshold + _lpm_worker_state['confidence_threshold'] = confidence_threshold + _lpm_worker_state['determinism_threshold'] = determinism_threshold + _lpm_worker_state['language_fit_threshold'] = language_fit_threshold + _lpm_worker_state['coverage_threshold'] = coverage_threshold + + +def __mp_evaluate_tree_worker(candidate): + tree, used_activities = candidate + args = _lpm_worker_state + local_return_lpms = [] + + expand_tree = evaluate_tree( + args['log'], tree, used_activities, args['projected_log_cache'], + args['activity_key'], args['timestamp_key'], args['case_id_key'], + args['iteration'], args['frequency_threshold'], args['confidence_threshold'], + args['determinism_threshold'], args['language_fit_threshold'], + args['coverage_threshold'], local_return_lpms + ) + + return tree, used_activities, expand_tree, local_return_lpms + + +def __evaluate_trees(log, candidates, activity_key, timestamp_key, case_id_key, iteration, + frequency_threshold, confidence_threshold, determinism_threshold, + language_fit_threshold, coverage_threshold, progress_bar_type, multi_processing, + max_number_of_models, projected_log_cache, start_time, time_limit, return_lpms): + trees_to_expand = [] + progress = __get_progress_bar(len(candidates), max_number_of_models, iteration, progress_bar_type) + __update_progress(progress, progress_bar_type, return_lpms) # makes sure the bar starts at the correct value when process bar type is "found_lpms" + + if multi_processing and len(candidates) > 200: + init_args = ( + log, projected_log_cache, activity_key, timestamp_key, case_id_key, iteration, + frequency_threshold, confidence_threshold, determinism_threshold, + language_fit_threshold, coverage_threshold + ) + + chunk_size = 50 + num_cores = mp.cpu_count() + with mp.Pool(processes=num_cores, initializer=__init_worker, initargs=init_args) as pool: # 69 + + candidate_iterator = iter(candidates) + for tree, used_activities, expand_tree, local_lpms in pool.imap_unordered( + __mp_evaluate_tree_worker, + candidate_iterator, + chunksize=chunk_size + ): + + return_lpms.extend(local_lpms) + + if expand_tree: + trees_to_expand.append((tree, used_activities)) + + __update_progress(progress, progress_bar_type, return_lpms) + + if max_number_of_models and len(return_lpms) >= max_number_of_models: + del return_lpms[max_number_of_models:] # due to multiprocessing we might have found too many lmps + pool.terminate() + __close_progress_bar(progress) + return [] + + elapsed_time = time.time() - start_time + if time_limit is not None and elapsed_time > time_limit: + if max_number_of_models and len(return_lpms) > max_number_of_models: + del return_lpms[max_number_of_models:] + pool.terminate() + __close_progress_bar(progress) + return [] + else: + for tree, used_activities in candidates: + expand_tree = evaluate_tree(log, + tree, + used_activities, + projected_log_cache, + activity_key, + timestamp_key, + case_id_key, + iteration, + frequency_threshold, + confidence_threshold, + determinism_threshold, + language_fit_threshold, + coverage_threshold, + return_lpms) + + if expand_tree: + trees_to_expand.append((tree, used_activities)) + + __update_progress(progress, progress_bar_type, return_lpms) + + if max_number_of_models and len(return_lpms) >= max_number_of_models: + __close_progress_bar(progress) + return [] + + elapsed_time = time.time() - start_time + if time_limit is not None and elapsed_time > time_limit: + __close_progress_bar(progress) + return [] + + __close_progress_bar(progress) + + return trees_to_expand + + +def __get_progress_bar(num_candidates, max_num_lpms, iteration, progress_bar_type): + progress = None + + if ( + importlib.util.find_spec("tqdm") + ): + if progress_bar_type == "found_lpms" and max_num_lpms is not None and max_num_lpms > 0: + from tqdm.auto import tqdm + progress = tqdm( + total=max_num_lpms, desc=f"Iteration {iteration} Total Discovered LPMs :: " + ) + elif progress_bar_type == "explored_lpms" and num_candidates > 0: + from tqdm.auto import tqdm + progress = tqdm( + total=num_candidates, desc=f"Iteration {iteration} Checking LPM Candidates :: " + ) + + return progress + + +def __update_progress(progress, progress_bar_type, return_lpms): + if progress is not None: + if progress_bar_type == "found_lpms": + progress.n = len(return_lpms) + progress.refresh() + elif progress_bar_type == "explored_lpms": + progress.update() + +def __close_progress_bar(progress): + if progress is not None: + progress.close() + del progress + diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94480ed0b8f9810e8fb0ac9f531024854576f392 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/__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.discovery.log_skeleton import variants, trace_skel, algorithm diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..d517a070dc44d521d89220ed0425f008cedf6c0e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/algorithm.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 +''' +from pm4py.algo.discovery.log_skeleton.variants import classic +from enum import Enum +from pm4py.util import exec_utils +from typing import Optional, Dict, Any, Union, Tuple, List +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd + + +class Variants(Enum): + CLASSIC = classic + + +CLASSIC = Variants.CLASSIC +DEFAULT_VARIANT = CLASSIC + +VERSIONS = {CLASSIC} + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + variant=DEFAULT_VARIANT, + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Any]: + """ + Discover a log skeleton from an event log + + Parameters + ------------- + log + Event log + variant + Variant of the algorithm, possible values: + - Variants.CLASSIC + parameters + Parameters of the algorithm, including: + - the activity key (Parameters.ACTIVITY_KEY) + - the noise threshold (Parameters.NOISE_THRESHOLD) + + Returns + ------------- + model + Log skeleton model + """ + return exec_utils.get_variant(variant).apply(log, parameters=parameters) + + +def apply_from_variants_list( + var_list: List[Tuple[str, int]], + variant=DEFAULT_VARIANT, + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Any]: + """ + Discovers the log skeleton from the variants list + + Parameters + --------------- + var_list + Variants list + variant + Variant of the algorithm, possible values: + - Variants.CLASSIC + parameters + Parameters + + Returns + ------------- + model + Log skeleton model + """ + return exec_utils.get_variant(variant).apply_from_variants_list( + var_list, parameters=parameters + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/trace_skel.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/trace_skel.py new file mode 100644 index 0000000000000000000000000000000000000000..a5fae832268dd14a4b3c793c5dbe1e2db87e0efb --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/trace_skel.py @@ -0,0 +1,155 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 + + +def equivalence(trace): + """ + Get the equivalence relations given a list of activities + + Parameters + -------------- + trace + List activities + + Returns + -------------- + rel + Relations inside the trace + """ + ret = list() + freq = activ_freq(trace) + for x in freq: + for y in freq: + if x != y and freq[x] == freq[y]: + for i in range(freq[x]): + ret.append((x, y)) + return ret + + +def after(trace): + """ + Get the after- relations given a list of activities + + Parameters + -------------- + trace + List activities + + Returns + -------------- + rel + After- inside the trace + """ + return list( + (trace[i], trace[j]) + for i in range(len(trace)) + for j in range(len(trace)) + if j > i + ) + + +def before(trace): + """ + Get the before- relations given a list of activities + + Parameters + -------------- + trace + List activities + + Returns + -------------- + rel + Before- inside the trace + """ + return list( + (trace[i], trace[j]) + for i in range(len(trace)) + for j in range(len(trace)) + if j < i + ) + + +def combos(trace): + """ + Get the combinations between all the activities of the trace relations given a list of activities + + Parameters + -------------- + trace + List activities + + Returns + -------------- + rel + Combos inside the trace + """ + return set((x, y) for x in trace for y in trace if x != y) + + +def directly_follows(trace): + """ + Get the directly-follows relations given a list of activities + + Parameters + -------------- + trace + List activities + + Returns + -------------- + rel + Directly-follows relations inside the trace + """ + return list((trace[i], trace[i + 1]) for i in range(len(trace) - 1)) + + +def activ_freq(trace): + """ + Gets the frequency of activities happening in a trace + + Parameters + -------------- + trace + List activities + + Returns + -------------- + freq + Frequency of activities + """ + return Counter(trace) + + +def get_trace_info(trace): + """ + Technical method for conformance checking + """ + return ( + equivalence(trace), + after(trace), + before(trace), + combos(trace), + directly_follows(trace), + activ_freq(trace), + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..244827fc057a3227d3ada146e281e84e10b503ab --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/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.algo.discovery.log_skeleton.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..28273f09a82a4b0ea3e15a82f4de7c48e1f1f654 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/log_skeleton/variants/classic.py @@ -0,0 +1,432 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 pm4py.algo.discovery.log_skeleton import trace_skel +from pm4py.objects.log.util import xes +from pm4py.util import exec_utils +from pm4py.util import variants_util, pandas_utils +from pm4py.util.constants import ( + PARAMETER_CONSTANT_ACTIVITY_KEY, + PARAMETER_CONSTANT_CASEID_KEY, + CASE_CONCEPT_NAME, +) +from typing import Optional, Dict, Any, Union +from pm4py.objects.log.obj import EventLog +import pandas as pd + + +class Parameters(Enum): + # parameter for the noise threshold + NOISE_THRESHOLD = "noise_threshold" + # considered constraints in conformance checking among: equivalence, + # always_after, always_before, never_together, directly_follows, + # activ_freq + CONSIDERED_CONSTRAINTS = "considered_constraints" + # default choice for conformance checking + DEFAULT_CONSIDERED_CONSTRAINTS = [ + "equivalence", + "always_after", + "always_before", + "never_together", + "directly_follows", + "activ_freq", + ] + CASE_ID_KEY = PARAMETER_CONSTANT_CASEID_KEY + ACTIVITY_KEY = PARAMETER_CONSTANT_ACTIVITY_KEY + PARAMETER_VARIANT_DELIMITER = "variant_delimiter" + + +NOISE_THRESHOLD = Parameters.NOISE_THRESHOLD +CONSIDERED_CONSTRAINTS = Parameters.CONSIDERED_CONSTRAINTS +DEFAULT_CONSIDERED_CONSTRAINTS = Parameters.DEFAULT_CONSIDERED_CONSTRAINTS +ACTIVITY_KEY = Parameters.ACTIVITY_KEY +PARAMETER_VARIANT_DELIMITER = Parameters.PARAMETER_VARIANT_DELIMITER + + +class Outputs(Enum): + EQUIVALENCE = "equivalence" + ALWAYS_AFTER = "always_after" + ALWAYS_BEFORE = "always_before" + NEVER_TOGETHER = "never_together" + DIRECTLY_FOLLOWS = "directly_follows" + ACTIV_FREQ = "activ_freq" + + +def equivalence(logs_traces, all_activs, noise_threshold=0): + """ + Gets the equivalence relations given the traces of the log + + Parameters + ------------- + logs_traces + Traces of the log + all_activs + All the activities + noise_threshold + Noise threshold + + Returns + -------------- + rel + List of relations in the log + """ + ret0 = Counter() + for trace in logs_traces: + rs = Counter(trace_skel.equivalence(list(trace))) + for k in rs: + rs[k] = rs[k] * logs_traces[trace] + ret0 += rs + ret = set( + x + for x, y in ret0.items() + if y >= all_activs[x[0]] * (1.0 - noise_threshold) + ) + return ret + + +def always_after(logs_traces, all_activs, noise_threshold=0): + """ + Gets the always-after relations given the traces of the log + + Parameters + ------------- + logs_traces + Traces of the log + all_activs + All the activities + noise_threshold + Noise threshold + + Returns + -------------- + rel + List of relations in the log + """ + # logs_traces: Counter mapping each trace‐tuple → frequency + # First, for each A, count how many traces have A at all. + traces_with_A = Counter() + # For each (trace_variant → freq), check if A appears in that variant. + for trace_variant, freq in logs_traces.items(): + for act in trace_variant: + traces_with_A[act] += freq + + # Next, for each pair (A,B), count how many traces have B after A at least once. + traces_with_A_then_B = Counter() + for trace_variant, freq in logs_traces.items(): + # Build the set of all (A,B) such that B comes after A in this one variant + after_pairs = set(trace_skel.after(list(trace_variant))) + for (A,B) in after_pairs: + traces_with_A_then_B[(A,B)] += freq + + # Finally, keep only those (A,B) with + # traces_with_A_then_B[(A,B)] >= traces_with_A[A] * (1 - noise_threshold) + result = set() + for (A,B), count_AB in traces_with_A_then_B.items(): + if count_AB >= traces_with_A[A] * (1 - noise_threshold): + result.add((A,B)) + return result + + +def always_before(logs_traces, all_activs, noise_threshold=0): + """ + Gets the always-before relations given the traces of the log + + Parameters + ------------- + logs_traces + Traces of the log + all_activs + All the activities + noise_threshold + Noise threshold + + Returns + -------------- + rel + List of relations in the log + """ + traces_with_A = Counter() + for trace_variant, freq in logs_traces.items(): + for act in trace_variant: + traces_with_A[act] += freq + + traces_with_A_then_B = Counter() + for trace_variant, freq in logs_traces.items(): + before_pairs = set(trace_skel.before(list(trace_variant))) + for (A,B) in before_pairs: + traces_with_A_then_B[(A,B)] += freq + + result = set() + for (A,B), count_AB in traces_with_A_then_B.items(): + if count_AB >= traces_with_A[A] * (1 - noise_threshold): + result.add((A,B)) + return result + + +def never_together(logs_traces, all_activs, len_log, noise_threshold=0): + """ + Gets the never-together relations given the traces of the log + + Parameters + ------------- + logs_traces + Traces of the log + all_activs + All the activities + len_log + Length of the log + noise_threshold + Noise threshold + + Returns + -------------- + rel + List of relations in the log + """ + all_combos = set((x, y) for x in all_activs for y in all_activs if x != y) + ret0 = Counter() + for k in all_combos: + ret0[k] = all_activs[k[0]] + for trace in logs_traces: + rs = Counter(trace_skel.combos(list(trace))) + for k in rs: + rs[k] = rs[k] * logs_traces[trace] + ret0 -= rs + ret = set( + x + for x, y in ret0.items() + if y >= all_activs[x[0]] * (1.0 - noise_threshold) + ) + return ret + + +def directly_follows(logs_traces, all_activs, noise_threshold=0): + """ + Gets the allowed directly-follows relations given the traces of the log + + Parameters + ------------- + logs_traces + Traces of the log + all_activs + All the activities + noise_threshold + Noise threshold + + Returns + -------------- + rel + List of relations in the log + """ + ret0 = Counter() + for trace in logs_traces: + rs = Counter(trace_skel.directly_follows(list(trace))) + for k in rs: + rs[k] = rs[k] * logs_traces[trace] + ret0 += rs + ret = set( + x + for x, y in ret0.items() + if y >= all_activs[x[0]] * (1.0 - noise_threshold) + ) + return ret + + +def activ_freq(logs_traces, all_activs, len_log, noise_threshold=0): + """ + Gets the allowed activities frequencies given the traces of the log + + Parameters + ------------- + logs_traces + Traces of the log + all_activs + All the activities + len_log + Length of the log + noise_threshold + Noise threshold + + Returns + -------------- + rel + List of relations in the log + """ + ret0 = {} + ret = {} + for trace in logs_traces: + rs = trace_skel.activ_freq(trace) + for act in all_activs: + if act not in rs: + rs[act] = 0 + for act in rs: + if act not in ret0: + ret0[act] = Counter() + ret0[act][rs[act]] += logs_traces[trace] + for act in ret0: + ret0[act] = sorted( + list((x, y) for x, y in ret0[act].items()), + key=lambda x: x[1], + reverse=True, + ) + added = 0 + i = 0 + while i < len(ret0[act]): + added += ret0[act][i][1] + if added >= (1.0 - noise_threshold) * len_log: + ret0[act] = ret0[act][: min(i + 1, len(ret0[act]))] + i = i + 1 + ret[act] = set(x[0] for x in ret0[act]) + return ret + + +def apply( + log: Union[EventLog, pd.DataFrame], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """ + Discover a log skeleton from an event log + + Parameters + ------------- + log + Event log + parameters + Parameters of the algorithm, including: + - the activity key (Parameters.ACTIVITY_KEY) + - the noise threshold (Parameters.NOISE_THRESHOLD) + + Returns + ------------- + model + Log skeleton model + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + noise_threshold = exec_utils.get_param_value( + Parameters.NOISE_THRESHOLD, parameters, 0.0 + ) + + if type(log) is EventLog: + logs_traces = Counter([tuple(y[activity_key] for y in x) for x in log]) + all_activs = Counter(list(y[activity_key] for x in log for y in x)) + events_count = sum(len(x) for x in log) + elif pandas_utils.check_is_pandas_dataframe(log): + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, CASE_CONCEPT_NAME + ) + logs_traces = pandas_utils.get_traces(log, case_id_key, activity_key) + logs_traces = Counter(logs_traces) + all_activs = pandas_utils.get_attribute_values_count(log, activity_key) + events_count = pandas_utils.df_row_count(log) + + ret = {} + ret[Outputs.EQUIVALENCE.value] = equivalence( + logs_traces, all_activs, noise_threshold=noise_threshold + ) + ret[Outputs.ALWAYS_AFTER.value] = always_after( + logs_traces, all_activs, noise_threshold=noise_threshold + ) + ret[Outputs.ALWAYS_BEFORE.value] = always_before( + logs_traces, all_activs, noise_threshold=noise_threshold + ) + ret[Outputs.NEVER_TOGETHER.value] = never_together( + logs_traces, all_activs, events_count, noise_threshold=noise_threshold + ) + ret[Outputs.DIRECTLY_FOLLOWS.value] = directly_follows( + logs_traces, all_activs, noise_threshold=noise_threshold + ) + ret[Outputs.ACTIV_FREQ.value] = activ_freq( + logs_traces, all_activs, events_count, noise_threshold=noise_threshold + ) + + return ret + + +def apply_from_variants_list(var_list, parameters=None): + """ + Discovers the log skeleton from the variants list + + Parameters + --------------- + var_list + Variants list + parameters + Parameters + + Returns + --------------- + model + Log skeleton model + """ + if parameters is None: + parameters = {} + + log = EventLog() + for cv in var_list: + v = cv[0] + trace = variants_util.variant_to_trace(v, parameters=parameters) + log.append(trace) + + return apply(log, parameters=parameters) + + +def prepare_encode(log_skeleton): + """ + Prepares the log skeleton for encoding + + Parameters + -------------- + log_skeleton + Log skeleton + + Returns + -------------- + log_skeleton + Log skeleton (with lists instead of sets) + """ + log_skeleton[Outputs.EQUIVALENCE.value] = list( + log_skeleton[Outputs.EQUIVALENCE.value] + ) + log_skeleton[Outputs.ALWAYS_AFTER.value] = list( + log_skeleton[Outputs.ALWAYS_AFTER.value] + ) + log_skeleton[Outputs.ALWAYS_BEFORE.value] = list( + log_skeleton[Outputs.ALWAYS_BEFORE.value] + ) + log_skeleton[Outputs.NEVER_TOGETHER.value] = list( + log_skeleton[Outputs.NEVER_TOGETHER.value] + ) + log_skeleton[Outputs.DIRECTLY_FOLLOWS.value] = list( + log_skeleton[Outputs.DIRECTLY_FOLLOWS.value] + ) + for act in log_skeleton[Outputs.ACTIV_FREQ.value]: + log_skeleton[Outputs.ACTIV_FREQ.value][act] = list( + log_skeleton[Outputs.ACTIV_FREQ.value][act] + ) + return log_skeleton diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..832a169ad784f0e25dadf20fcd29533c6241c60e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/__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.algo.discovery.minimum_self_distance import ( + algorithm, + utils, + variants, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..837c68eb45dfce77c5e2bc8eb8dc870b77a0f016 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/algorithm.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 +''' +from enum import Enum +from typing import Union, Optional, Dict, Any + +import pandas as pd + +from pm4py.algo.discovery.minimum_self_distance.variants import log, pandas +from pm4py.objects.log.obj import EventLog, EventStream +from pm4py.util import exec_utils, pandas_utils +from pm4py.utils import is_polars_lazyframe +import importlib.util + +POLARS_AVAILABLE = importlib.util.find_spec("polars") is not None +if POLARS_AVAILABLE: + from pm4py.algo.discovery.minimum_self_distance.variants import polars + + +class Variants(Enum): + LOG = log + PANDAS = pandas + POLARS = polars if POLARS_AVAILABLE else log + + +def apply( + log_obj: Union[EventLog, pd.DataFrame, EventStream], + variant: Union[str, None] = None, + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, int]: + if parameters is None: + parameters = {} + + if variant is None: + if is_polars_lazyframe(log_obj): + if not POLARS_AVAILABLE: + raise RuntimeError( + "Polars LazyFrame provided but 'polars' package is not installed." + ) + variant = Variants.POLARS + elif pandas_utils.check_is_pandas_dataframe(log_obj): + variant = Variants.PANDAS + else: + variant = Variants.LOG + + return exec_utils.get_variant(variant).apply( + log_obj, parameters=parameters + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/utils.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fedfd2d21762ade3d546a9ae52ad66283d39a506 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/utils.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 enum import Enum +from typing import Any, Dict, Optional, Set, Union + +import pm4py +from pm4py.objects.conversion.log import converter +from pm4py.algo.discovery.minimum_self_distance import algorithm as msd_algo +from pm4py.objects.log.obj import EventLog +from pm4py.util import constants, exec_utils, xes_constants + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + + +def derive_msd_witnesses( + log: EventLog, + msd: Optional[Dict[Any, int]] = None, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Set[str]]: + """ + This function derives the minimum self distance witnesses. + The self distance of a in is infinity, of a in is 0, in is 1, etc. + The minimum self distance is the minimal observed self distance value in the event log. + A 'witness' is an activity that witnesses the minimum self distance. + For example, if the minimum self distance of activity a in some log L is 2, then, + if trace is in log L, b and c are a witness of a. + + Parameters + ---------- + log + Event Log to use + msd + Optional minimum self distance dictionary + parameters + Optional parameters dictionary + + Returns + ------- + Dictionary mapping each activity to a set of witnesses. + + """ + log = converter.apply( + log, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters + ) + act_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + alphabet = pm4py.get_event_attribute_values(log, act_key) + msd = msd if msd is not None else msd_algo.apply(log, parameters) + log = list(map(lambda t: list(map(lambda e: e[act_key], t)), log)) + witnesses = dict() + for a in alphabet: + if a in msd and msd[a] > 0: + witnesses[a] = set() + else: + continue + for t in log: + if len(list(filter(lambda e: e == a, t))) > 1: + indices = [i for i, x in enumerate(t) if x == a] + for i in range(len(indices) - 1): + if indices[i + 1] - indices[i] - 1 == msd[a]: + for b in t[indices[i] + 1: indices[i + 1]]: + witnesses[a].add(b) + return witnesses diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e88dda7fd2479ee70333652b5f25b32060949578 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/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.algo.discovery.minimum_self_distance.variants import log, pandas + +import importlib.util + +if importlib.util.find_spec("polars"): + from pm4py.algo.discovery.minimum_self_distance.variants import polars # type: ignore[F401] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/log.py new file mode 100644 index 0000000000000000000000000000000000000000..87ba9ed2aa016e7769f62695baa78350a8129528 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/log.py @@ -0,0 +1,112 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 Union, Dict, Optional, Any + +from pandas import DataFrame + +import pm4py +from pm4py.objects.conversion.log import converter +from pm4py.objects.log.obj import EventLog, EventStream +from pm4py.util import constants, exec_utils, xes_constants + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + + +def apply( + log: Union[DataFrame, EventLog, EventStream], + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, int]: + """ + This algorithm computes the minimum self-distance for each activity observed in an event log. + The self distance of a in is infinity, of a in is 0, in is 1, etc. + The minimum self distance is the minimal observed self distance value in the event log. + The activity key needs to be specified in the parameters input object (if None, default value 'concept:name' is used). + + + Parameters + ---------- + log + event log (either EventLog or EventStream) + parameters + parameters object; + + Returns + ------- + dict mapping an activity to its self-distance, if it exists, otherwise it is not part of the dict. + """ + log = converter.apply( + log, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters + ) + act_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + alphabet = pm4py.get_event_attribute_values(log, act_key) + log = list(map(lambda t: list(map(lambda e: e[act_key], t)), log)) + min_self_distances = dict() + for a in alphabet: + if ( + len( + list( + filter( + lambda t: len(t) > 1, + list( + map( + lambda t: list(filter(lambda e: e == a, t)), + log, + ) + ), + ) + ) + ) + > 0 + ): + activity_indices = list( + filter( + lambda t: len(t) > 1, + list( + map( + lambda t: [i for i, x in enumerate(t) if x == a], + log, + ) + ), + ) + ) + min_self_distances[a] = min( + [ + i + for l in list( + map( + lambda t: [ + t[i] - t[i - 1] - 1 + for i, x in enumerate(t) + if i > 0 + ], + activity_indices, + ) + ) + for i in l + ] + ) + return min_self_distances diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/pandas.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..d22af040d2181a35859f68e199a6206ddee8b725 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/pandas.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 enum import Enum +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY + + +CONCAT_ACT_CASE = "@@concat_act_case" +INT_CASE_ACT_SIZE = "@@int_case_act_size" +DIFF_INDEX = "@@diff_index" + + +def apply(df, parameters=None): + """ + This algorithm computes the minimum self-distance for each activity observed in an event log. + The self distance of a in is infinity, of a in is 0, in is 1, etc. + The minimum self distance is the minimal observed self distance value in the event log. + The activity key needs to be specified in the parameters input object (if None, default value 'concept:name' is used). + + + Parameters + ---------- + df + Pandas dataframe + parameters + parameters object; + + Returns + ------- + dict mapping an activity to its self-distance, if it exists, otherwise it is not part of the dict. + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + + df = df.copy() + df = df[list({activity_key, case_id_key})] + df = pandas_utils.insert_ev_in_tr_index( + df, + case_id=case_id_key, + column_name=constants.DEFAULT_INDEX_IN_TRACE_KEY, + ) + df[CONCAT_ACT_CASE] = df[case_id_key] + df[activity_key] + df[INT_CASE_ACT_SIZE] = df.groupby(CONCAT_ACT_CASE).cumcount() + df_last = df.groupby(CONCAT_ACT_CASE).last().reset_index() + df_last = df_last[df_last[INT_CASE_ACT_SIZE] > 0] + df = df[df[CONCAT_ACT_CASE].isin(df_last[CONCAT_ACT_CASE])] + df = df.merge(df, on=[activity_key, case_id_key], suffixes=("", "_2")) + df[DIFF_INDEX] = ( + df[constants.DEFAULT_INDEX_IN_TRACE_KEY + "_2"] + - df[constants.DEFAULT_INDEX_IN_TRACE_KEY] + - 1 + ) + df = df[df[DIFF_INDEX] >= 0] + ret = df.groupby(activity_key)[DIFF_INDEX].agg("min").to_dict() + return ret diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/polars.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/polars.py new file mode 100644 index 0000000000000000000000000000000000000000..9f99d06a9f6c32e58f697ef499abe8e75dd8181e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/minimum_self_distance/variants/polars.py @@ -0,0 +1,102 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 + +import importlib.util + +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils + + +class Parameters(Enum): + ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY + CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY + + +DIFF_INDEX = "@@diff_index" +NEXT_INDEX = "@@next_index" + + +def apply(df, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> Dict[str, int]: + if parameters is None: + parameters = {} + + 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] + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + + required_columns = {activity_key, case_id_key} + if hasattr(df, "collect_schema"): + df_columns = df.collect_schema().names() + else: + df_columns = df.columns + missing_columns = [col for col in required_columns if col not in df_columns] + if missing_columns: + raise Exception( + "The provided Polars LazyFrame does not contain the following required columns: " + + ", ".join(sorted(missing_columns)) + ) + + lf = df.select(list(required_columns)) + lf = pandas_utils.insert_ev_in_tr_index( + lf, + case_id=case_id_key, + column_name=constants.DEFAULT_INDEX_IN_TRACE_KEY, + ) + + lf = lf.sort([case_id_key, constants.DEFAULT_INDEX_IN_TRACE_KEY], maintain_order=True) + + lf = lf.with_columns( + pl.col(constants.DEFAULT_INDEX_IN_TRACE_KEY) + .shift(-1) + .over([case_id_key, activity_key]) + .alias(NEXT_INDEX) + ) + + lf = lf.with_columns( + (pl.col(NEXT_INDEX) - pl.col(constants.DEFAULT_INDEX_IN_TRACE_KEY) - 1).alias( + DIFF_INDEX + ) + ) + + lf = lf.filter(pl.col(DIFF_INDEX).is_not_null() & (pl.col(DIFF_INDEX) >= 0)) + + result = ( + lf.group_by(activity_key) + .agg(pl.col(DIFF_INDEX).min().alias(DIFF_INDEX)) + .collect() + ) + + return { + row[activity_key]: int(row[DIFF_INDEX]) + for row in result.iter_rows(named=True) + } diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f36ed07301889ca545d5e32fb45c55df73c1b95d --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/__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.discovery.ocel import interleavings, ocdfg, ocpn, link_analysis, saw_nets, otg, etot diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69bc05d98bbb6fefcfd1bc3e12ec8d181f57f908 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/__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.discovery.ocel.etot import variants, algorithm diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..6060e72d986e70622e23cf11bbc11f6ae4e60e5a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/algorithm.py @@ -0,0 +1,69 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 typing import Optional, Dict, Any, Tuple, Set +from pm4py.objects.ocel.obj import OCEL +from enum import Enum +from pm4py.util import exec_utils +from pm4py.algo.discovery.ocel.etot.variants import classic + + +class Variants(Enum): + CLASSIC = classic + + +def apply(ocel: OCEL, + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, + Any]] = None) -> Tuple[Set[str], + Set[str], + Set[Tuple[str, + str]], + Dict[Tuple[str, + str], + int]]: + """ + Discovers the ET-OT graph from an OCEL + + Published in: https://publications.rwth-aachen.de/record/1014107 + + Parameters + --------------- + ocel + Object-centric event log + variant + Variant of the algorithm to be used (available: Variants.CLASSIC) + parameters + Variant-specific parameters + + Returns + ---------------- + activities + Set of activities + object_types + Set of object types + edges + Set of edges + edges_frequency + Dictionary associating to each edge a frequency + """ + return exec_utils.get_variant(variant).apply(ocel, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a588364b1055afe376637fa67e1d79518ab4fccf --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/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.algo.discovery.ocel.etot.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..76bf3bb145eb6fee2e35e4b2a40022b10901c591 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/etot/variants/classic.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 collections import defaultdict +from typing import Optional, Dict, Any, Tuple, Set +from pm4py.objects.ocel.obj import OCEL + + +def apply(ocel: OCEL, + parameters: Optional[Dict[Any, + Any]] = None) -> Tuple[Set[str], + Set[str], + Set[Tuple[str, + str]], + Dict[Tuple[str, + str], + int]]: + """ + Discovers the ET-OT graph from an OCEL + + Published in: https://publications.rwth-aachen.de/record/1014107 + + Parameters + --------------- + ocel + Object-centric event log + parameters + Variant-specific parameters + + Returns + ---------------- + activities + Set of activities + object_types + Set of object types + edges + Set of edges + edges_frequency + Dictionary associating to each edge a frequency + """ + if parameters is None: + parameters = {} + + A = set() + OT = set() + R = set() + w = defaultdict(int) + + # Iterate over the relations to build the ETOT Graph + for index, row in ocel.relations.iterrows(): + a = row['ocel:activity'] + ot = row['ocel:type'] + A.add(a) + OT.add(ot) + R.add((a, ot)) + w[(a, ot)] += 1 + + return A, OT, R, w diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e8f6ee8ae4252ffdfeccbed492b856601c5f545 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/__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.discovery.ocel.interleavings import algorithm, variants, utils diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c25557847bc368d808e760655725295d10bb65 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/algorithm.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.algo.discovery.ocel.interleavings.variants import ( + timestamp_interleavings, +) +from enum import Enum +from pm4py.util import exec_utils +import pandas as pd +from typing import Optional, Dict, Any + + +class Variants(Enum): + TIMESTAMP_INTERLEAVINGS = timestamp_interleavings + + +def apply( + left_df: pd.DataFrame, + right_df: pd.DataFrame, + case_relations: pd.DataFrame, + variant=Variants.TIMESTAMP_INTERLEAVINGS, + parameters: Optional[Dict[Any, Any]] = None, +): + """ + Discover the interleavings between two dataframes, given also a dataframe about the relations of the cases. + + Parameters + ----------------- + left_df + Left dataframe + right_df + Right dataframe + case_relations + Dictionary associating the cases of the first dataframe (column: case:concept:name_LEFT) to the + cases of the second dataframe (column: case:concept:name_RIGHT) + variant + Variant of the algorithm to be used, possible values: + - Variants.TIMESTAMP_INTERLEAVINGS + parameters + Variant-specific parameters + + Returns + ----------------- + interleavings + Interleavings dataframe + """ + return exec_utils.get_variant(variant).apply( + left_df, right_df, case_relations, parameters + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c04cf30bb485058c4fc9ef9dae9136a8814f3dbe --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/utils/__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.algo.discovery.ocel.interleavings.utils import ( + merge_dataframe_rel_cases, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/utils/merge_dataframe_rel_cases.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/utils/merge_dataframe_rel_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..e7025f1c121e58ce4a846cb4ad593347f4905199 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/utils/merge_dataframe_rel_cases.py @@ -0,0 +1,155 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General 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 enum import Enum +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils +from pm4py.objects.log.util import dataframe_utils +from copy import copy + + +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 + LEFT_SUFFIX = "left_suffix" + RIGHT_SUFFIX = "right_suffix" + INDEX_KEY = "index_key" + + +def directly_follows_dataframe( + dataframe: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None +): + """ + Calculates the directly-follows dataframe (internal usage) + """ + if parameters is None: + parameters = {} + + 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 + ) + 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]) + + dataframe = pandas_utils.insert_index(dataframe, index_key) + + insert_parameters = copy(parameters) + insert_parameters["use_extremes_timestamp"] = True + + dataframe = dataframe_utils.insert_artificial_start_end( + dataframe, parameters=insert_parameters + ) + + df_shifted = dataframe.shift(-1) + df_shifted.columns = [x + "_2" for x in df_shifted.columns] + dataframe = pandas_utils.concat([dataframe, df_shifted], axis=1) + dataframe = dataframe[ + dataframe[case_id_key] == dataframe[case_id_key + "_2"] + ] + + return dataframe + + +def merge_dataframes( + left_df: pd.DataFrame, + right_df: pd.DataFrame, + case_relations: pd.DataFrame, + parameters: Optional[Dict[Any, Any]] = None, +): + """ + Merge the two dataframes based on the provided case relations + + Parameters + ----------------- + left_df + First dataframe to merge + right_df + Second dataframe to merge + case_relations + Dictionary associating the cases of the first dataframe (column: case:concept:name_LEFT) to the + cases of the second dataframe (column: case:concept:name_RIGHT) + parameters + Parameters of the algorithm, including: + - Parameters.CASE_ID_KEY => the case ID + - Parameters.LEFT_SUFFIX => the suffix for the columns of the left dataframe + - Parameters.RIGHT_SUFFIX => the suffix for the columns of the right dataframe + + Returns + ------------------ + merged_df + Merged dataframe + """ + if parameters is None: + parameters = {} + + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME + ) + left_suffix = exec_utils.get_param_value( + Parameters.LEFT_SUFFIX, parameters, "_LEFT" + ) + right_suffix = exec_utils.get_param_value( + Parameters.RIGHT_SUFFIX, parameters, "_RIGHT" + ) + + left_df = directly_follows_dataframe(left_df, parameters=parameters) + right_df = directly_follows_dataframe(right_df, parameters=parameters) + + left_df = left_df.merge( + case_relations, + left_on=case_id_key, + right_on=case_id_key + left_suffix, + suffixes=("", ""), + ) + del left_df[case_id_key + left_suffix] + + # Rename the right-case column coming from relations to avoid clashing with + # the suffix that will be assigned to the right dataframe case column. + merge_key = case_id_key + right_suffix + if merge_key in left_df.columns: + renamed_merge_key = merge_key + "_REL" + left_df = left_df.rename(columns={merge_key: renamed_merge_key}) + merge_key = renamed_merge_key + + left_df = left_df.merge( + right_df, + left_on=merge_key, + right_on=case_id_key, + suffixes=(left_suffix, right_suffix), + ) + + if merge_key in left_df.columns and merge_key.endswith("_REL"): + del left_df[merge_key] + + return left_df diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc289f301a83b808abdf0eb7822f007923fa7f3b --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/variants/__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.algo.discovery.ocel.interleavings.variants import ( + timestamp_interleavings, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/variants/timestamp_interleavings.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/variants/timestamp_interleavings.py new file mode 100644 index 0000000000000000000000000000000000000000..098a40f6e0622ef19861d2f2b4222e5827d93c39 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/interleavings/variants/timestamp_interleavings.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 +''' +from pm4py.algo.discovery.ocel.interleavings.utils import ( + merge_dataframe_rel_cases, +) +import pandas as pd +from typing import Optional, Dict, Any +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils +from enum import Enum + + +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 + LEFT_SUFFIX = "left_suffix" + RIGHT_SUFFIX = "right_suffix" + INDEX_KEY = "index_key" + SOURCE_ACTIVITY = "source_activity_param" + TARGET_ACTIVITY = "target_activity_param" + SOURCE_TIMESTAMP = "source_timestamp_param" + TARGET_TIMESTAMP = "target_timestamp_param" + LEFT_INDEX = "left_index_param" + RIGHT_INDEX = "right_index_param" + DIRECTION = "direction_param" + TIMESTAMP_DIFF = "timestamp_diff" + + +def apply( + left_df: pd.DataFrame, + right_df: pd.DataFrame, + case_relations: pd.DataFrame, + parameters: Optional[Dict[Any, Any]] = None, +): + """ + Calculates the timestamp-based interleavings ongoing from the left/right to the right/left dataframe. + + Parameters + ------------------ + left_df + Left dataframe + right_df + Right dataframe + case_relations + Dictionary associating the cases of the first dataframe (column: case:concept:name_LEFT) to the + cases of the second dataframe (column: case:concept:name_RIGHT) + 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.LEFT_SUFFIX => the suffix for the columns of the left dataframe + - Parameters.RIGHT_SUFFIX => the suffix for the columns of the right dataframe + - Parameters.INDEX_KEY => the index column in the dataframe + - Parameters.SOURCE_ACTIVITY => the source activity of the interleaving + - Parameters.TARGET_ACTIVITY => the target activity of the interleaving + - Parameters.SOURCE_TIMESTAMP => the source timestamp of the interleaving + - Parameters.TARGET_TIMESTAMP => the target timestamp of the interleaving + - Parameters.LEFT_INDEX => the index of the event of the left-dataframe in the interleaving + - Parameters.RIGHT_INDEX => the index of the event of the right-dataframe in the interleaving + - Parameters.DIRECTION => the direction of the interleaving (LR: left to right; RL: right to left) + - Parameters.TIMESTAMP_DIFF => the difference between the timestamps of the interleaving + + Returns + ----------------- + interleavings_dataframe + Sorted interleaving dataframe + """ + if parameters is None: + parameters = {} + + 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 + ) + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY + ) + left_suffix = exec_utils.get_param_value( + Parameters.LEFT_SUFFIX, parameters, "_LEFT" + ) + right_suffix = exec_utils.get_param_value( + Parameters.RIGHT_SUFFIX, parameters, "_RIGHT" + ) + source_activity = exec_utils.get_param_value( + Parameters.SOURCE_ACTIVITY, parameters, "@@source_activity" + ) + target_activity = exec_utils.get_param_value( + Parameters.TARGET_ACTIVITY, parameters, "@@target_activity" + ) + source_timestamp = exec_utils.get_param_value( + Parameters.SOURCE_TIMESTAMP, parameters, "@@source_timestamp" + ) + target_timestamp = exec_utils.get_param_value( + Parameters.TARGET_TIMESTAMP, parameters, "@@target_timestamp" + ) + direction = exec_utils.get_param_value( + Parameters.DIRECTION, parameters, "@@direction" + ) + timestamp_diff = exec_utils.get_param_value( + Parameters.TIMESTAMP_DIFF, parameters, "@@timestamp_diff" + ) + 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" + ) + + md = merge_dataframe_rel_cases.merge_dataframes( + left_df, right_df, case_relations, parameters=parameters + ) + + df1 = md[ + md[timestamp_key + left_suffix] < md[timestamp_key + right_suffix] + ] + df1 = df1[ + df1[timestamp_key + right_suffix] + < df1[timestamp_key + "_2" + left_suffix] + ] + df1 = df1[ + df1[timestamp_key + "_2" + left_suffix] + < df1[timestamp_key + "_2" + right_suffix] + ] + df1[source_activity] = df1[activity_key + left_suffix] + df1[target_activity] = df1[activity_key + right_suffix] + df1[source_timestamp] = df1[timestamp_key + left_suffix] + df1[target_timestamp] = df1[timestamp_key + right_suffix] + df1[left_index] = df1[index_key + left_suffix] + df1[right_index] = df1[index_key + right_suffix] + df1[direction] = "LR" + + df2 = md[ + md[timestamp_key + right_suffix] < md[timestamp_key + left_suffix] + ] + df2 = df2[ + df2[timestamp_key + left_suffix] + < df2[timestamp_key + "_2" + right_suffix] + ] + df2 = df2[ + df2[timestamp_key + "_2" + right_suffix] + < df2[timestamp_key + "_2" + left_suffix] + ] + df2[source_activity] = df2[activity_key + "_2" + right_suffix] + df2[target_activity] = df2[activity_key + "_2" + left_suffix] + df2[source_timestamp] = df2[timestamp_key + "_2" + right_suffix] + df2[target_timestamp] = df2[timestamp_key + "_2" + left_suffix] + df2[left_index] = df2[index_key + "_2" + left_suffix] + df2[right_index] = df2[index_key + "_2" + right_suffix] + df2[direction] = "RL" + + md = pandas_utils.concat([df1, df2]) + md = md.sort_values([index_key + left_suffix, index_key + right_suffix]) + md[timestamp_diff] = pandas_utils.get_total_seconds( + md[target_timestamp] - md[source_timestamp] + ) + + return md diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08700121c13440a7a46582e827014f5e7bd7cec2 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/__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.discovery.ocel.link_analysis import variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..47616b23b555bde58c60394369c282731e0ff125 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/algorithm.py @@ -0,0 +1,68 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.ocel.link_analysis.variants import classic +from enum import Enum +from pm4py.util import exec_utils +import pandas as pd +from typing import Optional, Dict, Any +from pm4py.objects.log.obj import EventLog, EventStream +from typing import Union +from pm4py.objects.conversion.log import converter + + +class Variants(Enum): + CLASSIC = classic + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> pd.DataFrame: + """ + Applies a link analysis algorithm on the provided log object. + + Parameters + ----------------- + log + Event log + variant + Variant of the algorithm to consider + parameters + Variant-specific parameters + + Returns + ----------------- + link_analysis_dataframe + Link analysis dataframe + """ + if parameters is None: + parameters = {} + + return exec_utils.get_variant(variant).apply( + converter.apply( + log, + variant=converter.Variants.TO_DATA_FRAME, + parameters=parameters, + ), + parameters=parameters, + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc7b3456db73490017846e4d766fcbc91103256 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/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.algo.discovery.ocel.link_analysis.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..67899698e5c1ceec18cc173fd5e79d0cb0490562 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/link_analysis/variants/classic.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 +''' +from enum import Enum + +from pm4py.util import exec_utils, constants, xes_constants, pandas_utils +from typing import Optional, Dict, Any, Set +import pandas as pd + + +class Parameters(Enum): + OUT_COLUMN = "out_column" + IN_COLUMN = "in_column" + SORTING_COLUMN = "sorting_column" + INDEX_COLUMN = "index_column" + LOOK_FORWARD = "look_forward" + KEEP_FIRST_OCCURRENCE = "keep_first_occurrence" + PROPAGATE = "propagate" + + +def propagate_associations( + associations: Dict[str, Set[str]] +) -> Dict[str, Set[str]]: + """ + Propagate the associations, such that the eventually-follows + flow between the events of the event log is considered + + Parameters + ------------------- + associations + Associations between events + + Returns + ------------------ + propagated_associations + Propagated associations + """ + reverse_dict = {} + for x in associations: + for k in associations[x]: + if k not in reverse_dict: + reverse_dict[k] = set() + reverse_dict[k].add(x) + change_dict = {x: True for x in associations} + to_change = [x for x in change_dict if change_dict[x]] + while to_change: + for x in to_change: + change_dict[x] = False + for x in to_change: + if x in reverse_dict: + rv = reverse_dict[x] + for k in rv: + new_set = associations[k].union(associations[x]) + if len(new_set) > len(associations[k]): + change_dict[k] = True + associations[k] = new_set + to_change = [x for x in change_dict if change_dict[x]] + return associations + + +def apply( + dataframe: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None +) -> pd.DataFrame: + """ + Performs a link analysis between the entries of the current dataframe. + The link analysis permits advanced filtering based on events connected in an + output-input relation (e.g., the OUT column of the first is equal to the IN column + of the second). + + When OUT_COLUMN = IN_COLUMN = CASE ID, it can be equivalent to the directly-follows graph + (when Parameters.KEEP_FIRST_OCCURRENCE = True), and to the eventually-follows graph + (when Parameters.KEEP_FIRST_OCCURRENCE = False). + + Parameters + ----------------- + dataframe + Pandas dataframe + parameters + Parameters of the algorithm, including: + - Parameters.OUT_COLUMN => the output column of the dataframe + - Parameters.IN_COLUMN => the input column of the dataframe + - Parameters.SORTING_COLUMN => the column on top of which the + - Parameters.INDEX_COLUMN => the attribute to use for the indexing + - Parameters.LOOK_FORWARD => filters the relations in which the second event has an index >= than the index + of the first event. + - Parameters.KEEP_FIRST_OCCURRENCE => keep, for every source event, only the first-occurring relationship + with a target event (OUT=IN). + - Parameters.PROPAGATE => propagate the relationships between events, in such a way that the entire document + flow chain can be reconstructed. + + Returns + ----------------- + link_analysis_dataframe + Link analysis dataframe + """ + if parameters is None: + parameters = {} + + out_column = exec_utils.get_param_value( + Parameters.OUT_COLUMN, parameters, constants.CASE_CONCEPT_NAME + ) + in_column = exec_utils.get_param_value( + Parameters.IN_COLUMN, parameters, constants.CASE_CONCEPT_NAME + ) + sorting_column = exec_utils.get_param_value( + Parameters.SORTING_COLUMN, + parameters, + xes_constants.DEFAULT_TIMESTAMP_KEY, + ) + index_column = exec_utils.get_param_value( + Parameters.INDEX_COLUMN, parameters, constants.DEFAULT_INDEX_KEY + ) + look_forward = exec_utils.get_param_value( + Parameters.LOOK_FORWARD, parameters, True + ) + keep_first_occurrence = exec_utils.get_param_value( + Parameters.KEEP_FIRST_OCCURRENCE, parameters, False + ) + propagate = exec_utils.get_param_value( + Parameters.PROPAGATE, parameters, False + ) + + dataframe = dataframe.sort_values(sorting_column) + dataframe = pandas_utils.insert_index(dataframe, index_column) + + df_red1 = dataframe[[out_column, index_column]] + df_red2 = dataframe[[in_column, index_column]] + df_red = df_red1.merge( + df_red2, + left_on=out_column, + right_on=in_column, + suffixes=("_out", "_in"), + ) + + if look_forward: + df_red = df_red[ + df_red[index_column + "_out"] < df_red[index_column + "_in"] + ] + + if keep_first_occurrence: + df_red = df_red.groupby(index_column + "_out").first().reset_index() + + stream_red = df_red.to_dict(orient="records") + associations = {} + for el in stream_red: + if el[index_column + "_out"] not in associations: + associations[el[index_column + "_out"]] = set() + associations[el[index_column + "_out"]].add(el[index_column + "_in"]) + + if propagate: + associations = propagate_associations(associations) + + out_clmn = [] + in_clmn = [] + for k in associations: + for v in associations[k]: + out_clmn.append(k) + in_clmn.append(v) + + rel = pandas_utils.instantiate_dataframe( + {index_column + "_out": out_clmn, index_column + "_in": in_clmn} + ) + + df_link = dataframe.copy() + df_link.columns = [x + "_out" for x in df_link.columns] + df_link = df_link.merge( + rel, left_on=index_column + "_out", right_on=index_column + "_out" + ) + dataframe.columns = [x + "_in" for x in dataframe.columns] + df_link = df_link.merge( + dataframe, left_on=index_column + "_in", right_on=index_column + "_in" + ) + + return df_link diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7de954f1a0a45abd5cd8e173d2c9ef541ffcd368 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/__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.discovery.ocel.ocdfg import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..4e2f40a69e1a8289e4327a2ff0ae51909b004417 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/algorithm.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 +''' +from pm4py.objects.ocel.obj import OCEL +from typing import Optional, Dict, Any +from pm4py.algo.discovery.ocel.ocdfg.variants import classic +from enum import Enum +from pm4py.util import exec_utils + + +class Variants(Enum): + CLASSIC = classic + + +def apply( + ocel: OCEL, + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Any]: + """ + Discovers an OC-DFG model from an object-centric event log + 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. + + Parameters + ---------------- + ocel + Object-centric event log + variant + Variant of the algorithm to use: + - Variants.CLASSIC + parameters + Variant-specific parameters + + Returns + ---------------- + ocdfg + Object-centric directly-follows graph + """ + return exec_utils.get_variant(variant).apply(ocel, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c02de3ac4ade6495a95b628daa546a6ab2e4234 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/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.algo.discovery.ocel.ocdfg.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5eee975478bc90b2f7054e4e68b2ad0fe3584c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocdfg/variants/classic.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 typing import Optional, Dict, Any +from enum import Enum +from pm4py.util import exec_utils, pandas_utils +from pm4py.objects.ocel import constants as ocel_constants +from pm4py.objects.ocel.obj import OCEL +from pm4py.statistics.ocel import act_ot_dependent, act_utils, edge_metrics + + +class Parameters(Enum): + EVENT_ID = ocel_constants.PARAM_EVENT_ID + EVENT_ACTIVITY = ocel_constants.PARAM_EVENT_ACTIVITY + EVENT_TIMESTAMP = ocel_constants.PARAM_EVENT_TIMESTAMP + OBJECT_ID = ocel_constants.PARAM_OBJECT_ID + OBJECT_TYPE = ocel_constants.PARAM_OBJECT_TYPE + COMPUTE_EDGES_PERFORMANCE = "compute_edges_performance" + BUSINESS_HOURS = "business_hours" + BUSINESS_HOUR_SLOTS = "business_hour_slots" + WORKCALENDAR = "workcalendar" + + +def apply( + ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None +) -> Dict[str, Any]: + """ + Discovers an OC-DFG model from an object-centric event log. + 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. + + Parameters + ----------------- + ocel + Object-centric event log + parameters + Parameters of the algorithm, including: + - Parameters.EVENT_ID => the attribute to be used as event identifier + - Parameters.EVENT_ACTIVITY => the attribute to be used as activity + - Parameters.EVENT_TIMESTAMP => the attribute to be used as timestamp + - Parameters.OBJECT_ID => the attribute to be used as object identifier + - Parameters.OBJECT_TYPE => the attribute to be used as object type + - Parameters.COMPUTE_EDGES_PERFORMANCE => (boolean) enables/disables the computation of the performance on the edges + - Parameters.BUSINESS_HOURS => enables/disables business-hour edge performance + - Parameters.BUSINESS_HOUR_SLOTS => work schedule of the company + - Parameters.WORKCALENDAR => work calendar to use when business hours are enabled + + Returns + ----------------- + ocdfg + 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 + """ + if parameters is None: + parameters = {} + + # Extract parameter values once + 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 + ) + compute_edges_performance = exec_utils.get_param_value( + Parameters.COMPUTE_EDGES_PERFORMANCE, parameters, True + ) + + # Pre-compute activities and object types (used multiple times) + activities = set(pandas_utils.format_unique(ocel.events[event_activity].unique())) + object_types = set(pandas_utils.format_unique(ocel.objects[object_type].unique())) + + # Initialize result dictionary with pre-computed values + ret = { + "activities": activities, + "object_types": object_types, + "edges": {}, + "activities_indep": {}, + "activities_ot": {}, + "start_activities": {}, + "end_activities": {}, + "edges_performance": {"event_couples": {}, "total_objects": {}} + } + + # Process object-type independent associations (shared computation) + ot_independent = act_utils.find_associations_from_ocel( + ocel, parameters=parameters + ) + ret["activities_indep"] = { + "events": act_utils.aggregate_events(ot_independent), + "unique_objects": act_utils.aggregate_unique_objects(ot_independent), + "total_objects": act_utils.aggregate_total_objects(ot_independent) + } + + # Process object-type dependent associations (shared computation) + ot_dependent = act_ot_dependent.find_associations_from_ocel( + ocel, parameters=parameters + ) + ret["activities_ot"] = { + "events": act_ot_dependent.aggregate_events(ot_dependent), + "unique_objects": act_ot_dependent.aggregate_unique_objects(ot_dependent), + "total_objects": act_ot_dependent.aggregate_total_objects(ot_dependent) + } + + # Process start activities + start_parameters = {**parameters, "prefiltering": "start"} + ot_dependent_start = act_ot_dependent.find_associations_from_ocel( + ocel, parameters=start_parameters + ) + ret["start_activities"] = { + "events": act_ot_dependent.aggregate_events(ot_dependent_start), + "unique_objects": act_ot_dependent.aggregate_unique_objects(ot_dependent_start), + "total_objects": act_ot_dependent.aggregate_total_objects(ot_dependent_start) + } + + # Process end activities + end_parameters = {**parameters, "prefiltering": "end"} + ot_dependent_end = act_ot_dependent.find_associations_from_ocel( + ocel, parameters=end_parameters + ) + ret["end_activities"] = { + "events": act_ot_dependent.aggregate_events(ot_dependent_end), + "unique_objects": act_ot_dependent.aggregate_unique_objects(ot_dependent_end), + "total_objects": act_ot_dependent.aggregate_total_objects(ot_dependent_end) + } + + # Process edges + edges = edge_metrics.find_associations_per_edge( + ocel, parameters=end_parameters + ) + ret["edges"] = { + "event_couples": edge_metrics.aggregate_ev_couples(edges), + "unique_objects": edge_metrics.aggregate_unique_objects(edges), + "total_objects": edge_metrics.aggregate_total_objects(edges) + } + + # Only compute performance metrics if needed + if compute_edges_performance: + ret["edges_performance"] = { + "event_couples": edge_metrics.performance_calculation_ocel_aggregation( + ocel, ret["edges"]["event_couples"], parameters=parameters + ), + "total_objects": edge_metrics.performance_calculation_ocel_aggregation( + ocel, ret["edges"]["total_objects"], parameters=parameters + ) + } + + return ret diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7434bb175fefdfd4609eca000b22cd408df0f0b9 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/__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.discovery.ocel.ocpn import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..58ebb039f72d9061149649d4e2a5496ab3184145 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/algorithm.py @@ -0,0 +1,59 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.algo.discovery.ocel.ocpn.variants import classic +from pm4py.objects.ocel.obj import OCEL +from pm4py.objects.ocpn.obj import OCPetriNet +from pm4py.util import exec_utils +from typing import Optional, Dict, Any + + +class Variants(Enum): + WO_ANNOTATION = classic + CLASSIC = classic + + +def apply( + ocel: OCEL, + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> 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. + + Parameters + ----------------- + ocel + Object-centric event log + variant + Variant of the algorithm to be used + parameters + Variant-specific parameters + + Returns + ---------------- + ocpn + Object-centric Petri net model. + """ + return exec_utils.get_variant(variant).apply(ocel, parameters=parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76247fb222ad78993bfb1becba20eff974dc9e2f --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/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.algo.discovery.ocel.ocpn.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..9db2959d77f8bec0a8a71fee18b6b99d2fcbd972 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/classic.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.obj import OCEL +from pm4py.algo.discovery.ocel.ocdfg.variants import classic as ocdfg_discovery +from pm4py.algo.discovery.inductive import algorithm as inductive_miner +from enum import Enum +from pm4py.util import exec_utils +from pm4py.objects.ocel import constants as ocel_constants +from collections import Counter +from typing import Optional, Dict, Any +from pm4py.objects.dfg.obj import DFG +from pm4py.objects.conversion.process_tree import converter as tree_converter +from pm4py.algo.conformance.tokenreplay import algorithm as token_based_replay +from pm4py.objects.ocel.util import flattening +from pm4py.objects.ocpn.obj import OCPetriNet +from pm4py.objects.ocpn import factory as ocpn_factory +from copy import copy + + +class Parameters(Enum): + EVENT_ACTIVITY = ocel_constants.PARAM_EVENT_ACTIVITY + OBJECT_ID = ocel_constants.PARAM_OBJECT_ID + OBJECT_TYPE = ocel_constants.PARAM_OBJECT_TYPE + INDUCTIVE_MINER_VARIANT = "inductive_miner_variant" + NOISE_THRESHOLD = "noise_threshold" + MULTIPROCESSING = "multiprocessing" + DISABLE_FALLTHROUGHS = "disable_fallthroughs" + DISABLE_STRICT_SEQUENCE_CUT = "disable_strict_sequence_cut" + DOUBLE_ARC_THRESHOLD = "double_arc_threshold" + DIAGNOSTICS_WITH_TBR = "diagnostics_with_token_based_replay" + + +def apply( + ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None +) -> OCPetriNet: + """ + Discovers an object-centric Petri net (without annotation) from the + given object-centric event log, using the Inductive Miner as process + discovery algorithm. + + Reference paper: van der Aalst, Wil MP, and Alessandro Berti. "Discovering object-centric Petri nets." Fundamenta informaticae 175.1-4 (2020): 1-40. + + Parameters + ---------- + ocel + Object-centric event log + parameters + Parameters of the algorithm, including: + + - Parameters.EVENT_ACTIVITY => the activity attribute to be used + - Parameters.OBJECT_ID => the object identifier attribute to be used + - Parameters.OBJECT_TYPE => the object type attribute to be used + - Parameters.INDUCTIVE_MINER_VARIANT => variant of the inductive miner to use ("im", "imf", or "imd") + - Parameters.NOISE_THRESHOLD => noise threshold for the inductive miner + - Parameters.MULTIPROCESSING => enables/disables multiprocessing in the inductive miner + - Parameters.DISABLE_FALLTHROUGHS => disables the inductive miner fall-throughs + - Parameters.DISABLE_STRICT_SEQUENCE_CUT => disables the strict sequence cut in the inductive miner + - Parameters.DOUBLE_ARC_THRESHOLD => the threshold for the attribution of the "double arc", as described in the paper. + - Parameters.DIAGNOSTICS_WITH_TBR => performs token-based replay and stores the result in the return dict + + Returns + ----------------- + ocpn + Object-centric Petri net model. The returned object preserves the + legacy dictionary payload for retro-compatibility with code that still + accesses keys such as ``ocpn["petri_nets"]``. + + """ + if parameters is None: + parameters = {} + + double_arc_threshold = exec_utils.get_param_value( + Parameters.DOUBLE_ARC_THRESHOLD, parameters, 0.8 + ) + inductive_miner_variant = exec_utils.get_param_value( + Parameters.INDUCTIVE_MINER_VARIANT, parameters, "im" + ).lower() + noise_threshold = exec_utils.get_param_value( + Parameters.NOISE_THRESHOLD, parameters, 0.0 + ) + diagnostics_with_tbr = exec_utils.get_param_value( + Parameters.DIAGNOSTICS_WITH_TBR, parameters, False + ) + 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 + ) + + ocdfg_parameters = copy(parameters) + ocdfg_parameters["compute_edges_performance"] = False + ocpn = ocdfg_discovery.apply(ocel, parameters=ocdfg_parameters) + activity_event_counts = Counter(ocel.events[event_activity]) + object_ids = { + ot: set(ot_relations[object_id].unique()) + for ot, ot_relations in ocel.relations.groupby(object_type) + } + for ot in ocpn["object_types"]: + object_ids.setdefault(ot, set()) + + petri_nets = {} + double_arcs_on_activity = {} + tbr_results = {} + + for ot in ocpn["object_types"]: + activities_eo = ocpn["activities_ot"]["total_objects"][ot] + + start_activities = { + x: len(y) + for x, y in ocpn["start_activities"]["events"][ot].items() + } + end_activities = { + x: len(y) for x, y in ocpn["end_activities"]["events"][ot].items() + } + dfg = {} + if ot in ocpn["edges"]["event_couples"]: + dfg = { + x: len(y) + for x, y in ocpn["edges"]["event_couples"][ot].items() + } + + is_activity_double = {} + for act in activities_eo: + ev_obj_count = Counter([x[0] for x in activities_eo[act]]) + single_object_events = 0 + for y in ev_obj_count.values(): + if y == 1: + single_object_events += 1 + + total_activity_events = activity_event_counts[act] + score = ( + single_object_events / total_activity_events + if total_activity_events + else 0 + ) + + if score < double_arc_threshold: + is_activity_double[act] = True + else: + is_activity_double[act] = False + + double_arcs_on_activity[ot] = is_activity_double + + im_parameters = copy(parameters) + im_parameters["noise_threshold"] = noise_threshold + # Historical OCPN discovery defaults disable these expensive inductive + # miner paths, but caller-provided values should take precedence. + im_parameters["disable_fallthroughs"] = exec_utils.get_param_value( + Parameters.DISABLE_FALLTHROUGHS, parameters, True + ) + im_parameters["disable_strict_sequence_cut"] = ( + exec_utils.get_param_value( + Parameters.DISABLE_STRICT_SEQUENCE_CUT, parameters, True + ) + ) + if ( + Parameters.MULTIPROCESSING.value in parameters + or Parameters.MULTIPROCESSING in parameters + ): + im_parameters["multiprocessing"] = exec_utils.get_param_value( + Parameters.MULTIPROCESSING, parameters, False + ) + + process_tree = None + flat_log = None + + if inductive_miner_variant in ["im", "imf"] or diagnostics_with_tbr: + # do the flattening only if it is required + flat_log = flattening.flatten(ocel, ot, parameters=parameters) + + if inductive_miner_variant == "imd": + obj = DFG() + obj._graph = Counter(dfg) + obj._start_activities = Counter(start_activities) + obj._end_activities = Counter(end_activities) + process_tree = inductive_miner.apply( + obj, + variant=inductive_miner.Variants.IMd, + parameters=im_parameters, + ) + elif inductive_miner_variant in ["im", "imf"]: + variant = ( + inductive_miner.Variants.IMf + if inductive_miner_variant == "imf" or noise_threshold > 0 + else inductive_miner.Variants.IM + ) + process_tree = inductive_miner.apply( + flat_log, variant=variant, parameters=im_parameters + ) + + petri_net = tree_converter.apply(process_tree, parameters=parameters) + + if diagnostics_with_tbr: + tbr_parameters = copy(parameters) + tbr_parameters["enable_pltr_fitness"] = True + tbr_parameters["show_progress_bar"] = False + + ( + replayed_traces, + place_fitness_per_trace, + transition_fitness_per_trace, + notexisting_activities_in_model, + ) = token_based_replay.apply( + flat_log, + petri_net[0], + petri_net[1], + petri_net[2], + parameters=tbr_parameters, + ) + place_diagnostics = { + place: {"m": 0, "r": 0, "c": 0, "p": 0} + for place in place_fitness_per_trace + } + trans_count = {trans: 0 for trans in petri_net[0].transitions} + # computes the missing, remaining, consumed, and produced tokens + # per place. + for place, res in place_fitness_per_trace.items(): + place_diagnostics[place]["m"] += res["m"] + place_diagnostics[place]["r"] += res["r"] + place_diagnostics[place]["c"] += res["c"] + place_diagnostics[place]["p"] += res["p"] + + # counts the number of times a transition has been fired during the + # replay. + for trace in replayed_traces: + for trans in trace["activated_transitions"]: + trans_count[trans] += 1 + + tbr_results[ot] = (place_diagnostics, trans_count) + + petri_nets[ot] = petri_net + + ocpn["petri_nets"] = petri_nets + ocpn["double_arcs_on_activity"] = double_arcs_on_activity + ocpn["object_ids"] = object_ids + ocpn["tbr_results"] = tbr_results + + return ocpn_factory.create(ocpn) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/wo_annotation.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/wo_annotation.py new file mode 100644 index 0000000000000000000000000000000000000000..3150646818e37d93f7b48f6278deddcae6d6d302 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/ocpn/variants/wo_annotation.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.algo.discovery.ocel.ocpn.variants.classic import * + +# renamed diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d06cf75c3a6d73e675e5be3a14fafa66f234082a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/__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.discovery.ocel.otg import variants, algorithm diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..383d06d5620d430b20b4e7f1d62d20c998746aa1 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/algorithm.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.algo.discovery.ocel.otg.variants import classic +from enum import Enum +from pm4py.util import exec_utils +from pm4py.objects.ocel.obj import OCEL +from typing import Optional, Dict, Any, Tuple, Set + + +class Variants(Enum): + CLASSIC = classic + + +def apply(ocel: OCEL, + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, + Any]] = None) -> Tuple[Set[str], + Dict[Tuple[str, + str, + str], + int]]: + """ + Discovers an OTG (object-type-graph) from the provided OCEL + + Published in: https://publications.rwth-aachen.de/record/1014107 + + Parameters + ----------------- + ocel + OCEL + variant + Variant to be used (available: Variants.CLASSIC) + parameters + Variant-specific parameters + + Returns + ----------------- + otg + Object-type-graph (tuple; the first element is the set of object types, the second element is the OTG) + """ + if parameters is None: + parameters = {} + + return exec_utils.get_variant(variant).apply(ocel, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66d87603b00b18b24b6deef4e802132928f09c81 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/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.algo.discovery.ocel.otg.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..ce793266633c3318bc7b3b0bd40727c0d0570de9 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/otg/variants/classic.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 collections import defaultdict +from pm4py.objects.ocel.obj import OCEL +from typing import Optional, Dict, Any, Tuple, Set + + +def apply(ocel: OCEL, + parameters: Optional[Dict[Any, + Any]] = None) -> Tuple[Set[str], + Dict[Tuple[str, + str, + str], + int]]: + if parameters is None: + parameters = {} + + import pm4py + + # Available graph types + graph_types = [ + "object_interaction", + "object_descendants", + "object_inheritance", + "object_cobirth", + "object_codeath" + ] + + # Initialize OTG components + edges = defaultdict(int) + + object_types = set(ocel.objects["ocel:type"].unique()) + objects = ocel.objects.to_dict(orient="records") + objects = {x["ocel:oid"]: x["ocel:type"] for x in objects} + + # Iterate over each relationship type + for sigma in graph_types: + # Discover the object graph for the relationship type + object_graph = pm4py.discover_objects_graph(ocel, graph_type=sigma) + + # Build the edges for the OTG + for o1, o2 in object_graph: + ot1 = objects[o1] + ot2 = objects[o2] + + ot_pair = (ot1, ot2) + + edge = (ot_pair[0], sigma, ot_pair[1]) + edges[edge] += 1 + + return object_types, dict(edges) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45346530ed6e0fa2a79bdf8f48a3f02a7ea5a445 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/__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.algo.discovery.ocel.saw_nets import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..003c84a2b75cfbbe14c1f9db7cf33dc4385568c0 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/algorithm.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 +''' + +from enum import Enum +from pm4py.util import exec_utils +from pm4py.algo.discovery.ocel.saw_nets.variants import classic +from pm4py.objects.ocel.obj import OCEL +from typing import Optional, Dict, Any + + +class Variants(Enum): + CLASSIC = classic + + +def apply( + ocel: OCEL, + variant=Variants.CLASSIC, + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Any]: + """ + Discovers a SAW net representing the behavior of the provided object-centric event log. + + Parameters + ---------------- + ocel + Object-centric event log + variant + The variant of the algorithm to be used, possible values: Variants.CLASSIC + parameters + Variant-specific parameters + + Returns + --------------- + Dictionary with the following keys: + - ot_saw_net => the SAW nets for the single object types + - multi_saw_net => the overall SAW net + - decorations_multi_saw_net => decorations for the visualization of the SAW net + """ + return exec_utils.get_variant(variant).apply(ocel, parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4363081bd7ac8e82d76dd695d5995cbc773fb12 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/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.algo.discovery.ocel.saw_nets.variants import classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/variants/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/variants/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..a000cb21ec770cc6a8374345c7f50bcd45b969d5 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/ocel/saw_nets/variants/classic.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 +''' + +from pm4py.objects.ocel.obj import OCEL +from typing import Optional, Dict, Any +from pm4py.objects.ocel import constants as ocel_constants +from pm4py.algo.discovery.inductive import algorithm as inductive_miner +from enum import Enum +from pm4py.util import exec_utils, pandas_utils +from pm4py.objects.ocel.util import flattening +from pm4py.algo.conformance.tokenreplay import algorithm as token_replay +from pm4py.objects.conversion.log import converter as log_converter +from pm4py.objects.conversion.process_tree import converter as pt_converter +from pm4py.objects.petri_net.obj import PetriNet +from pm4py.objects.petri_net.saw_net.obj import StochasticArcWeightNet +from pm4py.objects.petri_net.utils import petri_utils +from collections import Counter +from pm4py.util import vis_utils +from copy import copy + + +class Parameters(Enum): + EVENT_ACTIVITY = ocel_constants.PARAM_EVENT_ACTIVITY + OBJECT_TYPE = ocel_constants.PARAM_OBJECT_TYPE + + +def __ot_to_color(ot: str) -> str: + """ + Auxiliary method converting an object type to a color + """ + ot = int(hash(ot)) + num = [] + while len(num) < 6: + num.insert(0, ot % 16) + ot = ot // 16 + ret = "#" + "".join([vis_utils.get_corr_hex(x) for x in num]) + return ret + + +def __discover_petri_and_consumption_stats_tbr( + ocel: OCEL, obj_types, parameters: Optional[Dict[Any, Any]] = None +): + """ + Flattens the OCEL, discovers Petri nets for the flattened log, + and by the token-based replay measures the usage of the elements + """ + saw_weights = {} + ocpn_nets = {} + + for ot in obj_types: + flat_log = log_converter.apply( + flattening.flatten(ocel, ot), + variant=log_converter.Variants.TO_EVENT_LOG, + ) + process_tree = inductive_miner.apply(flat_log, parameters=parameters) + net, im, fm = pt_converter.apply(process_tree) + ocpn_nets[ot] = (net, im, fm) + replayed_traces = token_replay.apply( + flat_log, net, im, fm, parameters=parameters + ) + transes_ev_ids = {x: [] for x in net.transitions} + for i in range(len(flat_log)): + flat_trace = flat_log[i] + rep_res = replayed_traces[i]["activated_transitions"] + j = 0 + z = 0 + while z < len(rep_res): + evid = flat_trace[j][ocel.event_id_column] + transes_ev_ids[rep_res[z]].append(evid) + if rep_res[z].label is not None and j < len(flat_trace) - 1: + j = j + 1 + z = z + 1 + for x in transes_ev_ids: + transes_ev_ids[x] = dict( + Counter(list(Counter(transes_ev_ids[x]).values())) + ) + saw_weights[ot] = transes_ev_ids + + return ocpn_nets, saw_weights + + +def __get_ot_saw_nets(obj_types, ocpn_nets, saw_weights): + """ + Computes a SAW net for every object type + """ + ot_saw_nets = {} + for ot in obj_types: + net, im, fm = ocpn_nets[ot] + saw_net = StochasticArcWeightNet(net.name) + for place in net.places: + saw_net.places.add(place) + for trans in net.transitions: + saw_net.transitions.add(trans) + for arc in net.arcs: + new_arc = petri_utils.add_arc_from_to( + arc.source, arc.target, saw_net, type="stochastic_arc" + ) + if ( + isinstance(new_arc.source, PetriNet.Transition) + and new_arc.source in saw_weights[ot] + ): + new_arc.weight = saw_weights[ot][new_arc.source] + elif ( + isinstance(new_arc.target, PetriNet.Transition) + and new_arc.target in saw_weights[ot] + ): + new_arc.weight = saw_weights[ot][new_arc.target] + ot_saw_nets[ot] = saw_net + return ot_saw_nets + + +def __get_multi_saw_net(ot_saw_nets): + """ + Puts together the SAW nets of the single object types + """ + multi_saw_net = StochasticArcWeightNet("multi") + el_corr = dict() + trans_unq_corr = dict() + decorations_multi_saw_net = {} + + for ot in ot_saw_nets: + otc0 = __ot_to_color(ot) + ot_color = {"color": otc0} + saw_net = ot_saw_nets[ot] + for place in saw_net.places: + multi_saw_net.places.add(place) + el_corr[place] = place + decorations_multi_saw_net[place] = ot_color + for trans in saw_net.transitions: + if trans.label is None: + multi_saw_net.transitions.add(trans) + el_corr[trans] = trans + decorations_multi_saw_net[trans] = ot_color + elif trans.label not in trans_unq_corr: + multi_saw_net.transitions.add(trans) + trans_unq_corr[trans.label] = trans + el_corr[trans] = trans + else: + el_corr[trans] = el_corr[trans_unq_corr[trans.label]] + for arc in saw_net.arcs: + new_arc = petri_utils.add_arc_from_to( + el_corr[arc.source], + el_corr[arc.target], + multi_saw_net, + weight=arc.weight, + ) + decorations_multi_saw_net[new_arc] = ot_color + + return multi_saw_net, decorations_multi_saw_net + + +def apply( + ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None +) -> Dict[str, Any]: + """ + Discovers a SAW net representing the behavior of the provided object-centric event log. + + Parameters + ---------------- + ocel + Object-centric event log + parameters + Possible parameters of the method, including: + - Parameters.OBJECT_TYPE => the attribute of the log to be used as object type + + Returns + -------------- + model + Dictionary with the following keys: + - ot_saw_net => the SAW nets for the single object types + - multi_saw_net => the overall SAW net + - decorations_multi_saw_net => decorations for the visualization of the SAW net + """ + if parameters is None: + parameters = {} + + object_type = exec_utils.get_param_value( + Parameters.OBJECT_TYPE, parameters, ocel.object_type_column + ) + obj_types = pandas_utils.format_unique(ocel.objects[object_type].unique()) + + disc_parameters = copy(parameters) + # disables the fallthroughs, as computing the model on a myriad of different object types + # could be really expensive + disc_parameters["disable_fallthroughs"] = True + # for performance reasons, also disable the strict sequence cut (use the + # normal sequence cut) + disc_parameters["disable_strict_sequence_cut"] = True + ocpn_nets, saw_weights = __discover_petri_and_consumption_stats_tbr( + ocel, obj_types, parameters=disc_parameters + ) + + ot_saw_nets = __get_ot_saw_nets(obj_types, ocpn_nets, saw_weights) + multi_saw_net, decorations_multi_saw_net = __get_multi_saw_net(ot_saw_nets) + + return { + "ot_saw_nets": ot_saw_nets, + "multi_saw_net": multi_saw_net, + "decorations_multi_saw_net": decorations_multi_saw_net, + } diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c438688124751cb3bd3184cbcfe2e4e65318de --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/__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.discovery.performance_spectrum import algorithm, variants diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6308f73ac75a984f625ae162d8e1aa586b2738 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/algorithm.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 +''' +import importlib.util + +from pm4py.algo.discovery.performance_spectrum.variants import ( + dataframe, + log, + dataframe_disconnected, + log_disconnected, +) +from pm4py.util import exec_utils +from enum import Enum +from pm4py.util import constants, pandas_utils +from typing import Optional, Dict, Any, Union, List +from pm4py.objects.log.obj import EventLog, EventStream +import pandas as pd + + +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 + ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY + PARAMETER_SAMPLE_SIZE = "sample_size" + + +class Outputs(Enum): + LIST_ACTIVITIES = "list_activities" + POINTS = "points" + + +class Variants(Enum): + DATAFRAME = dataframe + LOG = log + DATAFRAME_DISCONNECTED = dataframe_disconnected + LOG_DISCONNECTED = log_disconnected + + +if importlib.util.find_spec("polars"): + from pm4py.algo.discovery.performance_spectrum.variants import ( + lazyframe, + lazyframe_disconnected, + ) + + Variants.LAZYFRAME = lazyframe + Variants.LAZYFRAME_DISCONNECTED = lazyframe_disconnected + + +def is_polars_lazyframe(df: Any) -> bool: + """Return True if the provided dataframe is a Polars LazyFrame.""" + df_type = str(type(df)).lower() + return "polars" in df_type and "lazyframe" in df_type + + +def apply( + log: Union[EventLog, EventStream, pd.DataFrame], + list_activities: List[str], + variant=None, + parameters: Optional[Dict[Any, Any]] = None, +) -> Dict[str, Any]: + """ + Finds the performance spectrum provided a log/dataframe + and a list of activities + + Parameters + ------------- + log + Event log/Dataframe + list_activities + List of activities interesting for the performance spectrum (at least two) + variant + Variant to be used (see Variants Enum) + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + + Returns + ------------- + ps + Performance spectrum object (dictionary) + """ + from pm4py.objects.conversion.log import converter as log_conversion + + if parameters is None: + parameters = {} + + sample_size = exec_utils.get_param_value( + Parameters.PARAMETER_SAMPLE_SIZE, parameters, 10000 + ) + + if len(list_activities) < 2: + raise Exception( + "performance spectrum can be applied providing at least two activities!" + ) + + points = None + + if pandas_utils.check_is_pandas_dataframe(log): + if variant is None: + if is_polars_lazyframe(log): + variant = Variants.LAZYFRAME + else: + variant = Variants.DATAFRAME + + points = exec_utils.get_variant(variant).apply( + log, list_activities, sample_size, parameters + ) + + if points is None: + if variant is None: + variant = Variants.LOG + + points = exec_utils.get_variant(variant).apply( + log_conversion.apply( + log, + variant=log_conversion.Variants.TO_EVENT_LOG, + parameters=parameters, + ), + list_activities, + sample_size, + parameters, + ) + + ps = { + Outputs.LIST_ACTIVITIES.value: list_activities, + Outputs.POINTS.value: points, + } + + return ps diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c6ddccaf4214502da028b213855a7bf0b218cbb --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/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.algo.discovery.performance_spectrum.variants import ( + dataframe, + log, + dataframe_disconnected, + log_disconnected, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/dataframe.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..c7d568b785d22f2aed08f0e9b1a23157debcddbe --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/dataframe.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 enum import Enum + +from pm4py.util import constants +from pm4py.util import exec_utils, pandas_utils +from pm4py.util import xes_constants as xes +from pm4py.util.constants import CASE_CONCEPT_NAME +from typing import Optional, Dict, Any, Union, List +import pandas as pd + + +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 + ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY + PARAMETER_SAMPLE_SIZE = "sample_size" + SORT_LOG_REQUIRED = "sort_log_required" + + +def apply( + dataframe: pd.DataFrame, + list_activities: List[str], + sample_size: int, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """ + Finds the performance spectrum provided a dataframe + and a list of activities + + Parameters + ------------- + dataframe + Dataframe + list_activities + List of activities interesting for the performance spectrum (at least two) + sample_size + Size of the sample + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + + Returns + ------------- + points + Points of the performance spectrum + """ + if parameters is None: + parameters = {} + + import pandas as pd + import numpy as np + + case_id_glue = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, CASE_CONCEPT_NAME + ) + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + sort_log_required = exec_utils.get_param_value( + Parameters.SORT_LOG_REQUIRED, parameters, True + ) + + dataframe = dataframe[[case_id_glue, activity_key, timestamp_key]] + dataframe[activity_key] = dataframe[activity_key].astype("string") + dataframe = dataframe[dataframe[activity_key].isin(list_activities)] + dataframe = pandas_utils.insert_index( + dataframe, constants.DEFAULT_EVENT_INDEX_KEY + ) + if sort_log_required: + dataframe = dataframe.sort_values( + [case_id_glue, timestamp_key, constants.DEFAULT_EVENT_INDEX_KEY] + ) + dataframe[timestamp_key] = ( + dataframe[timestamp_key].astype(np.int64) / 10**9 + ) + + def key(k, n): + return k + str(n) + + # create a dataframe with all needed columns to check for the activities + # pattern + dfs = [ + dataframe.add_suffix(str(i)).shift(-i) + for i in range(len(list_activities)) + ] + dataframe = pandas_utils.concat(dfs, axis=1) + # keep only rows that belong to exactly one case + for i in range(len(list_activities) - 1): + dataframe = dataframe[ + dataframe[key(case_id_glue, i)] + == dataframe[key(case_id_glue, i + 1)] + ] + + column_list = [key(activity_key, i) for i in range(len(list_activities))] + pattern = "".join(list_activities) + # keep only rows that have the desired activities pattern + + matches = dataframe[ + np.equal(dataframe[column_list].agg("".join, axis=1), pattern) + ] + if len(matches) > sample_size: + matches = matches.sample(n=sample_size) + + filt_col_names = [ + timestamp_key + str(i) for i in range(len(list_activities)) + ] + points = pandas_utils.to_dict_records(matches) + points = [[p[tk] for tk in filt_col_names] for p in points] + points = sorted(points, key=lambda x: x[0]) + + return points diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/dataframe_disconnected.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/dataframe_disconnected.py new file mode 100644 index 0000000000000000000000000000000000000000..20e8376e243443297ae4d68b8311d35ac5c817e6 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/dataframe_disconnected.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 +''' +from enum import Enum + +import numpy as np + +from pm4py.util import constants, points_subset +from pm4py.util import exec_utils, pandas_utils +from pm4py.util import xes_constants as xes +from typing import Optional, Dict, Any, Union, List +import pandas as pd + + +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 + PARAMETER_SAMPLE_SIZE = "sample_size" + SORT_LOG_REQUIRED = "sort_log_required" + + +def gen_patterns(pattern, length): + return [ + "".join(pattern[i: i + length]) + for i in range(len(pattern) - (length - 1)) + ] + + +def apply( + dataframe: pd.DataFrame, + list_activities: List[str], + sample_size: int, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """ + Finds the disconnected performance spectrum provided a dataframe + and a list of activities + + Parameters + ------------- + dataframe + Dataframe + list_activities + List of activities interesting for the performance spectrum (at least two) + sample_size + Size of the sample + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + - Parameters.CASE_ID_KEY + + Returns + ------------- + points + Points of the performance spectrum + """ + if parameters is None: + parameters = {} + + case_id_glue = 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.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + + sort_log_required = exec_utils.get_param_value( + Parameters.SORT_LOG_REQUIRED, parameters, True + ) + + dataframe = dataframe[[case_id_glue, activity_key, timestamp_key]] + dataframe = dataframe[dataframe[activity_key].isin(list_activities)] + dataframe = pandas_utils.insert_index( + dataframe, constants.DEFAULT_EVENT_INDEX_KEY + ) + if sort_log_required: + dataframe = dataframe.sort_values( + [case_id_glue, timestamp_key, constants.DEFAULT_EVENT_INDEX_KEY] + ) + dataframe[timestamp_key] = ( + dataframe[timestamp_key].astype(np.int64) / 10**9 + ) + + all_patterns = [ + ( + len(list_activities) - i, + gen_patterns(list_activities, len(list_activities) - i), + ) + for i in range(len(list_activities) - 1) + ] + + def key(k, n): + return k + str(n) + + def to_points(match, l): + return { + "case_id": match[key(case_id_glue, 0)], + "points": [ + (match[key(activity_key, i)], match[key(timestamp_key, i)]) + for i in range(l) + ], + } + + points = [] + for l, patterns in all_patterns: + # concat shifted and suffixed dataframes to get a dataframe that allows + # to check for the patterns + dfs = [dataframe.add_suffix(str(i)).shift(-i) for i in range(l)] + df_merged = pandas_utils.concat(dfs, axis=1) + + indices = [shift_index(dfs[i].index, i) for i in range(len(dfs))] + mindex = pd.MultiIndex.from_arrays(indices) + df_merged = df_merged.set_index(mindex) + + for i in range(l - 1): + df_merged = df_merged[ + df_merged[key(case_id_glue, i)] + == df_merged[key(case_id_glue, i + 1)] + ] + + column_list = [key(activity_key, i) for i in range(l)] + matches = df_merged[ + np.isin(df_merged[column_list].sum(axis=1), patterns) + ] + points.extend([to_points(m, l) for m in matches.to_dict(orient="records")]) + # drop rows of this match to not discover subsets of this match again + dataframe = dataframe.drop( + [int(i) for indices in matches.index for i in indices[:-1]] + ) + pass + + points = sorted( + points, key=lambda x: min(x["points"], key=lambda x: x[1])[1] + ) + if len(points) > sample_size: + points = points_subset.pick_chosen_points_list(sample_size, points) + + return points + + +def shift_index(index, n): + if n == 0: + return list(index) + nones = [None for _ in range(n)] + return list(index[n:]) + nones diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/lazyframe.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/lazyframe.py new file mode 100644 index 0000000000000000000000000000000000000000..4a3f961c1c9053bfa9bced6b7854a6e33787bfb8 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/lazyframe.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 +''' + +from enum import Enum +from typing import Any, Dict, List, Optional, Union + +import polars as pl + +from pm4py.util import constants +from pm4py.util import exec_utils +from pm4py.util import xes_constants as xes +from pm4py.util.constants import CASE_CONCEPT_NAME + + +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 + PARAMETER_SAMPLE_SIZE = "sample_size" + SORT_LOG_REQUIRED = "sort_log_required" + + +def apply( + dataframe: pl.LazyFrame, + list_activities: List[str], + sample_size: int, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> List[List[float]]: + """Compute the performance spectrum on a Polars LazyFrame.""" + + if parameters is None: + parameters = {} + + case_id_glue = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, CASE_CONCEPT_NAME + ) + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + sort_log_required = exec_utils.get_param_value( + Parameters.SORT_LOG_REQUIRED, parameters, True + ) + + lf = dataframe.select( + pl.col(case_id_glue), + pl.col(activity_key).cast(pl.Utf8), + pl.col(timestamp_key), + ) + lf = lf.filter(pl.col(activity_key).is_in(list_activities)) + lf = lf.with_row_index(constants.DEFAULT_EVENT_INDEX_KEY) + + if sort_log_required: + lf = lf.sort([case_id_glue, timestamp_key, constants.DEFAULT_EVENT_INDEX_KEY], maintain_order=True) + + lf = lf.with_columns( + pl.col(timestamp_key).dt.timestamp().alias(timestamp_key) + ) + + def key(prefix: str, idx: int) -> str: + return f"{prefix}_{idx}" + + shifted = lf + for idx in range(len(list_activities)): + shifted = shifted.with_columns( + pl.col(activity_key) + .shift(-idx) + .over(case_id_glue) + .alias(key(activity_key, idx)), + pl.col(timestamp_key) + .shift(-idx) + .over(case_id_glue) + .alias(key(timestamp_key, idx)), + ) + + activity_cols = [key(activity_key, idx) for idx in range(len(list_activities))] + timestamp_cols = [key(timestamp_key, idx) for idx in range(len(list_activities))] + + pattern_str = "".join(list_activities) + + shifted = shifted.filter( + pl.all_horizontal([pl.col(col).is_not_null() for col in activity_cols]) + ) + + shifted = shifted.with_columns( + pl.concat_str([pl.col(col) for col in activity_cols]).alias("pattern") + ) + + shifted = shifted.filter(pl.col("pattern") == pattern_str) + + matches = shifted.select([pl.col(col) for col in timestamp_cols]).collect() + + points = [] + for row in matches.iter_rows(named=False): + points.append([value / 1_000_000 for value in row]) + + points.sort(key=lambda x: x[0]) + + if len(points) > sample_size: + points = points[:sample_size] + + return points diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/lazyframe_disconnected.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/lazyframe_disconnected.py new file mode 100644 index 0000000000000000000000000000000000000000..83bf01855454fe9cc79aebc8c816578552ff1b70 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/lazyframe_disconnected.py @@ -0,0 +1,189 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, Set, Union + +import polars as pl + +from pm4py.util import constants, points_subset +from pm4py.util import exec_utils +from pm4py.util import xes_constants as xes + + +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 + PARAMETER_SAMPLE_SIZE = "sample_size" + SORT_LOG_REQUIRED = "sort_log_required" + + +def gen_patterns(pattern: List[str], length: int) -> List[str]: + return ["".join(pattern[i : i + length]) for i in range(len(pattern) - (length - 1))] + + +def _prepare_dataframe( + lf: pl.LazyFrame, + activities: List[str], + case_id_glue: str, + activity_key: str, + timestamp_key: str, + sort_required: bool, +) -> pl.LazyFrame: + lf = lf.select( + pl.col(case_id_glue), + pl.col(activity_key), + pl.col(timestamp_key), + ) + lf = lf.filter(pl.col(activity_key).is_in(activities)) + lf = lf.with_row_index(constants.DEFAULT_EVENT_INDEX_KEY) + if sort_required: + lf = lf.sort([case_id_glue, timestamp_key, constants.DEFAULT_EVENT_INDEX_KEY], maintain_order=True) + lf = lf.with_columns(pl.col(timestamp_key).dt.timestamp().alias(timestamp_key)) + return lf + + +def apply( + dataframe: pl.LazyFrame, + list_activities: List[str], + sample_size: int, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """Compute disconnected performance spectrum using a Polars LazyFrame.""" + + if parameters is None: + parameters = {} + + case_id_glue = 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.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + sort_log_required = exec_utils.get_param_value( + Parameters.SORT_LOG_REQUIRED, parameters, True + ) + + lf = _prepare_dataframe( + dataframe, + list_activities, + case_id_glue, + activity_key, + timestamp_key, + sort_log_required, + ) + + points: List[Dict[str, Any]] = [] + + all_patterns = [ + ( + len(list_activities) - i, + gen_patterns(list_activities, len(list_activities) - i), + ) + for i in range(len(list_activities) - 1) + ] + + def key(prefix: str, idx: int) -> str: + return f"{prefix}_{idx}" + + for length, patterns in all_patterns: + if length <= 0: + continue + + pattern_lf = lf + exprs: List[pl.Expr] = [] + for i in range(length): + exprs.extend( + [ + pl.col(activity_key) + .shift(-i) + .over(case_id_glue) + .alias(key(activity_key, i)), + pl.col(timestamp_key) + .shift(-i) + .over(case_id_glue) + .alias(key(timestamp_key, i)), + pl.col(constants.DEFAULT_EVENT_INDEX_KEY) + .shift(-i) + .over(case_id_glue) + .alias(key(constants.DEFAULT_EVENT_INDEX_KEY, i)), + ] + ) + + pattern_lf = pattern_lf.with_columns(exprs) + pattern_lf = pattern_lf.filter( + pl.all_horizontal( + [pl.col(key(activity_key, i)).is_not_null() for i in range(length)] + ) + ) + + pattern_values = ["".join(pat) for pat in patterns] + if not pattern_values: + continue + + pattern_lf = pattern_lf.with_columns( + pl.concat_str([pl.col(key(activity_key, i)) for i in range(length)]) + .alias("pattern") + ) + pattern_lf = pattern_lf.filter(pl.col("pattern").is_in(pattern_values)) + + collected = pattern_lf.collect() + if collected.height == 0: + continue + + to_drop_indexes: Set[int] = set() + + for row in collected.iter_rows(named=True): + activities_seq = [row[key(activity_key, i)] for i in range(length)] + timestamps_seq = [row[key(timestamp_key, i)] / 1_000_000 for i in range(length)] + case_id = row[case_id_glue] + + points.append( + { + "case_id": case_id, + "points": list(zip(activities_seq, timestamps_seq)), + } + ) + + for i in range(length - 1): + to_drop_indexes.add(row[key(constants.DEFAULT_EVENT_INDEX_KEY, i)]) + + if to_drop_indexes: + lf = lf.filter( + ~pl.col(constants.DEFAULT_EVENT_INDEX_KEY).is_in( + pl.lit(list(to_drop_indexes)) + ) + ) + + points = sorted( + points, + key=lambda entry: min(entry["points"], key=lambda evt: evt[1])[1], + ) + + if len(points) > sample_size: + points = points_subset.pick_chosen_points_list(sample_size, points) + + return points diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/log.py new file mode 100644 index 0000000000000000000000000000000000000000..a9810e23915bd58d9ea26f2a380c9344ee3983cf --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/log.py @@ -0,0 +1,112 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 sorting +from pm4py.objects.log.util import basic_filter +from pm4py.util import points_subset +from pm4py.util import xes_constants as xes +from pm4py.util import exec_utils +from enum import Enum +from pm4py.util import constants +from typing import Optional, Dict, Any, Union, List +from pm4py.objects.log.obj import EventLog + + +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 + ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY + PARAMETER_SAMPLE_SIZE = "sample_size" + SORT_LOG_REQUIRED = "sort_log_required" + + +def apply( + log: EventLog, + list_activities: List[str], + sample_size: int, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """ + Finds the performance spectrum provided a log + and a list of activities + + Parameters + ------------- + log + Log + list_activities + List of activities interesting for the performance spectrum (at least two) + sample_size + Size of the sample + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + + Returns + ------------- + points + Points of the performance spectrum + """ + if parameters is None: + parameters = {} + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + sort_log_required = exec_utils.get_param_value( + Parameters.SORT_LOG_REQUIRED, parameters, True + ) + + parameters[Parameters.ATTRIBUTE_KEY] = activity_key + log = basic_filter.filter_log_events_attr( + log, list_activities, parameters=parameters + ) + if sort_log_required: + log = sorting.sort_timestamp_log(log, timestamp_key=timestamp_key) + + points = [] + + for trace in log: + for i in range(len(trace) - len(list_activities) + 1): + acti_comb = [ + event[activity_key] + for event in trace[i: i + len(list_activities)] + ] + + if acti_comb == list_activities: + timest_comb = [ + event[timestamp_key].timestamp() + for event in trace[i: i + len(list_activities)] + ] + + points.append(timest_comb) + + points = sorted(points, key=lambda x: x[0]) + + if len(points) > sample_size: + points = points_subset.pick_chosen_points_list(sample_size, points) + + return points diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/log_disconnected.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/log_disconnected.py new file mode 100644 index 0000000000000000000000000000000000000000..6aef352224a47b96924082791ca02f71ed590da4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/performance_spectrum/variants/log_disconnected.py @@ -0,0 +1,155 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.util import sorting +from pm4py.util import constants, exec_utils +from pm4py.util import points_subset +from pm4py.util import xes_constants as xes +from pm4py.objects.log.util import basic_filter +from typing import Optional, Dict, Any, Union, List +from pm4py.objects.log.obj import EventLog + + +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 + ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY + PARAMETER_SAMPLE_SIZE = "sample_size" + SORT_LOG_REQUIRED = "sort_log_required" + + +def apply( + log: EventLog, + list_activities: List[str], + sample_size: int, + parameters: Optional[Dict[Union[str, Parameters], Any]] = None, +) -> Dict[str, Any]: + """ + Finds the disconnected performance spectrum provided a log + and a list of activities + + Parameters + ------------- + log + Log + list_activities + List of activities interesting for the performance spectrum (at least two) + sample_size + Size of the sample + parameters + Parameters of the algorithm, including: + - Parameters.ACTIVITY_KEY + - Parameters.TIMESTAMP_KEY + + Returns + ------------- + points + Points of the performance spectrum + """ + if parameters is None: + parameters = {} + + sort_log_required = exec_utils.get_param_value( + Parameters.SORT_LOG_REQUIRED, parameters, True + ) + + all_acti_combs = set( + tuple(list_activities[j: j + i]) + for i in range(2, len(list_activities) + 1) + for j in range(0, len(list_activities) - i + 1) + ) + two_acti_combs = set( + (list_activities[i], list_activities[i + 1]) + for i in range(len(list_activities) - 1) + ) + + activity_key = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY + ) + timestamp_key = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes.DEFAULT_TIMESTAMP_KEY + ) + case_id_key = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, xes.DEFAULT_TRACEID_KEY + ) + + parameters[Parameters.ATTRIBUTE_KEY] = activity_key + log = basic_filter.filter_log_events_attr( + log, list_activities, parameters=parameters + ) + if sort_log_required: + log = sorting.sort_timestamp_log(log, timestamp_key=timestamp_key) + + points = [] + for trace in log: + matches = [ + (i, i + 1) + for i in range(len(trace) - 1) + if (trace[i][activity_key], trace[i + 1][activity_key]) + in two_acti_combs + ] + + i = 0 + while i < len(matches) - 1: + matchAct = ( + trace[mi][activity_key] + for mi in (matches[i] + matches[i + 1][1:]) + ) + if ( + matches[i][-1] == matches[i + 1][0] + and matchAct in all_acti_combs + ): + matches[i] = matches[i] + matches[i + 1][1:] + del matches[i + 1] + i = 0 + else: + i += 1 + + if matches: + matches = set(matches) + timest_comb = [ + { + "points": [ + ( + trace[i][activity_key], + trace[i][timestamp_key].timestamp(), + ) + for i in match + ] + } + for match in matches + ] + for p in timest_comb: + p["case_id"] = trace.attributes[case_id_key] + + points += timest_comb + + points = sorted( + points, key=lambda x: min(x["points"], key=lambda x: x[1])[1] + ) + + if len(points) > sample_size: + points = points_subset.pick_chosen_points_list(sample_size, points) + + return points diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..542eddc894768d234b23b2336aeaf6d8ad2d237a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/__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.algo.discovery.powl import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4cf1b7333e16d6634bbaed1cfb6bcf2dfd3c19 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/algorithm.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 pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.powl.inductive.variants.im_dynamic_clustering_frequencies import ( + POWLInductiveMinerDynamicClusteringFrequency, ) +from pm4py.algo.discovery.powl.inductive.variants.im_tree import IMBasePOWL +from pm4py.algo.discovery.powl.inductive.variants.im_brute_force import ( + POWLInductiveMinerBruteForce, +) +from pm4py.algo.discovery.powl.inductive.variants.im_maximal import ( + POWLInductiveMinerMaximalOrder, +) +from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import ( + POWLDiscoveryVariant, ) + +from pm4py import util +from pm4py.algo.discovery.inductive.algorithm import Parameters +from pm4py.objects.powl.obj import POWL + +from pm4py.util import xes_constants as xes_util +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL + +from pm4py.util import exec_utils +from typing import Optional, Dict, Any, Union, Type +from pm4py.objects.log.obj import EventLog +import pandas as pd + + +def get_variant(variant: POWLDiscoveryVariant) -> Type[IMBasePOWL]: + if variant == POWLDiscoveryVariant.TREE: + return IMBasePOWL + elif variant == POWLDiscoveryVariant.BRUTE_FORCE: + return POWLInductiveMinerBruteForce + elif variant == POWLDiscoveryVariant.MAXIMAL: + return POWLInductiveMinerMaximalOrder + elif variant == POWLDiscoveryVariant.DYNAMIC_CLUSTERING: + return POWLInductiveMinerDynamicClusteringFrequency + else: + raise Exception("Invalid Variant!") + + +def apply( + obj: Union[EventLog, pd.DataFrame, UVCL], + parameters: Optional[Dict[Any, Any]] = None, + variant=POWLDiscoveryVariant.MAXIMAL, +) -> POWL: + if parameters is None: + parameters = {} + ack = exec_utils.get_param_value( + Parameters.ACTIVITY_KEY, parameters, xes_util.DEFAULT_NAME_KEY + ) + tk = exec_utils.get_param_value( + Parameters.TIMESTAMP_KEY, parameters, xes_util.DEFAULT_TIMESTAMP_KEY + ) + cidk = exec_utils.get_param_value( + Parameters.CASE_ID_KEY, parameters, util.constants.CASE_CONCEPT_NAME + ) + + if type(obj) is UVCL: + uvcl = obj + else: + uvcl = comut.get_variants( + comut.project_univariate( + obj, key=ack, df_glue=cidk, df_sorting_criterion_key=tk + ) + ) + + algorithm = get_variant(variant) + im = algorithm(parameters) + res = im.apply(IMDataStructureUVCL(uvcl), parameters) + res = res.simplify() + + return res diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8aed068014bc0a67dc79f1904a8407c59c5978b8 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/__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.algo.discovery.powl.inductive import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..550541e9646a8e56932b81dfc69597230457a9f5 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/__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.algo.discovery.powl.inductive.base_case import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7f82010100a68c7d354bb0570b195ff8c65047 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/abc.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 abc import ABC, abstractmethod +from typing import Union, TypeVar, Generic, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructure +from pm4py.objects.powl.obj import POWL + +T = TypeVar("T", bound=Union[IMDataStructure]) + + +class BaseCase(ABC, Generic[T]): + + @classmethod + def apply( + cls, obj=T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[POWL]: + return ( + cls.leaf(obj, parameters) if cls.holds(obj, parameters) else None + ) + + @classmethod + @abstractmethod + def holds(cls, obj=T, parameters: Optional[Dict[str, Any]] = None) -> bool: + pass + + @classmethod + @abstractmethod + def leaf(cls, obj=T, parameters: Optional[Dict[str, Any]] = None) -> POWL: + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/empty_log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/empty_log.py new file mode 100644 index 0000000000000000000000000000000000000000..e74a9c9686a130e909f9454d4aa474e5227e676e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/empty_log.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 abc import ABC +from typing import Generic, Optional, Dict, Any + +from pm4py.algo.discovery.powl.inductive.base_case.abc import BaseCase, T +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.obj import SilentTransition + + +class EmptyLogBaseCase(BaseCase[T], ABC, Generic[T]): + + @classmethod + def leaf( + cls, obj=T, parameters: Optional[Dict[str, Any]] = None + ) -> SilentTransition: + return SilentTransition() + + +class EmptyLogBaseCaseUVCL(EmptyLogBaseCase[IMDataStructureUVCL]): + + @classmethod + def holds( + cls, + obj=IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + return len(obj.data_structure) == 0 diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..5d3f08a8b1066c251a51fd4456cee8f867f45c04 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/factory.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 typing import TypeVar, Optional, Dict, Any, Type, List as TList + +from pm4py.algo.discovery.powl.inductive.base_case.abc import BaseCase +from pm4py.algo.discovery.powl.inductive.base_case.empty_log import ( + EmptyLogBaseCaseUVCL, +) +from pm4py.algo.discovery.powl.inductive.base_case.single_activity import ( + SingleActivityBaseCaseUVCL, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructure, + IMDataStructureUVCL, +) + +from pm4py.objects.powl.obj import POWL + +T = TypeVar("T", bound=IMDataStructure) +S = TypeVar("S", bound=BaseCase) + + +class BaseCaseFactory: + + @classmethod + def get_base_cases( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> TList[Type[S]]: + if type(obj) is IMDataStructureUVCL: + return [EmptyLogBaseCaseUVCL, SingleActivityBaseCaseUVCL] + return [] + + @classmethod + def apply_base_cases( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[POWL]: + for b in BaseCaseFactory.get_base_cases(obj): + r = b.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/single_activity.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/single_activity.py new file mode 100644 index 0000000000000000000000000000000000000000..d6f80e5d5c1896115a0465eacb7a51fd76bfc515 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/base_case/single_activity.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 pm4py.algo.discovery.powl.inductive.base_case.abc import BaseCase +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from typing import Optional, Dict, Any + +from pm4py.objects.powl.obj import Transition + + +class SingleActivityBaseCaseUVCL(BaseCase[IMDataStructureUVCL]): + @classmethod + def holds( + cls, + obj=IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> bool: + if len(obj.data_structure.keys()) != 1: + return False + if len(list(obj.data_structure.keys())[0]) > 1: + return False + return True + + @classmethod + def leaf( + cls, + obj=IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> Transition: + for t in obj.data_structure: + return Transition(label=t[0]) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7accb55edf6aff2cda7634a519e940d4ac4d6fe8 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/__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.algo.discovery.powl.inductive.cuts import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/concurrency.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..25396fed415bba1bd265d652aa0a28b946a21d58 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/concurrency.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 +''' + +from abc import ABC +from typing import Any, Optional, Dict, Generic, Tuple, List + +from pm4py.algo.discovery.inductive.cuts.concurrency import ( + ConcurrencyCut, + ConcurrencyCutUVCL, + T, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.obj import StrictPartialOrder + + +class POWLConcurrencyCut(ConcurrencyCut, ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> StrictPartialOrder: + raise Exception("This function should not be called!") + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[StrictPartialOrder, List[T]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + else: + children = cls.project(obj, g, parameters) + return StrictPartialOrder(children), children + + +class POWLConcurrencyCutUVCL( + ConcurrencyCutUVCL, POWLConcurrencyCut[IMDataStructureUVCL] +): + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5f66a656a59d7f1f32495cb9dc3c9464464889 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/factory.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 +''' + +from typing import List, Optional, Tuple, Dict, Any, Type + +from pm4py.algo.discovery.inductive.cuts.factory import S, T +from pm4py.algo.discovery.powl.inductive.cuts.concurrency import ( + POWLConcurrencyCutUVCL, +) +from pm4py.algo.discovery.powl.inductive.cuts.loop import POWLLoopCutUVCL +from pm4py.algo.discovery.powl.inductive.cuts.sequence import ( + POWLStrictSequenceCutUVCL, +) +from pm4py.algo.discovery.powl.inductive.cuts.xor import ( + POWLExclusiveChoiceCutUVCL, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructure, + IMDataStructureUVCL, +) +from pm4py.objects.powl.obj import POWL + + +class CutFactory: + + @classmethod + def get_cuts( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> List[Type[S]]: + if type(obj) is IMDataStructureUVCL: + return [ + POWLExclusiveChoiceCutUVCL, + POWLStrictSequenceCutUVCL, + POWLConcurrencyCutUVCL, + POWLLoopCutUVCL, + ] + return list() + + @classmethod + def find_cut( + cls, obj: IMDataStructure, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + for c in CutFactory.get_cuts(obj): + r = c.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/loop.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/loop.py new file mode 100644 index 0000000000000000000000000000000000000000..0e421febc163c81301302a7cb2f0144a83a75ac9 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/loop.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 abc import ABC +from typing import Optional, Any, Dict, Generic, List, Tuple + +from pm4py.algo.discovery.inductive.cuts.loop import LoopCut, LoopCutUVCL, T +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.obj import OperatorPOWL, POWL +from pm4py.objects.process_tree.obj import Operator + + +class POWLLoopCut(LoopCut, ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> OperatorPOWL: + raise Exception("This function should not be called!") + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + else: + children = cls.project(obj, g, parameters) + return OperatorPOWL(Operator.LOOP, children), children + + +class POWLLoopCutUVCL(LoopCutUVCL, POWLLoopCut[IMDataStructureUVCL]): + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/sequence.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..a66bcbf267898f3950323a8ba96bfd305425c15c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/sequence.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 abc import ABC +from typing import Any, Optional, Dict, Tuple, List, Generic + +from pm4py.algo.discovery.inductive.base_case.abc import T +from pm4py.algo.discovery.inductive.cuts.sequence import ( + SequenceCut, + SequenceCutUVCL, + StrictSequenceCutUVCL, + StrictSequenceCut, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.obj import Sequence + + +class POWLSequenceCut(SequenceCut, ABC, Generic[T]): + + @classmethod + def operator(cls, parameters: Optional[Dict[str, Any]] = None) -> Sequence: + raise Exception("This function should not be called!") + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[Sequence, List[T]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + children = cls.project(obj, g, parameters) + po = Sequence(children) + return po, children + + +class POWLStrictSequenceCut(POWLSequenceCut[T], StrictSequenceCut, ABC): + pass + + +class POWLSequenceCutUVCL( + SequenceCutUVCL, POWLSequenceCut[IMDataStructureUVCL] +): + pass + + +class POWLStrictSequenceCutUVCL( + StrictSequenceCutUVCL, + StrictSequenceCut[IMDataStructureUVCL], + POWLSequenceCutUVCL, +): + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/xor.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/xor.py new file mode 100644 index 0000000000000000000000000000000000000000..d75919ac2a4766dc0d67244111356ae77fe7d389 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/cuts/xor.py @@ -0,0 +1,59 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' + +from abc import ABC +from typing import Optional, Any, Dict, Generic, Tuple, List + +from pm4py.algo.discovery.inductive.cuts.xor import ( + ExclusiveChoiceCut, + ExclusiveChoiceCutUVCL, + T, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.obj import OperatorPOWL, POWL +from pm4py.objects.process_tree.obj import Operator + + +class POWLExclusiveChoiceCut(ExclusiveChoiceCut, ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> OperatorPOWL: + raise Exception("This function should not be called!") + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + else: + children = cls.project(obj, g, parameters) + return OperatorPOWL(Operator.XOR, children), children + + +class POWLExclusiveChoiceCutUVCL( + ExclusiveChoiceCutUVCL, POWLExclusiveChoiceCut[IMDataStructureUVCL], ABC +): + pass diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34efa134499f5c99989c87971d3c5f2553d3d7cb --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/__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.discovery.powl.inductive.fall_through import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/activity_concurrent.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/activity_concurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..4b535c5a86c3b0a01258df8ae971c8ca62f81060 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/activity_concurrent.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 collections import Counter +from multiprocessing import Pool, Manager +from typing import Optional, Tuple, List, Any, Dict + +from pm4py.algo.discovery.inductive.fall_through.activity_concurrent import ( + ActivityConcurrentUVCL, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.obj import StrictPartialOrder + + +class POWLActivityConcurrentUVCL(ActivityConcurrentUVCL): + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool: Pool = None, + manager: Manager = None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[StrictPartialOrder, List[IMDataStructureUVCL]]]: + candidate = cls._get_candidate(obj, pool, manager, parameters) + if candidate is None: + return None + log = obj.data_structure + l_a = Counter() + l_other = Counter() + for t in log: + l_a.update({tuple(filter(lambda e: e == candidate, t)): log[t]}) + l_other.update( + {tuple(filter(lambda e: e != candidate, t)): log[t]} + ) + children = [IMDataStructureUVCL(l_a), IMDataStructureUVCL(l_other)] + return StrictPartialOrder(children), children diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/activity_once_per_trace.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/activity_once_per_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..2aeed426b766bfda86670f85c04f5abc2c9ab8f7 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/activity_once_per_trace.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 +''' +from collections import Counter +from typing import Optional, Tuple, List, Any, Dict + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.inductive.fall_through.activity_once_per_trace import ( + ActivityOncePerTraceUVCL, ) +from pm4py.algo.discovery.powl.inductive.fall_through.activity_concurrent import ( + POWLActivityConcurrentUVCL, ) +from pm4py.objects.powl.obj import StrictPartialOrder +from pm4py.objects.process_tree.obj import ProcessTree, Operator + + +class POWLActivityOncePerTraceUVCL( + ActivityOncePerTraceUVCL, POWLActivityConcurrentUVCL +): + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool=None, + manager=None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[StrictPartialOrder, List[IMDataStructureUVCL]]]: + + candidate = cls._get_candidate(obj, pool, manager, parameters) + if candidate is None: + return None + log = obj.data_structure + l_a = Counter() + l_other = Counter() + for t in log: + l_a.update({tuple(filter(lambda e: e == candidate, t)): log[t]}) + l_other.update( + {tuple(filter(lambda e: e != candidate, t)): log[t]} + ) + children = [IMDataStructureUVCL(l_a), IMDataStructureUVCL(l_other)] + return StrictPartialOrder(children), children diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/empty_traces.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/empty_traces.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ccd102408218fc40b6ce6950228c0c043ae2ab --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/empty_traces.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 collections import Counter +from multiprocessing import Pool, Manager +from typing import Tuple, List, Optional, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.inductive.fall_through.empty_traces import ( + EmptyTracesUVCL, +) +from pm4py.objects.powl.obj import OperatorPOWL +from pm4py.objects.process_tree.obj import Operator +from copy import copy + + +class POWLEmptyTracesUVCL(EmptyTracesUVCL): + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool: Pool = None, + manager: Manager = None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[OperatorPOWL, List[IMDataStructureUVCL]]]: + if cls.holds(obj, parameters): + data_structure = copy(obj.data_structure) + del data_structure[()] + children = [ + IMDataStructureUVCL(Counter()), + IMDataStructureUVCL(data_structure), + ] + return OperatorPOWL(Operator.XOR, children), children + else: + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..cde49c04291da17e93a93539341478999f751d58 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/factory.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 multiprocessing import Pool, Manager +from typing import List, TypeVar, Tuple, Optional, Dict, Any, Type + +from pm4py.algo.discovery.inductive.dtypes.im_ds import ( + IMDataStructure, + IMDataStructureUVCL, +) +from pm4py.algo.discovery.inductive.fall_through.abc import FallThrough +from pm4py.algo.discovery.powl.inductive.fall_through.activity_concurrent import ( + POWLActivityConcurrentUVCL, ) +from pm4py.algo.discovery.powl.inductive.fall_through.activity_once_per_trace import ( + POWLActivityOncePerTraceUVCL, ) +from pm4py.algo.discovery.powl.inductive.fall_through.empty_traces import ( + POWLEmptyTracesUVCL, +) +from pm4py.algo.discovery.powl.inductive.fall_through.flower import ( + POWLFlowerModelUVCL, +) +from pm4py.algo.discovery.powl.inductive.fall_through.strict_tau_loop import ( + POWLStrictTauLoopUVCL, +) +from pm4py.algo.discovery.powl.inductive.fall_through.tau_loop import ( + POWLTauLoopUVCL, +) +from pm4py.objects.powl.obj import POWL + +T = TypeVar("T", bound=IMDataStructure) +S = TypeVar("S", bound=FallThrough) + + +class FallThroughFactory: + + @classmethod + def get_fall_throughs( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> List[Type[S]]: + if type(obj) is IMDataStructureUVCL: + return [ + POWLEmptyTracesUVCL, + POWLActivityOncePerTraceUVCL, + POWLActivityConcurrentUVCL, + POWLStrictTauLoopUVCL, + POWLTauLoopUVCL, + POWLFlowerModelUVCL, + ] + return list() + + @classmethod + def fall_through( + cls, + obj: T, + pool: Pool, + manager: Manager, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[POWL, List[T]]]: + for f in FallThroughFactory.get_fall_throughs(obj): + r = f.apply(obj, pool, manager, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/flower.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/flower.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d1217726e6f44ce96dd509c68fb51afea52174 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/flower.py @@ -0,0 +1,52 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' + +from multiprocessing import Pool, Manager +from typing import Optional, Tuple, List, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.inductive.fall_through.flower import FlowerModelUVCL +from pm4py.objects.powl.obj import OperatorPOWL +from pm4py.objects.process_tree.obj import Operator +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL + + +class POWLFlowerModelUVCL(FlowerModelUVCL): + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool: Pool = None, + manager: Manager = None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[OperatorPOWL, List[IMDataStructureUVCL]]]: + log = obj.data_structure + uvcl_do = UVCL() + for a in comut.get_alphabet(log): + uvcl_do[(a,)] = 1 + uvcl_redo = UVCL() + im_uvcl_do = IMDataStructureUVCL(uvcl_do) + im_uvcl_redo = IMDataStructureUVCL(uvcl_redo) + children = [im_uvcl_do, im_uvcl_redo] + return OperatorPOWL(Operator.LOOP, children), children diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/strict_tau_loop.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/strict_tau_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..9c2482d511fb86e11b17539ff31ec929bf768e66 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/strict_tau_loop.py @@ -0,0 +1,52 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 multiprocessing import Pool, Manager +from typing import Optional, Tuple, List, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.inductive.fall_through.strict_tau_loop import ( + StrictTauLoopUVCL, +) +from pm4py.objects.powl.obj import OperatorPOWL +from pm4py.objects.process_tree.obj import Operator + + +class POWLStrictTauLoopUVCL(StrictTauLoopUVCL): + + @classmethod + def apply( + cls, + obj: IMDataStructureUVCL, + pool: Pool = None, + manager: Manager = None, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[OperatorPOWL, List[IMDataStructureUVCL]]]: + log = obj.data_structure + proj = cls._get_projected_log(log) + if sum(proj.values()) > sum(log.values()): + children = [ + IMDataStructureUVCL(proj), + IMDataStructureUVCL(Counter()), + ] + return OperatorPOWL(Operator.LOOP, children), children diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/tau_loop.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/tau_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..a126dbcc8fb991da2e64c458c32a54b23f23fbc7 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/fall_through/tau_loop.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 collections import Counter +from typing import Optional, Dict, Any + +from pm4py.algo.discovery.inductive.fall_through.tau_loop import TauLoopUVCL +from pm4py.algo.discovery.powl.inductive.fall_through.strict_tau_loop import ( + POWLStrictTauLoopUVCL, +) +from pm4py.util.compression import util as comut +from pm4py.util.compression.dtypes import UVCL + + +class POWLTauLoopUVCL(POWLStrictTauLoopUVCL, TauLoopUVCL): + + @classmethod + def _get_projected_log( + cls, log: UVCL, parameters: Optional[Dict[str, Any]] = None + ) -> UVCL: + start_activities = comut.get_start_activities(log) + proj = Counter() + for t in log: + x = 0 + for i in range(1, len(t)): + if t[i] in start_activities: + proj.update({t[x:i]: log[t]}) + x = i + proj.update({t[x: len(t)]: log[t]}) + return proj diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/utils/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75a35493ac1f121f60d3695e5db5af9f0eff02d4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/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/algo/discovery/powl/inductive/utils/filtering.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/utils/filtering.py new file mode 100644 index 0000000000000000000000000000000000000000..e995391e049bfc1f759f7dc345d43b21a5460a0e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/utils/filtering.py @@ -0,0 +1,69 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, auto +from collections import Counter +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL + + +class FilteringType(Enum): + DYNAMIC = auto() + DECREASING_FACTOR = auto() + + +DEFAULT_FILTERING_TYPE = FilteringType.DECREASING_FACTOR +FILTERING_THRESHOLD = "filtering_threshold" +FILTERING_TYPE = "filtering_type" + + +def filter_most_frequent_variants(log): + to_remove_freq = min([freq for var, freq in log.items()]) + new_log = Counter() + for var, freq in log.items(): + if freq == to_remove_freq: + continue + new_log[var] = freq + + return IMDataStructureUVCL(new_log) + + +def filter_most_frequent_variants_with_decreasing_factor( + log, decreasing_factor +): + sorted_variants = sorted(log, key=log.get, reverse=True) + new_log = Counter() + + already_added_sum = 0 + prev_var_count = -1 + + for variant in sorted_variants: + frequency = log[variant] + if ( + already_added_sum == 0 + or frequency > decreasing_factor * prev_var_count + ): + new_log[variant] = frequency + already_added_sum = already_added_sum + frequency + prev_var_count = frequency + else: + break + + return IMDataStructureUVCL(new_log) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..12023567869b54e9e52622a970ee4770575fd220 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/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.algo.discovery.powl.inductive.variants import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e22a54bec56f0f290beccf266c3669a1059a74 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/__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.discovery.powl.inductive.variants.brute_force import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/bf_partial_order_cut.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/bf_partial_order_cut.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9fa21401afb2330991fe6281e16c2d013d62c3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/bf_partial_order_cut.py @@ -0,0 +1,244 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' + +from abc import ABC +from collections import Counter +from itertools import combinations +from typing import Any, Optional, Dict, List, Generic, Tuple, Collection + +from pm4py.algo.discovery.inductive.cuts.abc import Cut, T + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.BinaryRelation import BinaryRelation +from pm4py.objects.powl.obj import StrictPartialOrder, POWL +from pm4py.objects.dfg import util as dfu +from pm4py.statistics.eventually_follows.uvcl.get import apply as to_efg + + +def remove(blocks, g): + res = [] + for g2 in blocks: + if not g2.__str__().__eq__(g.__str__()): + res.append(g2) + return res + + +def contains(blocks, g): + for g2 in blocks: + if g2.__str__().__eq__(g.__str__()): + return True + return False + + +def xor(a, b): + if a and not b: + return True + elif not a and b: + return True + else: + return False + + +def get_partitions_of_size_k(nodes, k=None): + n = len(nodes) + if k is not None: + if k < 1: + raise ValueError( + "Can't partition in a negative or zero number of groups" + ) + elif k > n: + return + + def set_partitions_helper(l, k): + length = len(l) + if k == 1: + yield [tuple(l)] + elif length == k: + yield [tuple([s]) for s in l] + else: + e, *M = l + for p in set_partitions_helper(M, k - 1): + yield [tuple([e]), *p] + for p in set_partitions_helper(M, k): + for i in range(len(p)): + yield p[:i] + [tuple([e]) + p[i]] + p[i + 1:] + + if k is None: + for k in range(1, n + 1): + yield from set_partitions_helper(nodes, k) + else: + yield from set_partitions_helper(nodes, k) + + +def partition(collection): + i = len(collection) + while i > 1: + for part in get_partitions_of_size_k(collection, i): + yield part + i = i - 1 + return + + +def generate_order(parts, efg): + nodes = parts + po = BinaryRelation(nodes) + for group_1, group_2 in combinations(nodes, 2): + all_ef_g1_g2 = True + all_ef_g2_g1 = True + none_ef_g1_g2 = True + none_ef_g2_g1 = True + for a in group_1: + for b in group_2: + if (a, b) in efg: + none_ef_g1_g2 = False + else: + all_ef_g1_g2 = False + + if (b, a) in efg: + none_ef_g2_g1 = False + else: + all_ef_g2_g1 = False + + if all_ef_g1_g2 and none_ef_g2_g1: + po.add_edge(group_1, group_2) + elif none_ef_g1_g2 and all_ef_g2_g1: + po.add_edge(group_2, group_1) + + return po + + +def is_valid_order(po, dfg_graph, efg): + if not po.is_strict_partial_order(): + return False + + start_blocks = po.nodes + end_blocks = po.nodes + + for group_1, group_2 in combinations(po.nodes, 2): + + edge_g1_g2 = po.is_edge(group_1, group_2) + edge_g2_g1 = po.is_edge(group_2, group_1) + + if edge_g1_g2: + start_blocks = remove(start_blocks, group_2) + end_blocks = remove(end_blocks, group_1) + if edge_g2_g1: + start_blocks = remove(start_blocks, group_1) + end_blocks = remove(end_blocks, group_2) + + all_ef_g1_g2 = True + all_ef_g2_g1 = True + + for a in group_1: + for b in group_2: + if (a, b) not in efg: + all_ef_g1_g2 = False + if (b, a) not in efg: + all_ef_g2_g1 = False + if all_ef_g1_g2 and all_ef_g2_g1 and (edge_g1_g2 or edge_g2_g1): + return False + if ( + not edge_g1_g2 + and not edge_g2_g1 + and not (all_ef_g1_g2 and all_ef_g2_g1) + ): + return False + + n = len(po.nodes) + for i in range(n): + group = po.nodes[i] + c1 = contains(start_blocks, group) + c2 = ( + len( + set(group).intersection(set(dfg_graph.start_activities.keys())) + ) + > 0 + ) + c3 = contains(end_blocks, group) + c4 = ( + len(set(group).intersection(set(dfg_graph.end_activities.keys()))) + > 0 + ) + if (c1 and not c2) or (c3 and not c4): + return False + + return True + + +class BruteForcePartialOrderCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> StrictPartialOrder: + raise Exception("This function should not be called!") + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[BinaryRelation]: + dfg_graph = obj.dfg + efg = to_efg(obj) + alphabet = sorted( + dfu.get_vertices(dfg_graph), key=lambda g: g.__str__() + ) + for part in partition(alphabet): + po = generate_order(part, efg) + if is_valid_order(po, dfg_graph, efg): + return po + return None + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[StrictPartialOrder, List[POWL]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + children = cls.project(obj, g.nodes, parameters) + po = StrictPartialOrder(children) + for i, j in combinations(range(len(g.nodes)), 2): + if g.is_edge_id(i, j): + po.order.add_edge(children[i], children[j]) + elif g.is_edge_id(j, i): + po.order.add_edge(children[j], children[i]) + return po, po.children + + +class BruteForcePartialOrderCutUVCL( + BruteForcePartialOrderCut[IMDataStructureUVCL] +): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + r = list() + for g in groups: + c = Counter() + for t in obj.data_structure: + c[tuple(filter(lambda e: e in g, t))] = obj.data_structure[t] + r.append(c) + return list(map(lambda l: IMDataStructureUVCL(l), r)) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..a4460558972b4af2847b563127719a819201c3dd --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/brute_force/factory.py @@ -0,0 +1,68 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, Tuple, Type + +from pm4py.algo.discovery.powl.inductive.cuts.concurrency import ( + POWLConcurrencyCutUVCL, +) +from pm4py.algo.discovery.powl.inductive.cuts.factory import S, T, CutFactory +from pm4py.algo.discovery.powl.inductive.cuts.loop import POWLLoopCutUVCL +from pm4py.algo.discovery.powl.inductive.cuts.sequence import ( + POWLStrictSequenceCutUVCL, +) +from pm4py.algo.discovery.powl.inductive.cuts.xor import ( + POWLExclusiveChoiceCutUVCL, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.powl.inductive.variants.brute_force.bf_partial_order_cut import ( + BruteForcePartialOrderCutUVCL, ) +from pm4py.objects.powl.obj import POWL + + +class CutFactoryPOWLBruteForce(CutFactory): + + @classmethod + def get_cuts( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> List[Type[S]]: + if type(obj) is IMDataStructureUVCL: + return [ + POWLExclusiveChoiceCutUVCL, + POWLStrictSequenceCutUVCL, + POWLConcurrencyCutUVCL, + POWLLoopCutUVCL, + BruteForcePartialOrderCutUVCL, + ] + return list() + + @classmethod + def find_cut( + cls, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[POWL, List[T]]]: + for c in CutFactoryPOWLBruteForce.get_cuts(obj): + r = c.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0bac6e3f8ab6d98931fd8c737141ff202056bbd9 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/__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.discovery.powl.inductive.variants.dynamic_clustering import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/dynamic_clustering_partial_order_cut.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/dynamic_clustering_partial_order_cut.py new file mode 100644 index 0000000000000000000000000000000000000000..971e9a41516615d2a55fd2f3ad4f8a261a7e972a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/dynamic_clustering_partial_order_cut.py @@ -0,0 +1,213 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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 product +from abc import ABC +from itertools import combinations +from typing import Any, Optional, Dict, List, Generic, Tuple, Collection + +from pm4py.algo.discovery.inductive.cuts.abc import Cut, T +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.BinaryRelation import BinaryRelation +from pm4py.objects.powl.obj import StrictPartialOrder, POWL +from pm4py.algo.discovery.inductive.cuts import utils as cut_util +from pm4py.algo.discovery.powl.inductive.variants.maximal.maximal_partial_order_cut import ( + project_on_groups_with_unique_activities, ) +from pm4py.objects.dfg import util as dfu +from pm4py.statistics.eventually_follows.uvcl.get import apply as to_efg + + +def generate_order(clusters, efg): + # Step 0: if we have one single group containing all activities ---> + # invoke fall-through. + if len(clusters) < 2: + return None + + # Step 1: Generate Order based on the EFG + po = BinaryRelation([tuple(c) for c in sorted(clusters)]) + at_least_one_efg = [ + [False for _ in range(len(po.nodes))] for _ in range(len(po.nodes)) + ] + all_efg = [ + [True for _ in range(len(po.nodes))] for _ in range(len(po.nodes)) + ] + + changed = False + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + for a in cluster_1: + for b in cluster_2: + if (a, b) in efg: + at_least_one_efg[i][j] = True + else: + all_efg[i][j] = False + if (b, a) in efg: + at_least_one_efg[j][i] = True + else: + all_efg[j][i] = False + + if at_least_one_efg[i][j] and not at_least_one_efg[j][i]: + po.add_edge(cluster_1, cluster_2) + elif at_least_one_efg[j][i] and not at_least_one_efg[i][j]: + po.add_edge(cluster_2, cluster_1) + + # Step 2: Ensure Transitivity and Irreflexivity + if not po.is_transitive(): + n = len(po.nodes) + continue_loop = True + while continue_loop: + continue_loop = False + for i, j, k in product(range(n), range(n), range(n)): + if ( + i != j + and j != k + and po.edges[i][j] + and po.edges[j][k] + and not po.is_edge_id(i, k) + ): + if not at_least_one_efg[k][i]: + po.edges[i][k] = True + continue_loop = True + else: + clusters = cut_util.merge_lists_based_on_activities( + po.nodes[i][0], po.nodes[k][0], clusters + ) + return generate_order(clusters, efg) + + if not po.is_irreflexive(): + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if po.is_edge(cluster_1, cluster_2) and po.is_edge( + cluster_2, cluster_1 + ): + clusters = cut_util.merge_lists_based_on_activities( + cluster_1[0], cluster_2[0], clusters + ) + changed = True + + if changed: + return generate_order(clusters, efg) + + # # Step 3: Detect Choice + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if ( + not po.is_edge(cluster_1, cluster_2) + and not po.is_edge(cluster_2, cluster_1) + and not at_least_one_efg[i][j] + and not at_least_one_efg[j][i] + ): + clusters = cut_util.merge_lists_based_on_activities( + cluster_1[0], cluster_2[0], clusters + ) + changed = True + + if changed: + return generate_order(clusters, efg) + + # Step 4: Cluster nodes sharing the same pre- and post-sets. + pre = {node: [] for node in po.nodes} + post = {node: [] for node in po.nodes} + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if po.is_edge(cluster_1, cluster_2): + pre[cluster_2].append(cluster_1) + post[cluster_1].append(cluster_2) + elif po.is_edge(cluster_2, cluster_1): + pre[cluster_1].append(cluster_2) + post[cluster_2].append(cluster_1) + + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if ( + pre[cluster_1] == pre[cluster_2] + and post[cluster_1] == post[cluster_2] + ): + clusters = cut_util.merge_lists_based_on_activities( + cluster_1[0], cluster_2[0], clusters + ) + changed = True + + if changed and len(clusters) > 1: + return generate_order(clusters, efg) + else: + return po + + +class DynamicClusteringPartialOrderCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> StrictPartialOrder: + raise Exception("This function should not be called!") + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[BinaryRelation]: + alphabet = sorted(dfu.get_vertices(obj.dfg), key=lambda g: g.__str__()) + efg = to_efg(obj) + clusters = [[a] for a in alphabet] + po = generate_order(clusters, efg) + return po + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[StrictPartialOrder, List[POWL]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + children = cls.project(obj, g.nodes, parameters) + po = StrictPartialOrder(children) + for i, j in combinations(range(len(g.nodes)), 2): + if g.is_edge_id(i, j): + po.order.add_edge(children[i], children[j]) + elif g.is_edge_id(j, i): + po.order.add_edge(children[j], children[i]) + return po, po.children + + +class DynamicClusteringPartialOrderCutUVCL( + DynamicClusteringPartialOrderCut[IMDataStructureUVCL] +): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + return project_on_groups_with_unique_activities( + obj.data_structure, groups + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..2d9c9ffbaa30eb4c49d1f2fec3c7d29a8c11c439 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering/factory.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, Tuple + +from pm4py.algo.discovery.powl.inductive.cuts.factory import T, CutFactory +from pm4py.algo.discovery.powl.inductive.cuts.loop import POWLLoopCutUVCL +from pm4py.algo.discovery.powl.inductive.cuts.xor import ( + POWLExclusiveChoiceCutUVCL, +) +from pm4py.algo.discovery.powl.inductive.variants.dynamic_clustering.dynamic_clustering_partial_order_cut import ( + DynamicClusteringPartialOrderCutUVCL, ) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructure +from pm4py.objects.powl.obj import POWL +from pm4py.objects.dfg import util as dfu + + +class CutFactoryPOWLDynamicClustering(CutFactory): + + @classmethod + def get_cuts(cls, obj, parameters=None): + return [ + POWLExclusiveChoiceCutUVCL, + POWLLoopCutUVCL, + DynamicClusteringPartialOrderCutUVCL, + ] + + @classmethod + def find_cut( + cls, obj: IMDataStructure, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + alphabet = sorted(dfu.get_vertices(obj.dfg), key=lambda g: g.__str__()) + if len(alphabet) < 2: + return None + for c in CutFactoryPOWLDynamicClustering.get_cuts(obj): + r = c.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c209d7d3a4e9ece95b052cc261fbbb0c838b1442 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/__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.discovery.powl.inductive.variants.dynamic_clustering_frequency import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/dynamic_clustering_frequency_partial_order_cut.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/dynamic_clustering_frequency_partial_order_cut.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb0d9155d99dd58276c621c8a0432ad3e87efa3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/dynamic_clustering_frequency_partial_order_cut.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 itertools import product +from abc import ABC +from itertools import combinations +from typing import Any, Optional, Dict, List, Generic, Tuple, Collection + +from pm4py.algo.discovery.inductive.cuts.abc import Cut, T +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.BinaryRelation import BinaryRelation +from pm4py.objects.powl.obj import StrictPartialOrder, POWL +from pm4py.algo.discovery.inductive.cuts import utils as cut_util +from pm4py.algo.discovery.powl.inductive.variants.maximal.maximal_partial_order_cut import ( + project_on_groups_with_unique_activities, ) +from pm4py.objects.dfg import util as dfu + +ORDER_FREQUENCY_RATIO = "order frequency ratio" + + +def generate_order(obj: T, clusters, order_frequency_ratio): + # Step 0: if we have one single group containing all activities ---> + # invoke fall-through. + if len(clusters) < 2: + return None + + # Step 1: Generate Order based on the EFG + po = BinaryRelation([tuple(c) for c in sorted(clusters)]) + efg_freq = compute_efg_frequencies(obj, groups=po.nodes) + + changed = False + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + + sum_freq = ( + efg_freq[(cluster_1, cluster_2)] + + efg_freq[(cluster_2, cluster_1)] + ) + if sum_freq > 0: + if ( + float(efg_freq[(cluster_1, cluster_2)]) / sum_freq + ) >= order_frequency_ratio: + po.add_edge(cluster_1, cluster_2) + if ( + float(efg_freq[cluster_2, cluster_1]) / sum_freq + ) >= order_frequency_ratio: + po.add_edge(cluster_2, cluster_1) + + # Step 2: Ensure Transitivity and Irreflexivity + if not po.is_transitive(): + n = len(po.nodes) + continue_loop = True + while continue_loop: + continue_loop = False + for i, j, k in product(range(n), range(n), range(n)): + if ( + i != j + and j != k + and po.edges[i][j] + and po.edges[j][k] + and not po.is_edge_id(i, k) + ): + if ( + efg_freq[(po.nodes[k], po.nodes[i])] + + efg_freq[(po.nodes[i], po.nodes[k])] + == 0 + ): + po.edges[i][k] = True + continue_loop = True + else: + clusters = cut_util.merge_lists_based_on_activities( + po.nodes[i][0], po.nodes[k][0], clusters + ) + return generate_order( + obj, clusters, order_frequency_ratio + ) + + if not po.is_irreflexive(): + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if po.is_edge(cluster_1, cluster_2) and po.is_edge( + cluster_2, cluster_1 + ): + clusters = cut_util.merge_lists_based_on_activities( + cluster_1[0], cluster_2[0], clusters + ) + changed = True + + if changed: + return generate_order(obj, clusters, order_frequency_ratio) + + # # Step 3: Detect Choice + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if ( + not po.is_edge(cluster_1, cluster_2) + and not po.is_edge(cluster_2, cluster_1) + and efg_freq[(cluster_1, cluster_2)] == 0 + and efg_freq[(cluster_2, cluster_1)] == 0 + ): + clusters = cut_util.merge_lists_based_on_activities( + cluster_1[0], cluster_2[0], clusters + ) + changed = True + + if changed: + return generate_order(obj, clusters, order_frequency_ratio) + + # Step 4: Cluster nodes sharing the same pre- and post-sets. + pre = {node: [] for node in po.nodes} + post = {node: [] for node in po.nodes} + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if po.is_edge(cluster_1, cluster_2): + pre[cluster_2].append(cluster_1) + post[cluster_1].append(cluster_2) + elif po.is_edge(cluster_2, cluster_1): + pre[cluster_1].append(cluster_2) + post[cluster_2].append(cluster_1) + + for i in range(len(po.nodes)): + cluster_1 = po.nodes[i] + for j in range(i + 1, len(po.nodes)): + cluster_2 = po.nodes[j] + if ( + pre[cluster_1] == pre[cluster_2] + and post[cluster_1] == post[cluster_2] + ): + clusters = cut_util.merge_lists_based_on_activities( + cluster_1[0], cluster_2[0], clusters + ) + changed = True + + if changed and len(clusters) > 1: + return generate_order(obj, clusters, order_frequency_ratio) + else: + return po + + +def compute_efg_frequencies( + interval_log: IMDataStructureUVCL, groups +) -> Dict[Tuple[str, str], int]: + res = {(g1, g2): 0 for g1 in groups for g2 in groups} + + activity_to_cluster = {} + for cluster in groups: + for activity in cluster: + activity_to_cluster[activity] = cluster + + for trace, freq in interval_log.data_structure.items(): + seen_pairs = set() + for i in range(len(trace)): + cluster_1 = activity_to_cluster.get(trace[i]) + for j in range(i + 1, len(trace)): + cluster_2 = activity_to_cluster.get(trace[j]) + pair = (cluster_1, cluster_2) + if pair not in seen_pairs: + res[pair] += freq + seen_pairs.add(pair) + return res + + +class DynamicClusteringFrequencyPartialOrderCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> StrictPartialOrder: + raise Exception("This function should not be called!") + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[BinaryRelation]: + alphabet = sorted(dfu.get_vertices(obj.dfg), key=lambda g: g.__str__()) + clusters = [[a] for a in alphabet] + + if ORDER_FREQUENCY_RATIO in parameters.keys(): + order_frequency_ratio = parameters[ORDER_FREQUENCY_RATIO] + if not (0.5 < order_frequency_ratio <= 1.0): + raise ValueError( + "Parameter value of " + + ORDER_FREQUENCY_RATIO + + "must be in range: 0.5 < value <= 1.0" + ) + else: + order_frequency_ratio = 1.0 + + po = generate_order(obj, clusters, order_frequency_ratio) + return po + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[StrictPartialOrder, List[POWL]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + children = cls.project(obj, g.nodes, parameters) + po = StrictPartialOrder(children) + for i, j in combinations(range(len(g.nodes)), 2): + if g.is_edge_id(i, j): + po.order.add_edge(children[i], children[j]) + elif g.is_edge_id(j, i): + po.order.add_edge(children[j], children[i]) + return po, po.children + + +class DynamicClusteringFrequencyPartialOrderCutUVCL( + DynamicClusteringFrequencyPartialOrderCut[IMDataStructureUVCL] +): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + return project_on_groups_with_unique_activities( + obj.data_structure, groups + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..6441d17b0d33051824e171b1b894f34bec43952a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/dynamic_clustering_frequency/factory.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, Tuple + +from pm4py.algo.discovery.powl.inductive.cuts.factory import T, CutFactory +from pm4py.algo.discovery.powl.inductive.cuts.loop import POWLLoopCutUVCL +from pm4py.algo.discovery.powl.inductive.cuts.xor import ( + POWLExclusiveChoiceCutUVCL, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructure +from pm4py.algo.discovery.powl.inductive.variants.dynamic_clustering_frequency.dynamic_clustering_frequency_partial_order_cut import ( + DynamicClusteringFrequencyPartialOrderCutUVCL, ) +from pm4py.objects.powl.obj import POWL +from pm4py.objects.dfg import util as dfu + + +class CutFactoryPOWLDynamicClusteringFrequency(CutFactory): + + @classmethod + def get_cuts(cls, obj, parameters=None): + return [ + POWLExclusiveChoiceCutUVCL, + POWLLoopCutUVCL, + DynamicClusteringFrequencyPartialOrderCutUVCL, + ] + + @classmethod + def find_cut( + cls, obj: IMDataStructure, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + alphabet = sorted(dfu.get_vertices(obj.dfg), key=lambda g: g.__str__()) + if len(alphabet) < 2: + return None + for c in CutFactoryPOWLDynamicClusteringFrequency.get_cuts(obj): + r = c.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_brute_force.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_brute_force.py new file mode 100644 index 0000000000000000000000000000000000000000..ee13f3898139054c766195eb97f3038f89b317bc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_brute_force.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 Optional, Tuple, List, Dict, Any + +from pm4py.algo.discovery.powl.inductive.variants.brute_force.factory import ( + CutFactoryPOWLBruteForce, +) +from pm4py.algo.discovery.powl.inductive.variants.im_tree import IMBasePOWL, T +from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import ( + POWLDiscoveryVariant, ) +from pm4py.objects.powl.obj import POWL + + +class POWLInductiveMinerBruteForce(IMBasePOWL): + + def instance(self) -> POWLDiscoveryVariant: + return POWLDiscoveryVariant.BRUTE_FORCE + + def find_cut( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + res = CutFactoryPOWLBruteForce.find_cut(obj, parameters=parameters) + return res diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_dynamic_clustering.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_dynamic_clustering.py new file mode 100644 index 0000000000000000000000000000000000000000..c7f5c18289d263f66e549a28c1af0a99dace8a2a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_dynamic_clustering.py @@ -0,0 +1,46 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, Tuple, List, TypeVar, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureLog +from pm4py.algo.discovery.powl.inductive.variants.dynamic_clustering.factory import ( + CutFactoryPOWLDynamicClustering, ) +from pm4py.algo.discovery.powl.inductive.variants.im_tree import IMBasePOWL +from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import ( + POWLDiscoveryVariant, ) +from pm4py.objects.powl.obj import POWL + +T = TypeVar("T", bound=IMDataStructureLog) + + +class POWLInductiveMinerDynamicClustering(IMBasePOWL): + + def instance(self) -> POWLDiscoveryVariant: + return POWLDiscoveryVariant.DYNAMIC_CLUSTERING + + def find_cut( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + res = CutFactoryPOWLDynamicClustering.find_cut( + obj, parameters=parameters + ) + return res diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_dynamic_clustering_frequencies.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_dynamic_clustering_frequencies.py new file mode 100644 index 0000000000000000000000000000000000000000..f90fac959b52fd9d0ba94cb2c84cc85ec9ac1b60 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_dynamic_clustering_frequencies.py @@ -0,0 +1,46 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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, Tuple, List, TypeVar, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureLog +from pm4py.algo.discovery.powl.inductive.variants.dynamic_clustering_frequency.factory import ( + CutFactoryPOWLDynamicClusteringFrequency, ) +from pm4py.algo.discovery.powl.inductive.variants.im_tree import IMBasePOWL +from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import ( + POWLDiscoveryVariant, ) +from pm4py.objects.powl.obj import POWL + +T = TypeVar("T", bound=IMDataStructureLog) + + +class POWLInductiveMinerDynamicClusteringFrequency(IMBasePOWL): + + def instance(self) -> POWLDiscoveryVariant: + return POWLDiscoveryVariant.DYNAMIC_CLUSTERING + + def find_cut( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + res = CutFactoryPOWLDynamicClusteringFrequency.find_cut( + obj, parameters=parameters + ) + return res diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_maximal.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_maximal.py new file mode 100644 index 0000000000000000000000000000000000000000..4503e27cd0464d152d2dbc0711751a06e51a6416 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_maximal.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 typing import Optional, Tuple, List, Dict, Any + +from pm4py.algo.discovery.powl.inductive.variants.maximal.factory import ( + CutFactoryPOWLMaximal, +) +from pm4py.algo.discovery.powl.inductive.variants.im_tree import IMBasePOWL, T +from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import ( + POWLDiscoveryVariant, ) +from pm4py.objects.powl.obj import POWL + + +class POWLInductiveMinerMaximalOrder(IMBasePOWL): + + def instance(self) -> POWLDiscoveryVariant: + return POWLDiscoveryVariant.MAXIMAL + + def find_cut( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + res = CutFactoryPOWLMaximal.find_cut(obj, parameters=parameters) + return res diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_tree.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..3532ed7c9b017611bdc7bc0fe1d9d4ffb417c8ac --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/im_tree.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 itertools import combinations +from typing import Optional, Tuple, List, TypeVar, Generic, Dict, Any + +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.powl.inductive.fall_through.empty_traces import ( + POWLEmptyTracesUVCL, +) +from pm4py.algo.discovery.inductive.variants.abc import InductiveMinerFramework + +from pm4py.algo.discovery.powl.inductive.base_case.factory import ( + BaseCaseFactory, +) +from pm4py.algo.discovery.powl.inductive.cuts.factory import CutFactory +from pm4py.algo.discovery.powl.inductive.fall_through.factory import ( + FallThroughFactory, +) +from pm4py.algo.discovery.powl.inductive.utils.filtering import ( + FILTERING_TYPE, + FilteringType, + filter_most_frequent_variants, + FILTERING_THRESHOLD, + filter_most_frequent_variants_with_decreasing_factor, + DEFAULT_FILTERING_TYPE, +) +from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import ( + POWLDiscoveryVariant, ) + +from pm4py.objects.powl.obj import ( + POWL, + StrictPartialOrder, + Sequence, + OperatorPOWL, +) + +T = TypeVar("T", bound=IMDataStructureUVCL) + + +class IMBasePOWL(Generic[T], InductiveMinerFramework[T]): + + def instance(self) -> POWLDiscoveryVariant: + return POWLDiscoveryVariant.TREE + + def apply( + self, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> POWL: + if FILTERING_TYPE not in parameters.keys(): + filtering_type = DEFAULT_FILTERING_TYPE + else: + filtering_type = parameters[FILTERING_TYPE] + if filtering_type not in FilteringType: + raise KeyError( + "Invalid FILTERING_TYPE: " + str(filtering_type) + ) + + empty_traces = POWLEmptyTracesUVCL.apply(obj, parameters) + if empty_traces is not None: + return self._recurse(empty_traces[0], empty_traces[1], parameters) + + powl = self.apply_base_cases(obj, parameters) + if powl is not None: + return powl + + cut = self.find_cut(obj, parameters) + if cut is not None: + powl = self._recurse(cut[0], cut[1], parameters=parameters) + + if powl is not None: + return powl + else: + if filtering_type is FilteringType.DYNAMIC: + filtered_log = filter_most_frequent_variants( + obj.data_structure + ) + if len(filtered_log.data_structure) > 0: + return self.apply(filtered_log, parameters=parameters) + + elif filtering_type is FilteringType.DECREASING_FACTOR: + if FILTERING_THRESHOLD in parameters.keys(): + t = parameters[FILTERING_THRESHOLD] + if isinstance(t, float) and 0 <= t < 1: + if t > 0: + filtered_log = filter_most_frequent_variants_with_decreasing_factor( + obj.data_structure, decreasing_factor=t) + if ( + 0 + < len(filtered_log.data_structure) + < len(obj.data_structure) + ): + return self.apply( + filtered_log, parameters=parameters + ) + else: + raise KeyError("Invalid filtering threshold!") + else: + raise KeyError("Invalid filtering type!") + + ft = self.fall_through(obj, parameters) + return self._recurse(ft[0], ft[1], parameters=parameters) + + def apply_base_cases( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[POWL]: + return BaseCaseFactory.apply_base_cases(obj, parameters=parameters) + + def find_cut( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[POWL, List[T]]]: + return CutFactory.find_cut(obj, parameters=parameters) + + def fall_through( + self, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Tuple[POWL, List[T]]: + return FallThroughFactory.fall_through( + obj, self._pool, self._manager, parameters=parameters + ) + + def _recurse( + self, + powl: POWL, + objs: List[T], + parameters: Optional[Dict[str, Any]] = None, + ): + children = [self.apply(obj, parameters=parameters) for obj in objs] + if isinstance(powl, StrictPartialOrder): + powl_new = StrictPartialOrder(children) + for i, j in combinations(range(len(powl.children)), 2): + if powl.order.is_edge_id(i, j): + powl_new.order.add_edge(children[i], children[j]) + elif powl.order.is_edge_id(j, i): + powl_new.order.add_edge(children[j], children[i]) + return powl_new + else: + new_powl = OperatorPOWL(operator=powl.operator, children=children) + return new_powl diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79178c28ef8af94b928ddf4198634a9f3b4289cc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/__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.discovery.powl.inductive.variants.maximal import * diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/factory.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..af1835c49b255a44d902c35c5d597cc4159b0e3a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/factory.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 typing import List, Optional, Dict, Any, Tuple, Type + +from pm4py.algo.discovery.powl.inductive.cuts.concurrency import ( + POWLConcurrencyCutUVCL, +) +from pm4py.algo.discovery.powl.inductive.cuts.factory import S, T, CutFactory +from pm4py.algo.discovery.powl.inductive.cuts.loop import POWLLoopCutUVCL +from pm4py.algo.discovery.powl.inductive.cuts.sequence import ( + POWLStrictSequenceCutUVCL, +) +from pm4py.algo.discovery.powl.inductive.cuts.xor import ( + POWLExclusiveChoiceCutUVCL, +) +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.algo.discovery.powl.inductive.variants.maximal.maximal_partial_order_cut import ( + MaximalPartialOrderCutUVCL, ) +from pm4py.objects.powl.obj import POWL +from pm4py.objects.dfg import util as dfu + + +class CutFactoryPOWLMaximal(CutFactory): + + @classmethod + def get_cuts( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> List[Type[S]]: + if type(obj) is IMDataStructureUVCL: + return [ + POWLExclusiveChoiceCutUVCL, + POWLStrictSequenceCutUVCL, + POWLConcurrencyCutUVCL, + POWLLoopCutUVCL, + MaximalPartialOrderCutUVCL, + ] + return list() + + @classmethod + def find_cut( + cls, + obj: IMDataStructureUVCL, + parameters: Optional[Dict[str, Any]] = None, + ) -> Optional[Tuple[POWL, List[T]]]: + + alphabet = sorted(dfu.get_vertices(obj.dfg), key=lambda g: g.__str__()) + if len(alphabet) < 2: + return None + for c in CutFactoryPOWLMaximal.get_cuts(obj): + r = c.apply(obj, parameters) + if r is not None: + return r + return None diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/maximal_partial_order_cut.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/maximal_partial_order_cut.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e33b51994494a7c9b72335503371d9ad6286d4 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/maximal/maximal_partial_order_cut.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 +''' + +from abc import ABC +from collections import Counter +from itertools import combinations +from typing import Any, Optional, Dict, List, Generic, Tuple, Collection + +from pm4py.algo.discovery.inductive.cuts.abc import Cut, T +from pm4py.algo.discovery.inductive.dtypes.im_ds import IMDataStructureUVCL +from pm4py.objects.powl.BinaryRelation import BinaryRelation +from pm4py.objects.powl.obj import StrictPartialOrder, POWL +from pm4py.objects.dfg import util as dfu +from pm4py.statistics.eventually_follows.uvcl.get import apply as to_efg + + +def generate_initial_order(nodes, efg): + po = BinaryRelation(nodes) + for a, b in combinations(nodes, 2): + if (a, b) in efg: + if (b, a) not in efg: + po.add_edge(a, b) + else: + if (b, a) in efg: + po.add_edge(b, a) + return po + + +def remove(blocks, g): + res = [] + for g2 in blocks: + if not g2.__str__().__eq__(g.__str__()): + res.append(g2) + return res + + +def contains(blocks, g): + for g2 in blocks: + if g2.__str__().__eq__(g.__str__()): + return True + return False + + +def is_valid_order(po, efg, start_activities, end_activities): + if po is None: + return False + + if len(po.nodes) < 2: + return False + + if not po.is_strict_partial_order(): + return False + + start_blocks = po.nodes + end_blocks = po.nodes + + for group_1, group_2 in combinations(po.nodes, 2): + + edge_g1_g2 = po.is_edge(group_1, group_2) + edge_g2_g1 = po.is_edge(group_2, group_1) + + if edge_g1_g2: + start_blocks = remove(start_blocks, group_2) + end_blocks = remove(end_blocks, group_1) + if edge_g2_g1: + start_blocks = remove(start_blocks, group_1) + end_blocks = remove(end_blocks, group_2) + + all_ef_g1_g2 = True + all_ef_g2_g1 = True + + for a in group_1: + for b in group_2: + if (a, b) not in efg: + all_ef_g1_g2 = False + if (b, a) not in efg: + all_ef_g2_g1 = False + if all_ef_g1_g2 and all_ef_g2_g1 and (edge_g1_g2 or edge_g2_g1): + return False + if ( + not edge_g1_g2 + and not edge_g2_g1 + and not (all_ef_g1_g2 and all_ef_g2_g1) + ): + return False + + n = len(po.nodes) + for i in range(n): + group = po.nodes[i] + c1 = contains(start_blocks, group) + c2 = len(set(group).intersection(start_activities)) > 0 + c3 = contains(end_blocks, group) + c4 = len(set(group).intersection(end_activities)) > 0 + if (c1 and not c2) or (c3 and not c4): + return False + + return True + + +def cluster_order(binary_relation): + pre = {node: set() for node in binary_relation.nodes} + post = {node: set() for node in binary_relation.nodes} + for node1 in binary_relation.nodes: + for node2 in binary_relation.nodes: + if binary_relation.is_edge(node1, node2): + pre[node2].add(node1) + post[node1].add(node2) + + clusters = [] + for node in binary_relation.nodes: + matched = False + for i in range(len(clusters)): + cluster = clusters[i] + if pre[node] == pre[cluster[0]] and post[node] == post[cluster[0]]: + clusters[i].append(node) + matched = True + break + if not matched: + clusters.append([node]) + + new_relation = BinaryRelation([tuple(c) for c in clusters]) + for cluster1 in new_relation.nodes: + for cluster2 in new_relation.nodes: + node1 = cluster1[0] + node2 = cluster2[0] + if binary_relation.is_edge(node1, node2): + new_relation.add_edge(cluster1, cluster2) + + return new_relation + + +class MaximalPartialOrderCut(Cut[T], ABC, Generic[T]): + + @classmethod + def operator( + cls, parameters: Optional[Dict[str, Any]] = None + ) -> StrictPartialOrder: + raise Exception("This function should not be called!") + + @classmethod + def holds( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[BinaryRelation]: + + efg = to_efg(obj) + alphabet = sorted(dfu.get_vertices(obj.dfg), key=lambda g: g.__str__()) + po = generate_initial_order(alphabet, efg) + clustered_po = cluster_order(po) + + start_activities = set(list(obj.dfg.start_activities.keys())) + end_activities = set(list(obj.dfg.end_activities.keys())) + if is_valid_order(clustered_po, efg, start_activities, end_activities): + return clustered_po + else: + return None + + @classmethod + def apply( + cls, obj: T, parameters: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[StrictPartialOrder, List[POWL]]]: + g = cls.holds(obj, parameters) + if g is None: + return g + children = cls.project(obj, g.nodes, parameters) + po = StrictPartialOrder(children) + for i, j in combinations(range(len(g.nodes)), 2): + if g.is_edge_id(i, j): + po.order.add_edge(children[i], children[j]) + elif g.is_edge_id(j, i): + po.order.add_edge(children[j], children[i]) + return po, po.children + + +def project_on_groups_with_unique_activities( + log: Counter, groups: List[Collection[Any]] +): + r = list() + for g in groups: + new_log = Counter() + for var, freq in log.items(): + new_var = [] + for activity in var: + if activity in g: + new_var.append(activity) + new_var_tuple = tuple(new_var) + if new_var_tuple in new_log.keys(): + new_log[new_var_tuple] = new_log[new_var_tuple] + freq + else: + new_log[new_var_tuple] = freq + r.append(new_log) + return list(map(lambda l: IMDataStructureUVCL(l), r)) + + +class MaximalPartialOrderCutUVCL(MaximalPartialOrderCut[IMDataStructureUVCL]): + + @classmethod + def project( + cls, + obj: IMDataStructureUVCL, + groups: List[Collection[Any]], + parameters: Optional[Dict[str, Any]] = None, + ) -> List[IMDataStructureUVCL]: + return project_on_groups_with_unique_activities( + obj.data_structure, groups + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/powl_discovery_varaints.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/powl_discovery_varaints.py new file mode 100644 index 0000000000000000000000000000000000000000..ca899a90f8c847253b608e5e6923e50ba3f8cea2 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/powl/inductive/variants/powl_discovery_varaints.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 enum import Enum, auto + + +class POWLDiscoveryVariant(Enum): + TREE = auto() # base IM with no partial orders + BRUTE_FORCE = auto() + MAXIMAL = auto() + DYNAMIC_CLUSTERING = auto() diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..53a5976526579ec2398d28dc5753dfec08767558 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/__init__.py @@ -0,0 +1,35 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public 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.split_miner import ( + algorithm, + bpmn_export, + bpmn_init, + sese, + concurrency, + dfg_discovery, + dtypes, + filtering, + joins, + or_min, + splits, + variants, +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/algorithm.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..8012799fe069549b27384bad5b7225fd103f70d0 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/algorithm.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 +''' +"""Top-level dispatcher for Split Miner. + +Two variants are exposed: + +* :data:`CLASSIC` — the classic Split Miner pipeline. +* :data:`SM2` — Split Miner 2.0: the same machinery driven by a + lifecycle-aware ``complete``-event DFG, an overlap-based concurrency + oracle for genuine lifecycle logs, a fixed frequency threshold + (``eta = 1.0``), inclusive joins left in place (``replaceIORs = false``) + plus the OR-split heuristic, and compact (marked) self-loops. + +Both variants return a :class:`pm4py.objects.bpmn.obj.BPMN`. + +Faithfulness and validation +--------------------------- +Every stage (DFG filtering, concurrency oracle, Oracle split discovery, +RPST-based SESE join discovery, OR-join replacement, gateway collapse) +is a port of the reference Java Split Miner, intended to reproduce its +output exactly rather than the idealised figures in the papers. The +ports were validated against the original Java tools on the SM-Experiment +corpus: classic Split Miner is byte-identical (isomorphic, same gateway +labels) to ``splitminer.jar`` on the deterministic real-life logs, and +SM2 is byte-identical to ``sm2.jar`` (``MineWithSMTC``) on 9 of 10 +reference logs (the tenth is non-deterministic in the Java tool itself). +Because the target is the *tool*, not the papers, some hand-computed +gateway counts from earlier tests changed: e.g. on the Augusto et al. +(2019) running example the tool yields 2 AND-splits / 4 XOR-splits, not +the 1 / 3 from the paper. +""" +from enum import Enum +from typing import Any, Dict, Optional, Tuple, Union + +import pandas as pd + +from pm4py.algo.discovery.split_miner.variants import classic, sm2 +from pm4py.objects.bpmn.obj import BPMN +from pm4py.objects.log.obj import EventLog, EventStream +from pm4py.util import exec_utils + + +class Variants(Enum): + CLASSIC = classic + SM2 = sm2 + + +CLASSIC = Variants.CLASSIC +SM2 = Variants.SM2 +DEFAULT_VARIANT = CLASSIC + +VERSIONS = {CLASSIC, SM2} + + +def apply( + log: Union[ + EventLog, EventStream, pd.DataFrame, Dict[Tuple[str, str], int] + ], + parameters: Optional[Dict[Any, Any]] = None, + variant: Variants = DEFAULT_VARIANT, +) -> BPMN: + """Discover a BPMN model from a log using Split Miner. + + Parameters + ---------- + log + Event log (``EventLog`` / ``EventStream`` / ``pandas.DataFrame``) + or a precomputed DFG (only accepted by the classic variant). + parameters + Variant-specific parameters; see ``classic.Parameters`` and + ``sm2.Parameters`` for the supported keys. The classic variant + honors ``EPSILON``, ``ETA``, ``OR_MINIMISE`` and + ``ACTIVITY_KEY``; the SM2 variant honors ``EPSILON``, + ``ACTIVITY_KEY`` and ``TIMESTAMP_KEY`` and ignores ``ETA`` and + ``OR_MINIMISE`` (pinned to the reference tool's fixed values). + variant + Either :data:`CLASSIC` (default) or :data:`SM2`. + """ + return exec_utils.get_variant(variant).apply(log, parameters=parameters) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d511e3f2632b9b4b690c6965c89e8f26fdc9517 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/__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.discovery.split_miner.bpmn_export import abc, classic, lifecycle diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..bf10dbf18952539c77e74c9d5473bcf52654ed31 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/abc.py @@ -0,0 +1,40 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Abstract base class for the BPMN-export phase.""" +from abc import ABC, abstractmethod +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph +from pm4py.objects.bpmn.obj import BPMN + + +class BPMNExporter(ABC): + """Convert the internal :class:`WorkingGraph` into a pm4py BPMN object.""" + + @classmethod + @abstractmethod + def apply( + cls, + wg: WorkingGraph, + parameters: Optional[Dict[str, Any]] = None, + ) -> BPMN: + ... diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..869caf5e6c8d237de0b0bb881430b248e6412b4e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/classic.py @@ -0,0 +1,118 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Convert :class:`WorkingGraph` into a pm4py :class:`BPMN`. + +Self-loops detected during the loops phase are reattached here by +wrapping the looped task with an XOR-join (predecessor side) and an +XOR-split (successor side) that connects back to the join. +""" +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.bpmn_export.abc import BPMNExporter +from pm4py.algo.discovery.split_miner.dtypes.log import END_LABEL, START_LABEL +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph +from pm4py.objects.bpmn.obj import BPMN + + +def _make_node(kind: str, label: str, node_id: str) -> BPMN.BPMNNode: + if kind == "start": + return BPMN.StartEvent(id=node_id, name="") + if kind == "end": + return BPMN.EndEvent(id=node_id, name="") + if kind == "task": + return BPMN.Task(id=node_id, name=label) + if kind == "xor": + return BPMN.ExclusiveGateway(id=node_id, name="") + if kind == "and": + return BPMN.ParallelGateway(id=node_id, name="") + if kind == "or": + return BPMN.InclusiveGateway(id=node_id, name="") + raise ValueError(f"Unknown node kind: {kind}") + + +class ClassicBPMNExporter(BPMNExporter): + """Materialise the pm4py :class:`BPMN` from the working graph.""" + + @classmethod + def apply( + cls, + wg: WorkingGraph, + parameters: Optional[Dict[str, Any]] = None, + ) -> BPMN: + bpmn = BPMN() + node_map: Dict[str, BPMN.BPMNNode] = {} + for nid, n in wg.nodes.items(): + bnode = _make_node(n.kind, n.label, nid) + bpmn.add_node(bnode) + node_map[nid] = bnode + + for src, tgt in wg.edges(): + bpmn.add_flow( + BPMN.SequenceFlow(node_map[src], node_map[tgt]) + ) + + # Sort to keep self-loop attachment order independent of + # hash randomization; semantically the model is the same, but + # node/flow ids and rendering order are then reproducible. + for task_id in sorted(wg.self_loops, reverse=True): + if task_id not in node_map: + continue + if task_id in {START_LABEL, END_LABEL}: + continue + cls._attach_self_loop(bpmn, node_map, task_id) + return bpmn + + # ------------------------------------------------------------------ + # helpers + # ------------------------------------------------------------------ + + @staticmethod + def _attach_self_loop( + bpmn: BPMN, + node_map: Dict[str, BPMN.BPMNNode], + task_id: str, + ) -> None: + task_node = node_map[task_id] + in_flows = [ + f for f in bpmn.get_flows() if f.get_target() is task_node + ] + out_flows = [ + f for f in bpmn.get_flows() if f.get_source() is task_node + ] + + loop_join = BPMN.ExclusiveGateway(id=f"{task_id}__loop_join", name="") + loop_split = BPMN.ExclusiveGateway(id=f"{task_id}__loop_split", name="") + bpmn.add_node(loop_join) + bpmn.add_node(loop_split) + + for f in in_flows: + src = f.get_source() + bpmn.remove_flow(f) + bpmn.add_flow(BPMN.SequenceFlow(src, loop_join)) + for f in out_flows: + tgt = f.get_target() + bpmn.remove_flow(f) + bpmn.add_flow(BPMN.SequenceFlow(loop_split, tgt)) + + bpmn.add_flow(BPMN.SequenceFlow(loop_join, task_node)) + bpmn.add_flow(BPMN.SequenceFlow(task_node, loop_split)) + bpmn.add_flow(BPMN.SequenceFlow(loop_split, loop_join)) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/lifecycle.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..7390254fff5fd4df31fc88215ab9f47b07f54de6 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_export/lifecycle.py @@ -0,0 +1,68 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""BPMN export for Split Miner 2.0. + +Differs from the classic exporter in how level-1 (self) loops are +rendered. Classic Split Miner expands every self-looping task into an +explicit XOR-join / XOR-split pair with a back edge; Split Miner 2.0 +keeps the task compact and marks it as a looping activity (the Java side +attaches ``standardLoopCharacteristics``), adding no extra gateways. +""" +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.bpmn_export.abc import BPMNExporter +from pm4py.algo.discovery.split_miner.bpmn_export.classic import _make_node +from pm4py.algo.discovery.split_miner.dtypes.log import END_LABEL, START_LABEL +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph +from pm4py.objects.bpmn.obj import BPMN + + +class LifecycleBPMNExporter(BPMNExporter): + """Materialize the BPMN, keeping self-loops as marked activities.""" + + @classmethod + def apply( + cls, + wg: WorkingGraph, + parameters: Optional[Dict[str, Any]] = None, + ) -> BPMN: + bpmn = BPMN() + node_map: Dict[str, BPMN.BPMNNode] = {} + for nid, n in wg.nodes.items(): + bnode = _make_node(n.kind, n.label, nid) + bpmn.add_node(bnode) + node_map[nid] = bnode + + for src, tgt in wg.edges(): + bpmn.add_flow(BPMN.SequenceFlow(node_map[src], node_map[tgt])) + + # Mark self-looping tasks (no XOR expansion). The Java side + # serializes this as ``standardLoopCharacteristics``; pm4py's + # BPMN exporter has no equivalent, so the attribute is purely + # informational for downstream consumers of the BPMN object. + for task_id in wg.self_loops: + if task_id in {START_LABEL, END_LABEL}: + continue + node = node_map.get(task_id) + if node is not None: + setattr(node, "_sm_looped", True) + return bpmn diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ced04efd225dfd3b7954c7d0407fb53a62963b3c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/__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.discovery.split_miner.bpmn_init import abc, classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..bd327881fa63cc63a496d3bb30549c4246ae0d93 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/abc.py @@ -0,0 +1,46 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Abstract base class for the BPMN-initialisation phase.""" +from abc import ABC, abstractmethod +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.dtypes.concurrency import ( + ConcurrencyResult, +) +from pm4py.algo.discovery.split_miner.dtypes.filtering import FilterResult +from pm4py.algo.discovery.split_miner.dtypes.loops import LoopInfo +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph + + +class BPMNInitializer(ABC): + """Materialise a :class:`WorkingGraph` from the filtered PDFG.""" + + @classmethod + @abstractmethod + def apply( + cls, + filtered: FilterResult, + concurrency: ConcurrencyResult, + loops: LoopInfo, + parameters: Optional[Dict[str, Any]] = None, + ) -> WorkingGraph: + """Return a fresh working graph ready for the splits phase.""" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..b8dfe1b730b8ef62f70363f981006704f3a7c4dc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/bpmn_init/classic.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 +''' +"""Initial BPMN construction from a filtered PDFG. + +Sentinel start / end labels in the filtered DFG become the BPMN start +and end events; every other node becomes a task. Concurrency and self- +loop metadata is attached to the working graph for the later phases. +""" +from typing import Any, Dict, Optional, Set + +from pm4py.algo.discovery.split_miner.bpmn_init.abc import BPMNInitializer +from pm4py.algo.discovery.split_miner.dtypes.concurrency import ( + ConcurrencyResult, +) +from pm4py.algo.discovery.split_miner.dtypes.filtering import FilterResult +from pm4py.algo.discovery.split_miner.dtypes.log import END_LABEL, START_LABEL +from pm4py.algo.discovery.split_miner.dtypes.loops import LoopInfo +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph + + +class ClassicBPMNInitializer(BPMNInitializer): + """Build a fresh working graph from a filtered PDFG and metadata.""" + + @classmethod + def apply( + cls, + filtered: FilterResult, + concurrency: ConcurrencyResult, + loops: LoopInfo, + parameters: Optional[Dict[str, Any]] = None, + ) -> WorkingGraph: + wg = WorkingGraph() + + # The filtered edge set is a Python ``set``; iterating it directly + # would expose ``PYTHONHASHSEED``-dependent ordering and make the + # whole pipeline non-deterministic across processes. Sort once + # here so every downstream phase sees a stable order of edges + # and node-insertion. + sorted_edges = sorted(filtered.edges, reverse=True) + + nodes: Set[str] = set() + for a, b in sorted_edges: + nodes.add(a) + nodes.add(b) + nodes.add(filtered.source) + nodes.add(filtered.sink) + + for label in sorted(nodes, reverse=True): + if label == START_LABEL: + wg.add_node("start", label="start", node_id=label) + wg.start_id = label + elif label == END_LABEL: + wg.add_node("end", label="end", node_id=label) + wg.end_id = label + else: + wg.add_node("task", label=label, node_id=label) + + for a, b in sorted_edges: + wg.add_edge(a, b) + + wg.concurrency = set(concurrency.concurrent_pairs) + wg.self_loops = set(loops.self_loops) + return wg diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79dc75c95c34df6177d0a14c0edb83d6ccad2c3d --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/__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.discovery.split_miner.concurrency import abc, classic, lifecycle diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f61c2d62637a97c851b82f2b914f26dd40a501 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/abc.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 +''' +"""Abstract base class for the concurrency-discovery phase. + +A :class:`ConcurrencyOracle` takes a DFG (and, optionally, the underlying +trace list) and returns both the set of unordered concurrent pairs and +the *pruned* DFG with the concurrent arcs removed. +""" +from abc import ABC, abstractmethod +from typing import Any, Dict, List, Optional, TypeVar + +from pm4py.algo.discovery.split_miner.dtypes.concurrency import ( + ConcurrencyResult, +) +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG +from pm4py.algo.discovery.split_miner.dtypes.loops import LoopInfo + + +TraceT = TypeVar("TraceT") + + +class ConcurrencyOracle(ABC): + """Detect concurrent activity pairs and prune the DFG accordingly.""" + + @classmethod + @abstractmethod + def apply( + cls, + dfg: DFG, + traces: Optional[List[TraceT]], + loops: LoopInfo, + parameters: Optional[Dict[str, Any]] = None, + ) -> ConcurrencyResult: + """Return the pruned DFG together with the concurrency relation.""" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..8602201c35c8d71cedb22362403cc38f48720a99 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/classic.py @@ -0,0 +1,177 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Classic Split Miner concurrency oracle. + +Two activities ``a`` and ``b`` are concurrent when they appear as both +``a -> b`` and ``b -> a`` in the DFG, are not a short-loop pair, and the +bidirectional frequencies are roughly balanced (imbalance under epsilon). + +When an imbalanced bidirectional pair is detected the less frequent +direction is dropped instead and concurrency is *not* recorded. + +Both pruning operations are performed greedily in ascending-frequency +order and respect a connectedness invariant inherited from the +reference Java implementation: an edge is only dropped when its source +retains another outgoing edge *and* its target retains another incoming +edge in the pruned DFG. When the favoured direction cannot be dropped +the algorithm falls back to dropping the opposite direction (if that is +itself removable) and demotes the pair from concurrent to sequential, +mirroring the behaviour of ``DirectlyFollowGraphPlus.removeEdge`` with +``ensureConnectedness=true``. +""" +from enum import Enum +from typing import Any, Dict, FrozenSet, List, Optional, Set, Tuple + +from pm4py.algo.discovery.split_miner.concurrency.abc import ConcurrencyOracle +from pm4py.algo.discovery.split_miner.dtypes.concurrency import ( + ConcurrencyResult, +) +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG +from pm4py.algo.discovery.split_miner.dtypes.loops import LoopInfo +from pm4py.util import exec_utils + + +class Parameters(Enum): + EPSILON = "split_miner_epsilon" + + +DEFAULT_EPSILON = 0.1 + + +class ClassicConcurrencyOracle(ConcurrencyOracle): + """Imbalance test on directly-follows frequencies, with a + connectedness guard that prevents pruning from isolating any task. + """ + + @classmethod + def apply( + cls, + dfg: DFG, + traces: Optional[List[Any]], # unused (kept to share signature) + loops: LoopInfo, + parameters: Optional[Dict[str, Any]] = None, + ) -> ConcurrencyResult: + eps = exec_utils.get_param_value( + Parameters.EPSILON, parameters or {}, DEFAULT_EPSILON + ) + + # Live in/out degree per node in the working DFG. The oracle + # mutates these counters as it drops edges so the connectedness + # guard reflects intermediate state, exactly like Java's + # incomings/outgoings maps. + out_count: Dict[str, int] = {} + in_count: Dict[str, int] = {} + for (a, b) in dfg.keys(): + out_count[a] = out_count.get(a, 0) + 1 + in_count[b] = in_count.get(b, 0) + 1 + + # Candidate drops, paired with their frequencies. For every + # bidirectional pair both directions are queued when the pair is + # balanced enough to be concurrent; when imbalanced only the + # weaker direction is queued (and concurrency is not asserted). + # ``pair_kind`` records whether each queued drop belongs to a + # concurrent pair (``"par"``) or an imbalance demotion + # (``"imb"``); this drives the bookkeeping that demotes + # concurrency back to a sequence arc when a removal is vetoed by + # the connectedness guard. + candidates: List[Tuple[Tuple[str, str], int]] = [] + pair_kind: Dict[Tuple[str, str], str] = {} + concurrent_pairs: Set[FrozenSet[str]] = set() + seen: Set[FrozenSet[str]] = set() + + # Deterministic iteration: sorting up front keeps the set of + # candidate pairs identical across runs regardless of dict + # insertion order. + for (a, b), f_ab in sorted(dfg.items()): + if a == b: + continue + pair = frozenset((a, b)) + if pair in seen: + continue + seen.add(pair) + + f_ba = dfg.get((b, a), 0) + if f_ab <= 0 or f_ba <= 0: + continue + if pair in loops.short_loops: + continue + + denom = f_ab + f_ba + imbalance = abs(f_ab - f_ba) / denom + + # Reference uses a strict comparison (Math.abs(score) < + # parallelismsThreshold); a pair whose imbalance is exactly + # epsilon is NOT concurrent. + if imbalance < eps: + concurrent_pairs.add(pair) + candidates.append(((a, b), f_ab)) + candidates.append(((b, a), f_ba)) + pair_kind[(a, b)] = "par" + pair_kind[(b, a)] = "par" + else: + drop = (a, b) if f_ab < f_ba else (b, a) + drop_f = min(f_ab, f_ba) + candidates.append((drop, drop_f)) + pair_kind[drop] = "imb" + + # Process candidate drops in ascending-frequency order so the + # least informative arcs are challenged by the guard first + # (matching Collections.sort on Java's DFGEdge). + candidates.sort(key=lambda x: (x[1], x[0])) + + to_drop: Set[Tuple[str, str]] = set() + + def _can_drop(edge: Tuple[str, str]) -> bool: + a, b = edge + return out_count.get(a, 0) > 1 and in_count.get(b, 0) > 1 + + def _do_drop(edge: Tuple[str, str]) -> None: + a, b = edge + to_drop.add(edge) + out_count[a] -= 1 + in_count[b] -= 1 + + for edge, _f in candidates: + if edge in to_drop: + continue + if _can_drop(edge): + _do_drop(edge) + continue + # Connectedness guard vetoed the drop. For concurrent pairs + # this demotes the pair to a sequence arc: discard the pair + # from ``concurrent_pairs`` and instead try to drop the + # reverse direction (if it has not been dropped already and + # the guard allows it). + a, b = edge + if pair_kind.get(edge) == "par": + concurrent_pairs.discard(frozenset((a, b))) + reverse = (b, a) + if reverse in dfg and reverse not in to_drop and _can_drop(reverse): + _do_drop(reverse) + # Imbalance drops vetoed by the guard simply stay in the + # DFG; Java behaves the same way (the edge survives because + # removing it would orphan a node). + + pdfg: DFG = { + (a, b): f for (a, b), f in dfg.items() if (a, b) not in to_drop + } + return ConcurrencyResult(pdfg=pdfg, concurrent_pairs=concurrent_pairs) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/lifecycle.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1280d76de1f9e57b5297eb8d75eea9234a8feb --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/lifecycle.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 +''' +"""Lifecycle (overlap-based) concurrency oracle for Split Miner 2.0. + +Faithful port of ``DirectlyFollowGraphPlus.detectParallelismsFromComplex +Log``. Unlike the classic oracle — which infers concurrency from a +*balanced bidirectional* directly-follows pair — this oracle marks two +activities concurrent when their execution intervals overlap often +enough: ``relativeConcurrency[a][b] = overlap[a][b] / (obs[a] + obs[b])`` +exceeds ``epsilon``. Each such directly-follows edge is then dropped +under the same connectedness guard the classic oracle uses; a vetoed +removal demotes the pair and drops the opposite direction instead. +""" +from typing import Dict, FrozenSet, List, Set, Tuple + +from pm4py.algo.discovery.split_miner.dtypes.concurrency import ( + ConcurrencyResult, +) +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG + + +def apply_overlap_concurrency( + dfg: DFG, + overlap: Dict[FrozenSet[str], int], + observed: Dict[str, int], + eps: float, +) -> ConcurrencyResult: + """Detect concurrency from lifecycle overlaps on a complex log.""" + out_count: Dict[str, int] = {} + in_count: Dict[str, int] = {} + for (a, b) in dfg.keys(): + out_count[a] = out_count.get(a, 0) + 1 + in_count[b] = in_count.get(b, 0) + 1 + + # Directly-follows edges whose endpoints overlap often enough are + # candidate parallelisms. Java thresholds the *directed* relative + # concurrency, but the matrix is symmetric, so a frozenset lookup is + # equivalent. + potential: List[Tuple[Tuple[str, str], int]] = [] + for (a, b), f in dfg.items(): + if a == b: + continue + ov = overlap.get(frozenset((a, b)), 0) + if ov <= 0: + continue + denom = observed.get(a, 0) + observed.get(b, 0) + if denom <= 0: + continue + if ov / denom > eps: + potential.append(((a, b), f)) + + # Ascending frequency (then lexicographic edge) reproduces + # Collections.sort on Java's DFGEdge. + potential.sort(key=lambda x: (x[1], x[0])) + + removed: Set[Tuple[str, str]] = set() + concurrent_pairs: Set[FrozenSet[str]] = set() + + def _can_drop(edge: Tuple[str, str]) -> bool: + a, b = edge + return out_count.get(a, 0) > 1 and in_count.get(b, 0) > 1 + + def _do_drop(edge: Tuple[str, str]) -> None: + a, b = edge + removed.add(edge) + out_count[a] -= 1 + in_count[b] -= 1 + + for edge, _f in potential: + if edge in removed: + continue + src, tgt = edge + if _can_drop(edge): + _do_drop(edge) + concurrent_pairs.add(frozenset((src, tgt))) + else: + # Guard veto: demote the pair and drop the opposite + # direction instead (Java removes dfgp[tgt][src]). + concurrent_pairs.discard(frozenset((src, tgt))) + reverse = (tgt, src) + if ( + reverse in dfg + and reverse not in removed + and _can_drop(reverse) + ): + _do_drop(reverse) + + pdfg: DFG = { + (a, b): f for (a, b), f in dfg.items() if (a, b) not in removed + } + return ConcurrencyResult(pdfg=pdfg, concurrent_pairs=concurrent_pairs) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/refined.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/refined.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc6f315f831d6f8630232bbdffe441ece59a5b --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/concurrency/refined.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 +''' +"""Removed module — compatibility shim. + +``concurrency.refined.RefinedConcurrencyOracle`` was the +approximate lifecycle-overlap oracle of the earlier Split Miner 2.0. It +was replaced by the faithful overlap oracle in +``pm4py.algo.discovery.split_miner.concurrency.lifecycle`` +(``apply_overlap_concurrency``), which the SM2 variant selects +automatically for genuine lifecycle logs. + +Use the public API instead:: + + pm4py.discover_bpmn_split_miner(log, variant='sm2') +""" +raise ImportError( + "pm4py.algo.discovery.split_miner.concurrency.refined was removed. The " + "faithful lifecycle-overlap oracle now lives in " + "pm4py.algo.discovery.split_miner.concurrency.lifecycle and is used " + "automatically for variant='sm2'. " + "Use pm4py.discover_bpmn_split_miner(log, variant='sm2')." +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..09bf3320fdaa8b5742a9a0a0563813f148a3981c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/__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.discovery.split_miner.dfg_discovery import abc, classic diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..97d6b4de57d2e0a840304074f38efe364b5e9f0e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/abc.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 +''' +"""Abstract base class for the DFG-discovery phase.""" +from abc import ABC, abstractmethod +from typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar + +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG +from pm4py.algo.discovery.split_miner.dtypes.loops import LoopInfo + + +TraceT = TypeVar("TraceT") + + +class DFGDiscoverer(ABC, Generic[TraceT]): + """Build a DFG and the corresponding ``LoopInfo`` from a list of traces.""" + + @classmethod + @abstractmethod + def apply( + cls, + traces: List[TraceT], + parameters: Optional[Dict[str, Any]] = None, + ) -> Tuple[DFG, LoopInfo]: + """Return the directly-follows graph and its self/short-loop summary.""" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..91de037ef153a1e8d081b74db64d8e4bdf78862c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/classic.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 +''' +"""Classic directly-follows graph + loop discovery. + +Builds the DFG from a list of activity-label traces and detects: + + * self-loops — activities ``a`` with ``|a -> a| > 0``; + * short-loops — pairs ``{a, b}`` for which an ``a, b, a`` sub-sequence + appears in some trace while neither ``a`` nor ``b`` is a self-loop. +""" +from collections import defaultdict +from typing import Any, Dict, FrozenSet, List, Optional, Set, Tuple + +from pm4py.algo.discovery.split_miner.dfg_discovery.abc import DFGDiscoverer +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG +from pm4py.algo.discovery.split_miner.dtypes.log import LabelTrace +from pm4py.algo.discovery.split_miner.dtypes.loops import LoopInfo + + +def _build_dfg(traces: List[LabelTrace]) -> Tuple[DFG, Set[str]]: + dfg: Dict[Tuple[str, str], int] = defaultdict(int) + labels: Set[str] = set() + for trace in traces: + for label in trace: + labels.add(label) + for a, b in zip(trace, trace[1:]): + dfg[(a, b)] += 1 + return dict(dfg), labels + + +def short_loop_frequencies( + traces: List[LabelTrace], +) -> Dict[Tuple[str, str], int]: + """Number of (a, b, a) sub-sequences over the supplied traces.""" + freq: Dict[Tuple[str, str], int] = defaultdict(int) + for trace in traces: + for i in range(len(trace) - 2): + a, b, c = trace[i], trace[i + 1], trace[i + 2] + if a == c and a != b: + freq[(a, b)] += 1 + return dict(freq) + + +def _discover_loops(dfg: DFG, traces: List[LabelTrace]) -> LoopInfo: + self_loops: Set[str] = { + a for (a, b), f in dfg.items() if a == b and f > 0 + } + short_freq = short_loop_frequencies(traces) + short_loops: Set[FrozenSet[str]] = set() + for (a, b), f in short_freq.items(): + if f == 0: + continue + if a in self_loops or b in self_loops: + continue + if short_freq.get((a, b), 0) + short_freq.get((b, a), 0) == 0: + continue + short_loops.add(frozenset((a, b))) + return LoopInfo( + self_loops=self_loops, + short_loops=short_loops, + short_loop_freq=short_freq, + ) + + +class ClassicDFGDiscoverer(DFGDiscoverer[LabelTrace]): + """Directly-follows graph built from flat label traces.""" + + @classmethod + def apply( + cls, + traces: List[LabelTrace], + parameters: Optional[Dict[str, Any]] = None, + ) -> Tuple[DFG, LoopInfo]: + dfg, _ = _build_dfg(traces) + loops = _discover_loops(dfg, traces) + return dfg, loops + + +def strip_self_loops(dfg: DFG) -> DFG: + """Drop ``a -> a`` arcs; they are re-attached during BPMN export.""" + return {(a, b): f for (a, b), f in dfg.items() if a != b} diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/refined.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/refined.py new file mode 100644 index 0000000000000000000000000000000000000000..0b38703f499711503fc9519e480d9c9e5c9d0b3f --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dfg_discovery/refined.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 +''' +"""Removed module — compatibility shim. + +``dfg_discovery.refined.RefinedDFGDiscoverer`` was the approximate +lifecycle DFG of the earlier Split Miner 2.0. The faithful variant now +builds the directly-follows graph from ``complete`` events via +``pm4py.algo.discovery.split_miner.dtypes.complex_log.parse_complex_log`` +(the ``getComplexLog`` port) and reuses the classic DFG discoverer; the +SM2 variant wires this automatically. + +Use the public API instead:: + + pm4py.discover_bpmn_split_miner(log, variant='sm2') +""" +raise ImportError( + "pm4py.algo.discovery.split_miner.dfg_discovery.refined was removed. The " + "faithful SM2 directly-follows graph is now built by " + "pm4py.algo.discovery.split_miner.dtypes.complex_log.parse_complex_log " + "and used automatically for variant='sm2'. " + "Use pm4py.discover_bpmn_split_miner(log, variant='sm2')." +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..31988104e0d76ab180bf18a9bd8885f324df8d9c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/__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.algo.discovery.split_miner.dtypes import ( + working_graph, + dfg, + loops, + concurrency, + complex_log, + filtering, + log, + rpst_tree, + gateway_map +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/complex_log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/complex_log.py new file mode 100644 index 0000000000000000000000000000000000000000..49bd71735431821d2d45510b204d037718233ec3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/complex_log.py @@ -0,0 +1,165 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Lifecycle-aware log parsing for Split Miner 2.0. + +The directly-follows graph is built from ``complete`` events +only (mirroring ``lastComplete -> LID``); when the log carries genuine +``start``/``complete`` lifecycle information (``|start - complete| < +0.5 * total``) the log is treated as a *complex* log and an +overlap-based concurrency matrix is computed (two activities are +concurrent when one ``start`` arrives while the other is still +executing). A ``potential OR`` relation is recorded for every activity +pair that is observed both concurrently *and* exclusively. + +The trace projection keeps activity *labels*; +ordering-sensitive downstream phases sort by label, so +the integer encoding is unnecessary for a result. +""" +from dataclasses import dataclass, field +from typing import Dict, FrozenSet, List, Set + +from pm4py.algo.discovery.split_miner.dtypes.log import ( + END_LABEL, + LabelTrace, + START_LABEL, +) + +_LIFECYCLE_START = "start" +_LIFECYCLE_COMPLETE = "complete" + + +@dataclass +class ComplexLogResult: + """Outcome of :func:`parse_complex_log`.""" + + traces: List[LabelTrace] + is_complex: bool + # overlap[(a, b)] = number of times a and b were executing + # simultaneously (symmetric); only populated for complex logs. + overlap: Dict[FrozenSet[str], int] = field(default_factory=dict) + # observed[a] = number of completes of a. + observed: Dict[str, int] = field(default_factory=dict) + # potential_ors: activity pairs seen both concurrently and + # exclusively (the Java ``potentialORs`` matrix, > 0 cells). + potential_ors: Set[FrozenSet[str]] = field(default_factory=set) + + +def _lifecycle(ev, lifecycle_key: str) -> str: + # Deliberate deviation: the Java reference assumes the attribute is + # always present (and aborts otherwise). Treating a missing value as + # ``complete`` lets lifecycle-free logs degrade to the simple-log + # path instead of failing; for logs with uniform lifecycle data the + # behaviour is identical. + val = ev.get(lifecycle_key) + return str(val).strip().lower() if val is not None else _LIFECYCLE_COMPLETE + + +def parse_complex_log( + event_log, + activity_key: str, + lifecycle_key: str, + timestamp_key: str = "time:timestamp", +) -> ComplexLogResult: + """Project a pm4py event log onto Split Miner 2.0's complex log. + + Returns the per-trace ``complete``-event label sequences (wrapped in + the start/end sentinels) together with the lifecycle metadata needed + by the concurrency oracle and the OR-split heuristic. + + The reference implementation assumes a timestamp-ordered XES log; + events within each trace are therefore sorted by timestamp (stably, + so equal-timestamp events keep their recorded order) before the + overlap-based concurrency is derived. + """ + start_events = 0 + complete_events = 0 + total_events = 0 + + overlap: Dict[FrozenSet[str], int] = {} + observed: Dict[str, int] = {} + + all_labels: Set[str] = set() + traces: List[LabelTrace] = [] + # One ``executed`` label set per trace, retained so exclusiveness can + # be computed in a second pass for complex logs only (it is quadratic + # in the activity count and never needed for simple logs). + executed_per_trace: List[Set[str]] = [] + + for trace in event_log: + executing: Set[str] = set() + executed: Set[str] = set() + seq: List[str] = [] + events = [ev for ev in trace if activity_key in ev] + if events and all( + ev.get(timestamp_key) is not None for ev in events + ): + # Stable sort keeps equal-timestamp events in recorded order. + events = sorted(events, key=lambda ev: ev[timestamp_key]) + for ev in events: + label = str(ev[activity_key]) + all_labels.add(label) + phase = _lifecycle(ev, lifecycle_key) + total_events += 1 + if phase == _LIFECYCLE_START: + start_events += 1 + for other in executing: + if other != label: + key = frozenset((other, label)) + overlap[key] = overlap.get(key, 0) + 1 + executing.add(label) + executed.add(label) + elif phase == _LIFECYCLE_COMPLETE: + complete_events += 1 + executing.discard(label) + observed[label] = observed.get(label, 0) + 1 + seq.append(label) + executed.add(label) + + traces.append([START_LABEL, *seq, END_LABEL]) + executed_per_trace.append(executed) + + is_complex = abs(start_events - complete_events) < total_events * 0.5 + + potential_ors: Set[FrozenSet[str]] = set() + if is_complex: + # exclusiveness[(a, b)]: traces where exactly one of a, b ran. + exclusiveness: Dict[FrozenSet[str], int] = {} + for executed in executed_per_trace: + not_executed = all_labels - executed + for a in executed: + for b in not_executed: + key = frozenset((a, b)) + exclusiveness[key] = exclusiveness.get(key, 0) + 1 + for key, ov in overlap.items(): + if ov > 0 and exclusiveness.get(key, 0) > 0: + potential_ors.add(key) + else: + # A non-complex log carries no overlap-based concurrency. + overlap = {} + + return ComplexLogResult( + traces=traces, + is_complex=is_complex, + overlap=overlap, + observed=observed, + potential_ors=potential_ors, + ) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/concurrency.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..b0cc44902c6a88ad9f7bc8850fce42ce2de569dc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/concurrency.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 +''' +"""Output of the concurrency phase: pruned DFG + concurrency relation.""" +from dataclasses import dataclass, field +from typing import FrozenSet, Set + +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG + + +@dataclass +class ConcurrencyResult: + pdfg: DFG = field(default_factory=dict) + concurrent_pairs: Set[FrozenSet[str]] = field(default_factory=set) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/dfg.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/dfg.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5fc661af1bfd267046e036a774076a9126ba18 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/dfg.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 +''' +"""Directly-follows graph type alias used across Split Miner phases.""" +from typing import Dict, Tuple + +#: ``DFG[(a, b)] = number of times b directly follows a``. +DFG = Dict[Tuple[str, str], int] diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/filtering.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/filtering.py new file mode 100644 index 0000000000000000000000000000000000000000..483eeffe65e639b9e56fd54874ec350d6c0e5bad --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/filtering.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 +''' +"""Output of the PDFG filtering phase.""" +from dataclasses import dataclass, field +from typing import Set, Tuple + + +@dataclass +class FilterResult: + edges: Set[Tuple[str, str]] = field(default_factory=set) + source: str = "" + sink: str = "" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/gateway_map.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/gateway_map.py new file mode 100644 index 0000000000000000000000000000000000000000..691bad94d7994ab5b3d431d207641f06f1eb8060 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/gateway_map.py @@ -0,0 +1,804 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Inclusive-OR-join replacement (port of the reference ``GatewayMap``). + +Split Miner's final step (``replaceIORs`` with the ``replace inclusive +gateways`` option enabled) rewrites every inclusive (OR) join into the +behaviourally equivalent exclusive (XOR) or parallel (AND) join. The +decision is made on a *gateway map* — a graph whose nodes are the +gateways of the BPMN model and whose edges are the task-paths connecting +them. + +For every OR-join, processed shallowest-first in a breadth-first depth +order, the algorithm walks backwards towards the join's dominator. If the +incoming branches are mutually exclusive (``check_xor``) the join becomes +an XOR; otherwise it becomes an AND and *token generators* (auxiliary AND +gateways with synthetic flows) are inserted so the parallel join can +always synchronise. +""" +from typing import Dict, List, Optional, Set + +import networkx as nx + +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph + + +# Gateway kinds as used by the WorkingGraph. +_XOR = "xor" +_AND = "and" +_OR = "or" +_GATE_KINDS = {_XOR, _AND, _OR} + +# Sentinels for the fake entry/exit gateways of the map. +_FAKE_ENTRY = "__gm_entry__" +_FAKE_EXIT = "__gm_exit__" + + +class _Flow: + """A gateway-map edge: a task-path between two gateways. + + ``first`` is the node immediately after ``src`` on the path, ``last`` + the node immediately before ``tgt`` (so the real BPMN edge entering a + join is ``last -> tgt``). ``loop`` marks edges that close a cycle. + """ + + __slots__ = ("id", "src", "tgt", "first", "last", "loop") + + def __init__(self, fid, src, tgt, first, last): + self.id = fid + self.src = src + self.tgt = tgt + self.first = first + self.last = last + self.loop = False + + def __repr__(self): + return f"F{self.id}({self.src}->{self.tgt}{'*' if self.loop else ''})" + + +def _is_gateway(wg: WorkingGraph, node: str) -> bool: + n = wg.nodes.get(node) + return n is not None and n.kind in _GATE_KINDS + + +# ---------------------------------------------------------------------- +# WorkingGraph pre-processing +# ---------------------------------------------------------------------- + + +def _remove_join_split(wg: WorkingGraph) -> None: + """Split every gateway that both joins and splits. + + A gateway with more than one incoming *and* more than one outgoing + flow is separated into a pure join (keeping the incoming flows, typed + inclusive) feeding a pure split (keeping the outgoing flows, original + type). Mirrors ``DiagramHandler.removeJoinSplit``. + """ + for gid in list(wg.nodes.keys()): + node = wg.nodes.get(gid) + if node is None or node.kind not in _GATE_KINDS: + continue + ins = list(wg.in_edges.get(gid, [])) + outs = list(wg.out_edges.get(gid, [])) + if len(ins) > 1 and len(outs) > 1: + split = wg.add_node(node.kind, label=node.kind) + for t in outs: + wg.remove_edge(gid, t) + wg.add_edge(split, t) + wg.add_edge(gid, split) + node.kind = _OR + node.label = _OR + + +# ---------------------------------------------------------------------- +# Gateway map +# ---------------------------------------------------------------------- + + +class GatewayMap: + def __init__(self, wg: WorkingGraph, apply_hagen: bool = True): + self.wg = wg + self.apply_hagen = apply_hagen + self.fid = 0 + self.gid = 0 + + self.gateways: Set[str] = set() + self.flows: Set[_Flow] = set() + self.incomings: Dict[str, Set[_Flow]] = {} + self.outgoings: Dict[str, Set[_Flow]] = {} + self.successors: Dict[str, Set[str]] = {} + self.predecessors: Dict[str, Set[str]] = {} + + self.entry: Optional[str] = None + self.exit: Optional[str] = None + + self.gates_depth: Dict[str, int] = {} + self.loop_joins: Set[str] = set() + self.idom: Dict[str, str] = {} + self.ior_hierarchy: List[str] = [] + + # -- map building ------------------------------------------------- + + def _add_gateway(self, gid: str) -> None: + self.gateways.add(gid) + self.incomings.setdefault(gid, set()) + self.outgoings.setdefault(gid, set()) + self.successors.setdefault(gid, set()) + self.predecessors.setdefault(gid, set()) + + def _add_flow(self, src, tgt, first, last) -> _Flow: + self.fid += 1 + flow = _Flow(self.fid, src, tgt, first, last) + self.flows.add(flow) + self.outgoings[src].add(flow) + self.incomings[tgt].add(flow) + self.successors[src].add(tgt) + self.predecessors[tgt].add(src) + return flow + + def _remove_flow(self, flow: _Flow) -> None: + self.flows.discard(flow) + self.outgoings[flow.src].discard(flow) + self.incomings[flow.tgt].discard(flow) + # recompute successor/predecessor membership + if not any(f.tgt == flow.tgt for f in self.outgoings[flow.src]): + self.successors[flow.src].discard(flow.tgt) + self.predecessors[flow.tgt].discard(flow.src) + + def _change_flow_tgt(self, flow: _Flow, new_tgt: str) -> _Flow: + first = new_tgt if flow.first == flow.tgt else flow.first + nf = self._add_flow(flow.src, new_tgt, first, flow.last) + if flow.loop: + nf.loop = True + self._remove_flow(flow) + return nf + + def _walk_to_gateway(self, src_gate: str, first: str): + """Follow a task chain from ``first`` until a gateway or the sink. + + Returns ``(reached, last)`` where ``reached`` is the next gateway + (or the WorkingGraph sink) and ``last`` the node just before it. + """ + wg = self.wg + prev = src_gate + cur = first + while ( + not _is_gateway(wg, cur) + and cur != wg.end_id + and len(wg.out_edges.get(cur, [])) == 1 + ): + prev = cur + cur = wg.out_edges[cur][0] + return cur, prev + + def build(self) -> bool: + wg = self.wg + _remove_join_split(wg) + + for gid, node in wg.nodes.items(): + if node.kind in _GATE_KINDS: + self._add_gateway(gid) + + if not self.gateways: + return False + + # First gateway reachable from the source. + cur = wg.start_id + while not _is_gateway(wg, cur) and len(wg.out_edges.get(cur, [])) == 1: + cur = wg.out_edges[cur][0] + if not _is_gateway(wg, cur): + return False + first_gate = cur + self.entry = first_gate + + exit_gate = None + to_visit = [first_gate] + visited = {wg.end_id} + seen = set() + while to_visit: + entry = to_visit.pop(0) + if entry in seen: + continue + seen.add(entry) + visited.add(entry) + for child in list(wg.out_edges.get(entry, [])): + reached, last = self._walk_to_gateway(entry, child) + if _is_gateway(wg, reached): + self._add_flow(entry, reached, child, last) + if reached == wg.end_id: + exit_gate = entry + if reached not in to_visit and reached not in visited: + to_visit.append(reached) + + if exit_gate is None: + return False + self.exit = exit_gate + + # Fake entry/exit so the dominator computation has a single root. + self._add_gateway(_FAKE_ENTRY) + self._add_gateway(_FAKE_EXIT) + self._add_flow(_FAKE_ENTRY, first_gate, first_gate, _FAKE_ENTRY) + self._add_flow(exit_gate, _FAKE_EXIT, _FAKE_EXIT, exit_gate) + self.entry = _FAKE_ENTRY + self.exit = _FAKE_EXIT + + self._detect_loops() + self._normalize_loop_joins() + self._populate_ior_hierarchy() + self._generate_dominators() + return True + + # -- loops -------------------------------------------------------- + + def _detect_loops(self) -> None: + """Mark map flows that close a cycle (loop edges). + + Faithful port of the reference ``detectLoops``/``exploreLoops``: a + fix-point DFS that classifies each flow as forward or loop. A node + is only *settled* once all its incoming flows have been traversed; + otherwise it is re-queued (added back to ``unvisited``) so it is + re-explored when reached again. The recursion's return value marks + whether the explored subtree can *only* go backward + (``loop and not forward``); an edge into such a subtree is itself a + loop edge. A flow is a true loop only if it was *never* classified + as a forward edge. + """ + unvisited: Set[str] = set(self.outgoings.keys()) + visiting: Set[str] = set() + visited_gates: Dict[str, bool] = {} + visited_flows: Set[_Flow] = set() + loop_edges: Set[_Flow] = set() + forward_edges: Set[_Flow] = set() + + def explore(entry: str) -> bool: + loop_edge = False + forward_edge = False + unvisited.discard(entry) + visiting.add(entry) + if entry == self.exit: + forward_edge = True + for oflow in sorted(self.outgoings.get(entry, set()), + key=lambda f: f.id): + visited_flows.add(oflow) + nxt = oflow.tgt + if nxt in unvisited: + if explore(nxt): + loop_edge = True + loop_edges.add(oflow) + else: + forward_edge = True + forward_edges.add(oflow) + elif nxt in visiting: + loop_edge = True + loop_edges.add(oflow) + elif nxt in visited_gates: + if visited_gates[nxt]: + loop_edge = True + loop_edges.add(oflow) + else: + forward_edge = True + forward_edges.add(oflow) + visiting.discard(entry) + fully = all( + iflow in visited_flows + for iflow in self.incomings.get(entry, set()) + ) + if fully: + visited_gates[entry] = loop_edge and not forward_edge + else: + unvisited.add(entry) + return loop_edge and not forward_edge + + import sys + old = sys.getrecursionlimit() + sys.setrecursionlimit(max(old, len(self.gateways) * 8 + 100)) + try: + explore(self.entry) + finally: + sys.setrecursionlimit(old) + + for flow in loop_edges: + if flow not in forward_edges: + flow.loop = True + + def _normalize_loop_joins(self) -> None: + """Separate loop merges from forward merges at loop-joins. + + A join receiving at least one loop edge is a loop-join. If it has + a single forward branch it is recorded as-is and, if inclusive, + demoted to exclusive. If it has *several* forward branches the + join is split (as in the reference) into a forward XOR-join that + feeds a new exclusive loop-join; the loop back-edges and the + forward result are merged at the loop-join. This keeps the + gateway map's dominator structure, which is what the + inclusive-join replacement relies on. + """ + self.loop_joins = set() + for join in sorted(self.gateways): + ins = self.incomings.get(join, set()) + if len(ins) <= 1: + continue + ins_ord = sorted(ins, key=lambda f: f.id) + loops = [f for f in ins_ord if f.loop] + fwds = [f for f in ins_ord if not f.loop] + if not loops: + continue + if len(fwds) > 1: + loop_join = self.wg.add_node(_XOR, label=_XOR) + self._add_gateway(loop_join) + # loop sources on the WorkingGraph side + srcs = {f.last for f in loops} + # map: the join's outgoing flow now leaves the loop-join, + # and a new flow connects join -> loop-join + for of in sorted(self.outgoings.get(join, set()), + key=lambda f: f.id): + self._change_flow_src(of, loop_join) + self._add_flow(join, loop_join, loop_join, join) + # map: loop edges are redirected to the loop-join + for f in loops: + self._change_flow_tgt(f, loop_join) + # WorkingGraph: move the join's successors onto the + # loop-join and wire join -> loop-join + for t in list(self.wg.out_edges.get(join, [])): + self.wg.remove_edge(join, t) + self.wg.add_edge(loop_join, t) + self.wg.add_edge(join, loop_join) + # WorkingGraph: move the loop back-edges onto the loop-join + for s in list(self.wg.in_edges.get(join, [])): + if s in srcs: + self.wg.remove_edge(s, join) + self.wg.add_edge(s, loop_join) + self.loop_joins.add(loop_join) + continue + self.loop_joins.add(join) + node = self.wg.nodes.get(join) + if node is not None and node.kind == _OR: + node.kind = _XOR + node.label = _XOR + + # -- hierarchy + dominators -------------------------------------- + + def _populate_ior_hierarchy(self) -> None: + # Longest-path depth from the entry (matching the reference): a + # node is re-queued whenever a deeper path reaches it; loop joins + # are never re-deepened nor re-queued once seen, so cycles + # terminate. This is the correct depth for the inclusive-join + # replacement. + depth: Dict[str, int] = {self.entry: 0} + to_visit = [self.entry] + visited = {self.entry} + while to_visit: + g = to_visit.pop(0) + sd = depth[g] + 1 + for nxt in sorted(self.successors.get(g, set())): + bumped = False + if nxt not in depth: + depth[nxt] = sd + bumped = True + elif depth[nxt] < sd and nxt not in self.loop_joins: + depth[nxt] = sd + bumped = True + if nxt in visited and nxt in self.loop_joins: + continue + if nxt in visited and not bumped: + continue + to_visit.append(nxt) + visited.add(nxt) + self.gates_depth = depth + + # Inclusive joins ordered shallowest-first. + iors = [ + g + for g in depth + if self.wg.nodes.get(g) is not None + and self.wg.nodes[g].kind == _OR + ] + iors.sort(key=lambda g: (depth[g], g)) + self.ior_hierarchy = iors + + def _generate_dominators(self) -> None: + g = nx.DiGraph() + g.add_nodes_from(sorted(self.gateways)) + for src in sorted(self.gateways): + for tgt in sorted(self.successors.get(src, set())): + g.add_edge(src, tgt) + # immediate_dominators needs every node reachable from the root. + reach = nx.descendants(g, self.entry) | {self.entry} + sub = g.subgraph(reach) + self.idom = nx.immediate_dominators(sub, self.entry) + + def _dominator(self, ior: str) -> Optional[str]: + return self.idom.get(ior) + + # -- IOR replacement --------------------------------------------- + + def detect_and_replace_iors(self) -> None: + # process shallowest-first; recompute hierarchy lazily because + # depths do not change as we only retype gateways + pending = list(self.ior_hierarchy) + for ior in pending: + node = self.wg.nodes.get(ior) + if node is None or node.kind != _OR: + continue + dominator = self._dominator(ior) + if dominator is None: + continue + + to_visit: Dict[str, Set[str]] = {} + visited_gates: Dict[str, Set[str]] = {} + visited_flows: Dict[str, Set[_Flow]] = {} + loop = False + + for igmf in sorted(self.incomings.get(ior, set()), + key=lambda f: f.id): + if igmf.loop: + node.kind = _XOR + node.label = _XOR + loop = True + break + last = igmf.last + # Mirror the reference: only insert a per-incoming XOR when a + # real edge last -> ior exists in the diagram. The fake-entry + # flow (``last`` is the map's entry sentinel, with no diagram + # edge) is left untouched instead of crashing. + if last not in self.wg.out_edges or ior not in \ + self.wg.out_edges.get(last, []): + continue + self.wg.remove_edge(last, ior) + xor = self.wg.add_node(_XOR, label=_XOR) + self.wg.add_edge(last, xor) + self.wg.add_edge(xor, ior) + self._add_gateway(xor) + self._add_flow(xor, ior, ior, xor) + self._change_flow_tgt(igmf, xor) + to_visit[xor] = {xor} + visited_gates[xor] = {dominator} + visited_flows[xor] = set() + + if loop: + continue + + ands: Set[str] = set() + ior_type = self._replace_ior( + dominator, + self.gates_depth.get(ior, 0), + to_visit, + visited_gates, + visited_flows, + set(), + {}, + ands, + ) + node.kind = ior_type + node.label = ior_type + + _remove_trivial_gateways(self.wg) + + def _replace_ior( + self, + dominator: str, + ior_depth: int, + to_visit: Dict[str, Set[str]], + visited_gates: Dict[str, Set[str]], + visited_flows: Dict[str, Set[_Flow]], + dom_frontier: Set[_Flow], + loop_injections: Dict[str, Set[_Flow]], + ands: Set[str], + ) -> str: + empty = True + for xor in sorted(to_visit.keys()): + tmp: Set[str] = set() + for g in sorted(to_visit[xor]): + for igmf in sorted(self.incomings.get(g, set()), + key=lambda f: f.id): + src = igmf.src + if igmf in visited_flows[xor]: + continue + visited_flows[xor].add(igmf) + if src == dominator: + dom_frontier.add(igmf) + if src in self.loop_joins and src not in loop_injections: + loop_injections[src] = set() + for injection in sorted( + self.incomings.get(src, set()), key=lambda f: f.id + ): + isrc = injection.src + if ( + isrc in self.gates_depth + and self.gates_depth[isrc] <= ior_depth + ): + continue + loop_injections[src].add(injection) + if src in visited_gates[xor] or ( + src in self.gates_depth + and self.gates_depth[src] > ior_depth + ): + continue + visited_gates[xor].add(src) + snode = self.wg.nodes.get(src) + if ( + snode is not None + and snode.kind == _AND + and len(self.outgoings.get(src, set())) > 1 + ): + ands.add(src) + tmp.add(src) + empty = False + to_visit[xor] = tmp + + if not empty: + return self._replace_ior( + dominator, + ior_depth, + to_visit, + visited_gates, + visited_flows, + dom_frontier, + loop_injections, + ands, + ) + + if self._check_xor(visited_gates, visited_flows, ands): + return _XOR + + # Build single-token generators for the parallel rewrite. + changes: Dict[_Flow, _SingleTokenGen] = {} + for xor in sorted(visited_gates): + for g in sorted(visited_gates[xor]): + gnode = self.wg.nodes.get(g) + if ( + gnode is not None and gnode.kind == _AND + ) or len(self.outgoings.get(g, set())) == 1: + continue + for of in sorted(self.outgoings.get(g, set()), + key=lambda f: f.id): + if of in visited_flows[xor] or ( + g == dominator and of not in dom_frontier + ): + continue + if of in changes: + changes[of].xors.add(xor) + else: + changes[of] = _SingleTokenGen(xor, g, of) + + # Loop-injection token generators: for every loop-join reached + # during the backward exploration whose injecting back-edges sit + # deeper than the IOR, every XOR that did *not* reach that loop-join + # must receive a token (reference: loopChanges/MultipleTokenGen). + loop_changes: List["_MultipleTokenGen"] = [] + for loop_inj in sorted(loop_injections): + if not loop_injections[loop_inj]: + continue + tmp: Set[str] = set() + for xor in sorted(visited_gates): + if loop_inj not in visited_gates[xor]: + tmp.add(xor) + if tmp: + loop_changes.append( + _MultipleTokenGen(tmp, loop_injections[loop_inj], loop_inj) + ) + + if not self.apply_hagen: + return _OR + + for of in sorted(changes.keys(), key=lambda f: f.id): + self._place_token_generator(changes[of]) + for mtg in loop_changes: + self._place_multiple_token_generator(mtg) + + return _AND + + def _check_xor( + self, + visited_gates: Dict[str, Set[str]], + visited_flows: Dict[str, Set[_Flow]], + ands: Set[str], + ) -> bool: + visited_ids: Dict[str, Dict[str, Set[int]]] = {} + unvisited_ids: Dict[str, Dict[str, Set[int]]] = {} + for and_g in sorted(ands): + visited_ids[and_g] = {} + unvisited_ids[and_g] = {} + for xor in sorted(visited_gates): + v = visited_flows[xor] + v1: Set[int] = set() + u1: Set[int] = set() + for oe in sorted(self.outgoings.get(and_g, set()), + key=lambda f: f.id): + if oe in v: + v1.add(oe.id) + else: + u1.add(oe.id) + if not v1: + continue + visited_ids[and_g][xor] = v1 + unvisited_ids[and_g][xor] = u1 + + for and_g in sorted(ands): + for xor1 in sorted(visited_ids[and_g]): + v1 = set(visited_ids[and_g][xor1]) + u1 = set(unvisited_ids[and_g][xor1]) + for xor2 in sorted(visited_ids[and_g]): + v2 = set(visited_ids[and_g][xor2]) + u2 = set(unvisited_ids[and_g][xor2]) + # retainAll(x) returns True (changed) iff not subset + u2_changed = not u2.issubset(u1) + v2_inter = v2 & v1 + v2_changed = v2_inter != v2 + if (not u2_changed) and ( + (not v2_changed) or (not v2_inter) + ): + continue + return False + return True + + def _place_token_generator(self, tg: "_SingleTokenGen") -> None: + wg = self.wg + e_gate = tg.escaping_gate + e_flow = tg.escaping_flow + first = e_flow.first + fnode = wg.nodes.get(first) + if ( + fnode is not None + and fnode.kind == _AND + and len(self.outgoings.get(first, set())) > 1 + ): + and_g = first + else: + and_g = wg.add_node(_AND, label=_AND) + wg.add_edge(e_gate, and_g) + # ``first`` may be the map-only fake entry/exit sentinel, which + # has no node in the WorkingGraph; the reference treats such a + # flow target as null, so the diagram-side edge is a no-op. + first_real = first in wg.nodes + if first_real: + wg.add_edge(and_g, first) + self._add_gateway(and_g) + self._add_flow(e_gate, and_g, and_g, e_gate) + # re-source the escaping flow through the new AND + ef = self._change_flow_src(e_flow, and_g) + if first_real and first in wg.out_edges.get(e_gate, []): + wg.remove_edge(e_gate, first) + e_flow = ef + for xor in sorted(tg.xors): + wg.add_edge(and_g, xor) + self._add_flow(and_g, xor, xor, and_g) + + def _place_multiple_token_generator(self, mtg: "_MultipleTokenGen") -> None: + wg = self.wg + xors = mtg.xors + injections = mtg.injections + loop_injection = mtg.loop_injection + if not xors: + return + and_g: Optional[str] = None + + if len(injections) > 1: + # merge all injecting back-edges through a new XOR join + xor = wg.add_node(_XOR, label=_XOR) + self._add_gateway(xor) + srcs: Set[str] = set() + for inj_flow in sorted(injections, key=lambda f: f.id): + srcs.add(inj_flow.last) + self._change_flow_tgt(inj_flow, xor) + final_injection = self._add_flow( + xor, loop_injection, loop_injection, xor + ) + final_injection.loop = True + injections = {final_injection} + for s in list(wg.in_edges.get(loop_injection, [])): + if s in srcs: + wg.remove_edge(s, loop_injection) + wg.add_edge(s, xor) + wg.add_edge(xor, loop_injection) + + # at this point a single injecting back-edge remains + for inj in sorted(injections, key=lambda f: f.id): + last = inj.last + lnode = wg.nodes.get(last) + if ( + lnode is not None + and lnode.kind == _AND + and len(self.outgoings.get(last, set())) > 1 + ): + and_g = last + else: + and_g = wg.add_node(_AND, label=_AND) + self._add_gateway(and_g) + self._change_flow_tgt(inj, and_g) + for s in list(wg.in_edges.get(loop_injection, [])): + if s == last: + wg.remove_edge(s, loop_injection) + wg.add_edge(last, and_g) + nf = self._add_flow( + and_g, loop_injection, loop_injection, and_g + ) + nf.loop = True + wg.add_edge(and_g, loop_injection) + + for x in sorted(xors): + wg.add_edge(and_g, x) + self._add_flow(and_g, x, x, and_g) + + def _change_flow_src(self, flow: _Flow, new_src: str) -> _Flow: + last = new_src if flow.last == flow.src else flow.last + nf = self._add_flow(new_src, flow.tgt, flow.first, last) + if flow.loop: + nf.loop = True + self._remove_flow(flow) + return nf + + +class _SingleTokenGen: + __slots__ = ("xors", "escaping_gate", "escaping_flow") + + def __init__(self, xor, escaping_gate, escaping_flow): + self.xors = {xor} + self.escaping_gate = escaping_gate + self.escaping_flow = escaping_flow + + +class _MultipleTokenGen: + __slots__ = ("xors", "injections", "loop_injection") + + def __init__(self, xors, injections, loop_injection): + self.xors = set(xors) + self.injections = injections + self.loop_injection = loop_injection + + +def _remove_trivial_gateways(wg: WorkingGraph) -> None: + """Splice out any gateway with a single incoming and outgoing flow.""" + changed = True + while changed: + changed = False + for gid in list(wg.nodes.keys()): + node = wg.nodes.get(gid) + if node is None or node.kind not in _GATE_KINDS: + continue + ins = list(wg.in_edges.get(gid, [])) + outs = list(wg.out_edges.get(gid, [])) + if len(ins) == 1 and len(outs) == 1: + src, tgt = ins[0], outs[0] + wg.remove_edge(src, gid) + wg.remove_edge(gid, tgt) + wg.remove_node(gid) + if src != tgt: + wg.add_edge(src, tgt) + changed = True + break + + +def replace_inclusive_joins( + wg: WorkingGraph, apply_hagen: bool = True +) -> None: + """Replace every inclusive (OR) join with an XOR or AND join.""" + has_or = any( + n.kind == _OR and len(wg.in_edges.get(nid, [])) > 1 + for nid, n in wg.nodes.items() + ) + if not has_or: + return + gm = GatewayMap(wg, apply_hagen=apply_hagen) + if not gm.build(): + return + gm.detect_and_replace_iors() diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/log.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/log.py new file mode 100644 index 0000000000000000000000000000000000000000..f15cb4a21360e057ebc33133aaf0fb3ee8135330 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/log.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 +''' +"""Trace types used by the Split Miner phases.""" +from typing import List + +# A flat label trace consumed by the Split Miner pipeline. Split Miner +# 2.0 projects each trace onto its ``complete``-event labels and feeds +# the same flat representation through the shared machinery. +LabelTrace = List[str] + +# Sentinel labels added to every trace so the resulting BPMN has a single +# start event and a single end event. +START_LABEL = "__start__" +END_LABEL = "__end__" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/loops.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/loops.py new file mode 100644 index 0000000000000000000000000000000000000000..a45fef2cde114ec026da5a5a1c465e384358c35c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/loops.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 +''' +"""Output of the loop-discovery phase.""" +from dataclasses import dataclass, field +from typing import Dict, FrozenSet, Set, Tuple + + +@dataclass +class LoopInfo: + """Self-loops, short-loops, and the underlying frequency map.""" + + self_loops: Set[str] = field(default_factory=set) + short_loops: Set[FrozenSet[str]] = field(default_factory=set) + short_loop_freq: Dict[Tuple[str, str], int] = field(default_factory=dict) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/rpst_tree.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/rpst_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..2a13933993e8b6aead94991d88bd69501f6554d3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/rpst_tree.py @@ -0,0 +1,1097 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Refined Process Structure Tree (RPST) via triconnected components. + +The graph is decomposed into triconnected components with the Hopcroft-Tarjan / +Gutwenger-Mutzel split-component algorithm (``ModelDecomposer`` + +``SplitCompDFS``), the components are organised into the triconnected +component tree (``TCTree``) and finally refined into the RPST. + +Fragment types (``TCType``): + * ``T`` trivial – a single edge, + * ``P`` polygon – series composition (all skeleton vertices deg 2), + * ``B`` bond – parallel composition (two skeleton vertices), + * ``R`` rigid – triconnected, anything else. +""" +import uuid +from typing import Dict, List, Optional, Set, Tuple + + +# ---------------------------------------------------------------------- +# Multigraph with orientable edges (mirrors jbpt TCTreeSkeleton) +# ---------------------------------------------------------------------- + + +class Edge: + __slots__ = ("v1", "v2", "virtual", "hidden", "id") + + def __init__(self, v1, v2, virtual=False): + self.v1 = v1 + self.v2 = v2 + self.virtual = virtual + self.hidden = False + self.id = "" + + def other(self, w): + return self.v1 if self.v2 == w else self.v2 + + def set_vertices(self, v, w): + self.v1 = v + self.v2 = w + + def is_self_loop(self): + return self.v1 == self.v2 + + def __repr__(self): + return f"{self.v1}-{self.v2}{'v' if self.virtual else ''}" + + +class Skeleton: + """Undirected multigraph; adjacency lists preserve insertion order.""" + + def __init__(self): + self.vertices: List = [] + self._vset: Set = set() + self.edges: List[Edge] = [] + self.inc: Dict[object, List[Edge]] = {} + + def add_vertex(self, v): + if v not in self._vset: + self._vset.add(v) + self.vertices.append(v) + self.inc[v] = [] + + def add_edge(self, v1, v2, virtual=False): + self.add_vertex(v1) + self.add_vertex(v2) + e = Edge(v1, v2, virtual) + self.edges.append(e) + self.inc[v1].append(e) + self.inc[v2].append(e) + return e + + def add_virtual_edge(self, v1, v2): + return self.add_edge(v1, v2, virtual=True) + + def remove_edge(self, e: Edge): + self.edges.remove(e) + if e in self.inc.get(e.v1, []): + self.inc[e.v1].remove(e) + if e in self.inc.get(e.v2, []): + self.inc[e.v2].remove(e) + + def get_edges(self, v) -> List[Edge]: + return self.inc.get(v, []) + + def get_edge(self, v1, v2) -> Optional[Edge]: + for e in self.inc.get(v1, []): + if (e.v1 == v1 and e.v2 == v2) or (e.v1 == v2 and e.v2 == v1): + return e + return None + + def count_vertices(self) -> int: + # vertices that still carry at least one edge + return len({v for e in self.edges for v in (e.v1, e.v2)}) + + def vertices_with_edges(self) -> Set: + return {v for e in self.edges for v in (e.v1, e.v2)} + + +# ---------------------------------------------------------------------- +# DFS passes (mirror AbstractDFS / ParentAndPathDFS / LowAndDescDFS / +# NumberDFS). They operate on a shared ``meta`` dict. +# ---------------------------------------------------------------------- + + +class _DFS: + """Recursive DFS framework with the four jbpt passes folded in via a + ``mode`` flag (``low`` for LowAndDescDFS, ``number`` for NumberDFS).""" + + def __init__(self, skeleton: Skeleton, meta: dict, adj: dict, mode: str): + self.g = skeleton + self.meta = meta + self.adj = adj + self.mode = mode + self.dfs_num = 0 + self.compl_num = 0 + # shared state + self.num = meta.setdefault("num", {}) + self.compl = meta.setdefault("compl", {}) + self.state = meta.setdefault("state", {}) + self.etype = meta.setdefault("etype", {}) + for v in self.g.vertices: + self.state[v] = 0 + self.num[v] = -1 + self.compl[v] = -1 + for e in self.g.edges: + self.etype[e] = 0 + # ParentAndPath + self.parent = meta.setdefault("parent", {}) + self.tree_arc = meta.setdefault("tree_arc", {}) + self.starts_path = meta.setdefault("starts_path", {}) + self.path_num = meta.setdefault("path_num", {}) + self._is_new_path = True + self._path_number = 1 + for v in self.g.vertices: + self.parent.setdefault(v, None) + self.tree_arc.setdefault(v, None) + for e in self.g.edges: + self.path_num[e] = -1 + self.starts_path[e] = False + if mode == "low": + self.lp1n = meta["lp1n"] = {} + self.lp2n = meta["lp2n"] = {} + self.lp1v = meta["lp1v"] = {} + self.lp2v = meta["lp2v"] = {} + self.numdesc = meta["numdesc"] = {} + for v in self.g.vertices: + self.lp1n[v] = -1 + self.lp2n[v] = -1 + self.lp1v[v] = None + self.lp2v[v] = None + self.numdesc[v] = -1 + elif mode == "number": + self.highpt = meta["highpt"] = {} + self.numv = meta["numv"] = {} + self.numtree = meta["numtree"] = {} + self.lp1num = meta["lp1num"] = {} + self.lp2num = meta["lp2num"] = {} + for v in self.g.vertices: + self.highpt[v] = [] + self.numv[v] = -1 + self.numtree[v] = -1 + self._m = len(self.g.vertices) + + def start(self, root): + self.dfs_num = 0 + self.compl_num = 0 + self._dfs(root) + + def _dfs(self, v): + self.dfs_num += 1 + self.num[v] = self.dfs_num + self.state[v] = 1 + self._pre_visit(v, self.num[v]) + for e in list(self.adj[v]): + if self.etype.get(e, 0) != 0: + continue + w = e.other(v) + e.set_vertices(v, w) + if self.state.get(w, 0) == 0: + self.etype[e] = 1 + self._pre_traverse(e, w, True) + self._dfs(w) + self._post_traverse(e, w) + else: + self.etype[e] = 2 + self._pre_traverse(e, w, False) + self.state[v] = 2 + self.compl_num += 1 + self.compl[v] = self.compl_num + self._post_visit(v, self.num[v], self.compl[v]) + + # -- hooks -------------------------------------------------------- + + def _pre_visit(self, v, dfsnum): + if self.mode == "low": + self.lp1n[v] = dfsnum + self.lp2n[v] = dfsnum + self.lp1v[v] = v + self.lp2v[v] = v + self.numdesc[v] = 1 + elif self.mode == "number": + self.numv[v] = self._m - self.meta["numdesc"][v] + 1 + self.numtree[v] = 0 + + def _pre_traverse(self, e, w, tree_edge): + # ParentAndPath + v = e.other(w) + if tree_edge: + self.parent[w] = v + self.tree_arc[w] = e + self.path_num[e] = self._path_number + if self._is_new_path: + self.starts_path[e] = True + self._is_new_path = False + else: + self.path_num[e] = self._path_number + if self._is_new_path: + self.starts_path[e] = True + self._path_number += 1 + self._is_new_path = True + if self.mode == "low" and not tree_edge: + if self.num[w] < self.lp1n[v]: + self.lp2n[v] = self.lp1n[v] + self.lp2v[v] = self.lp1v[v] + self.lp1n[v] = self.num[w] + self.lp1v[v] = w + elif self.num[w] > self.lp1n[v] and self.num[w] < self.lp2n[v]: + self.lp2n[v] = self.num[w] + self.lp2v[v] = w + if self.mode == "number" and not tree_edge: + self.highpt[w].append(e.other(w)) + + def _post_traverse(self, e, w): + v = e.other(w) + if self.mode == "low": + if self.lp1n[w] < self.lp1n[v]: + mn = min(self.lp1n[v], self.lp2n[w]) + self.lp2n[v] = mn + if mn == self.lp1n[v]: + self.lp2v[v] = self.lp1v[v] + else: + self.lp2v[v] = self.lp2v[w] + self.lp1n[v] = self.lp1n[w] + self.lp1v[v] = self.lp1v[w] + elif self.lp1n[w] == self.lp1n[v]: + if self.lp2n[w] < self.lp2n[v]: + self.lp2n[v] = self.lp2n[w] + self.lp2v[v] = self.lp2v[w] + elif self.lp1n[w] < self.lp2n[v]: + self.lp2n[v] = self.lp1n[w] + self.lp2v[v] = self.lp1v[w] + self.numdesc[v] = self.numdesc[v] + self.numdesc[w] + elif self.mode == "number": + self._m -= 1 + self.numtree[v] = self.numtree[v] + 1 + + def _post_visit(self, v, dfsnum, complnum): + if self.mode == "number": + self.lp1num[v] = self.numv[self.meta["lp1v"][v]] + self.lp2num[v] = self.numv[self.meta["lp2v"][v]] + + +# ---------------------------------------------------------------------- +# Split-component DFS (mirrors SplitCompDFS) +# ---------------------------------------------------------------------- + + +class _TSItem: + __slots__ = ("a", "b", "numH", "numA") + + def __init__(self, numH=-1, a=None, b=None, get_num=None): + self.a = a + self.b = b + self.numH = numH + self.numA = get_num(a) if (a is not None and get_num) else -1 + + +class _SplitCompDFS: + def __init__(self, g, meta, adj, comp, parent, tree_arc, highpt, + etype, virt, assigned_virt, is_hidden): + self.g = g + self.meta = meta + self.adj = adj + self.comp = comp + self.parent = parent + self.tree_arc = tree_arc + self.highpt = highpt + self.etype = etype + self.virt = virt + self.assigned_virt = assigned_virt + self.is_hidden = is_hidden + self.EOS = _TSItem() + self.dfs_root = None + self.e_stack: List[Edge] = [] + self.t_stack: List[_TSItem] = [] + self.num_not_visited_tree_edges = {} + self.starts_path = meta["starts_path"] + for v in g.vertices: + self.num_not_visited_tree_edges[v] = meta["numtree"].get(v, 0) + # restrict adjacency to the current (ordered) adj lists + self.state = {} + + # -- helpers ------------------------------------------------------ + + def get_num(self, v): + return self.meta["numv"][v] + + def get_l1num(self, v): + return self.meta["lp1num"][v] + + def get_l2num(self, v): + return self.meta["lp2num"][v] + + def get_numdesc(self, v): + return self.meta["numdesc"][v] + + def get_hnum(self, v): + hp = self.highpt.get(v, []) + if hp: + return self.get_num(hp[0]) + return 0 + + @staticmethod + def is_same_edge(e, v, w): + return (e.v1 == v and e.v2 == w) or (e.v1 == w and e.v2 == v) + + def _ts(self, numH, a, b): + return _TSItem(numH, a, b, self.get_num) + + # -- driver ------------------------------------------------------- + + def start(self, root): + self.dfs_root = root + self.t_stack.append(self.EOS) + self._dfs(root) + if self.e_stack: + self.new_component(list(self.e_stack)) + self.e_stack.clear() + + def _dfs(self, v): + # mirrors AbstractDFS.dfs but driven by ordered adj lists, with + # pre/post traverse hooks specialised below. + self.state[v] = 1 + for e in list(self.meta["ordered_adj"][v]): + if self.etype.get(e, 0) not in (1, 2): + # determine tree vs back using node state + w = e.other(v) + e.set_vertices(v, w) + if self.state.get(w, 0) == 0: + self.etype[e] = 1 + self.pre_traverse(e, w, True) + self._dfs(w) + self.post_traverse(e, w) + else: + self.etype[e] = 2 + self.pre_traverse(e, w, False) + else: + w = e.other(v) + e.set_vertices(v, w) + if self.state.get(w, 0) == 0: + self.pre_traverse(e, w, True) + self._dfs(w) + self.post_traverse(e, w) + else: + self.pre_traverse(e, w, False) + self.state[v] = 2 + + # -- hooks -------------------------------------------------------- + + def pre_traverse(self, e, w, tree_edge): + v = e.other(w) + self.num_not_visited_tree_edges[v] = ( + self.num_not_visited_tree_edges.get(v, 0) - 1 + ) + if self.starts_path.get(e, False): + self.update_t_stack(v, w, tree_edge) + if not tree_edge: + if w == self.parent.get(v): + el = [e, self.tree_arc.get(v)] + C = self.new_component(el) + virt_e = self.new_virtual_edge(C, w, v) + for edge in C: + self.assigned_virt[edge] = virt_e + self.make_tree_edge(virt_e, w, v) + else: + self.e_stack.append(e) + + def post_traverse(self, e, w): + v = e.other(w) + if self.is_hidden.get(e, False): + e_to_push = self.assigned_virt.get(e) + while self.is_hidden.get(e_to_push, False): + e_to_push = self.assigned_virt.get(e_to_push) + self.e_stack.append(e_to_push) + else: + self.e_stack.append(e) + self.check_type2(e, v, w) + self.check_type1(e, v, w) + if self.starts_path.get(e, False): + while self.t_stack and self.t_stack[-1] is not self.EOS: + self.t_stack.pop() + if self.t_stack: + self.t_stack.pop() # remove EOS + if self.t_stack: + i = self.t_stack[-1] + high_v = self.get_hnum(v) + while (i is not self.EOS and i.a != v and i.b != v + and high_v > i.numH): + self.t_stack.pop() + i = self.t_stack[-1] if self.t_stack else self.EOS + + # -- updateTStack (reconstructed) -------------------------------- + + def update_t_stack(self, v, w, is_tree_edge): + last_removed = None + y = -1 + if is_tree_edge: + while (self.t_stack and self.t_stack[-1] is not self.EOS + and self.t_stack[-1].numA > self.get_l1num(w)): + last_removed = self.t_stack.pop() + if last_removed.numH > y: + y = last_removed.numH + h = self.get_num(w) + self.get_numdesc(w) - 1 + if last_removed is None: + item = self._ts(h, self.meta["lp1v"][w], v) + else: + item = self._ts(max(y, h), self.meta["lp1v"][w], last_removed.b) + self.t_stack.append(item) + self.t_stack.append(self.EOS) + else: + while (self.t_stack and self.t_stack[-1] is not self.EOS + and self.t_stack[-1].numA > self.get_num(w)): + last_removed = self.t_stack.pop() + if last_removed.numH > y: + y = last_removed.numH + if last_removed is None: + item = self._ts(self.get_num(v), w, v) + else: + item = self._ts(y, w, last_removed.b) + self.t_stack.append(item) + + # -- checkType1 --------------------------------------------------- + + def check_type1(self, e_backtrack, v, w): + if (self.get_l2num(w) >= self.get_num(v) + and self.get_l1num(w) < self.get_num(v) + and (self.parent.get(v) != self.dfs_root + or self.num_not_visited_tree_edges.get(v, 0) > 0)): + lowpt1_w = self.meta["lp1v"][w] + C = self.new_component([]) + num_w = self.get_num(w) + h = num_w + self.get_numdesc(w) - 1 + e = self.e_stack[-1] if self.e_stack else None + while self.e_stack and ( + (num_w <= self.get_num(e.v1) <= h) + or (num_w <= self.get_num(e.v2) <= h) + ): + e = self.e_stack.pop() + C = self.add_to_component([e], C) + e = self.e_stack[-1] if self.e_stack else None + virtual_edge = self.new_virtual_edge(C, v, lowpt1_w) + for edge in C: + self.assigned_virt[edge] = virtual_edge + if self.e_stack and self.is_same_edge(self.e_stack[-1], v, lowpt1_w): + e = self.e_stack.pop() + el = [e, virtual_edge] + C = self.new_component(el) + virtual_edge = self.new_virtual_edge(C, v, lowpt1_w) + for edge in C: + self.assigned_virt[edge] = virtual_edge + if lowpt1_w != self.parent.get(v): + self.e_stack.append(virtual_edge) + else: + tree_arc_v = self.tree_arc.get(v) + el = [tree_arc_v, virtual_edge] + C = self.new_component(el) + virtual_edge = self.new_virtual_edge(C, lowpt1_w, v) + for edge in C: + self.assigned_virt[edge] = virtual_edge + self.tree_arc[v] = virtual_edge + self.meta["ordered_adj"][v].append(virtual_edge) + self.make_tree_edge(virtual_edge, lowpt1_w, v) + + # -- checkType2 --------------------------------------------------- + + def check_type2(self, e_backtrack, v, w): + top = self.t_stack[-1] if self.t_stack else None + adj_w = self.meta["ordered_adj"][w] + first_child = adj_w[0].other(w) if adj_w else None + edge_count_w = self.meta["edge_count"][w] + while v != self.dfs_root and ( + (top is not None and top is not self.EOS and top.a == v) + or (edge_count_w == 2 and first_child is not None + and self.get_num(first_child) > self.get_num(w)) + ): + e_ab: List[Edge] = [] + virt_edge = None + C = None + if (top is not None and top is not self.EOS and top.a == v + and self.parent.get(top.b) == top.a): + self.t_stack.pop() + top = self.t_stack[-1] if self.t_stack else None + continue + C = self.new_component([]) + if (edge_count_w == 2 and first_child is not None + and self.get_num(first_child) > self.get_num(w)): + # simple type-2 case + e1 = self.e_stack.pop() + el = [e1] + e2 = self.e_stack.pop() + el.append(e2) + self.add_to_component(el, C) + virt_edge = self.new_virtual_edge(C, v, first_child) + for edge in C: + self.assigned_virt[edge] = virt_edge + if self.e_stack: + e = self.e_stack[-1] + if (self.is_same_edge(e, v, top.b if top else None) + or self.is_same_edge(e, v, first_child)): + e_ab.append(self.e_stack.pop()) + else: + top = self.t_stack.pop() + e = self.e_stack[-1] if self.e_stack else None + while (e is not None + and top.numA <= self.get_num(e.v1) + and top.numA <= self.get_num(e.v2) + and self.get_num(e.v1) <= top.numH + and self.get_num(e.v2) <= top.numH): + e = self.e_stack.pop() + if self.is_same_edge(e, top.a, top.b): + e_ab.append(e) + else: + C = self.add_to_component([e], C) + e = self.e_stack[-1] if self.e_stack else None + virt_edge = self.new_virtual_edge(C, top.a, top.b) + for edge in C: + self.assigned_virt[edge] = virt_edge + if e_ab: + e_ab.append(virt_edge) + C = self.new_component(e_ab) + if (top is None or top.b is None + or (first_child is not None + and self.is_same_edge(e_ab[0], v, first_child))): + b = first_child + else: + b = top.b + virt_edge = self.new_virtual_edge(C, v, b) + for edge in C: + self.assigned_virt[edge] = virt_edge + self.e_stack.append(virt_edge) + self.make_tree_edge(virt_edge, v, virt_edge.other(v)) + w = virt_edge.other(v) + self.parent[w] = v + top = self.t_stack[-1] if self.t_stack else None + adj_w = self.meta["ordered_adj"][w] + first_child = adj_w[0].other(w) if adj_w else None + edge_count_w = self.meta["edge_count"][w] + + # -- component helpers ------------------------------------------- + + def new_component(self, comp_edges): + self.remove_edges(comp_edges) + self.comp.append(comp_edges) + return comp_edges + + def add_to_component(self, comp_edges, component): + self.remove_edges(comp_edges) + component.extend(comp_edges) + return component + + def remove_edges(self, edges): + for e in edges: + adj = self.meta["ordered_adj"].get(e.v1, []) + if adj and e in adj: + adj.remove(e) + if e in self.g.edges: + self.g.remove_edge(e) + self.update_edge_count(e.v1, -1) + self.update_edge_count(e.v2, -1) + self.is_hidden[e] = True + + def new_virtual_edge(self, component, v, w): + ve = self.g.add_virtual_edge(v, w) + self.update_edge_count(v, 1) + self.update_edge_count(w, 1) + ve.id = str(uuid.uuid4()) + self.virt[ve] = True + component.insert(0, ve) + self.meta["ordered_adj"][v].append(ve) + return ve + + def make_tree_edge(self, e, v, w): + e.set_vertices(v, w) + self.etype[e] = 1 + + def update_edge_count(self, node, i): + self.meta["edge_count"][node] = self.meta["edge_count"].get(node, 0) + i + + +# ---------------------------------------------------------------------- +# Triconnected component tree node + decomposer +# ---------------------------------------------------------------------- + + +class TCNode: + def __init__(self, name=""): + self.name = name + self.ttype = "" # B / P / R / T + self.skeleton = Skeleton() + self.boundary: List = [] + self.children: List["TCNode"] = [] + + def __repr__(self): + return f"{self.ttype or '?'}{self.name}" + + +def _order_adj_lists(g: Skeleton, meta: dict) -> Dict[object, List[Edge]]: + n = len(g.vertices) + bucket_size = 3 * n + 2 + bucket = [[] for _ in range(bucket_size)] + num = meta["num"] + lp1 = meta["lp1n"] + lp2 = meta["lp2n"] + etype = meta["etype"] + for e in g.edges: + if etype.get(e, 0) == 1: # tree edge + if lp2[e.v2] < num[e.v1]: + phi = 3 * lp1[e.v2] + else: + phi = 3 * lp1[e.v2] + 2 + else: # back edge + phi = 3 * num[e.v2] + 1 + bucket[phi - 1].append(e) + ordered: Dict[object, List[Edge]] = {v: [] for v in g.vertices} + for el in bucket: + for e in el: + ordered[e.v1].append(e) + meta["ordered_adj"] = ordered + return ordered + + +def _sort_consecutive_multiple_edges(g: Skeleton) -> List[Edge]: + indices = {v: i for i, v in enumerate(g.vertices)} + bucket = [[] for _ in range(len(g.vertices))] + for e in g.edges: + i = min(indices[e.v1], indices[e.v2]) + bucket[i].append(e) + sorted_edges: List[Edge] = [] + for el in bucket: + groups: Dict[int, List[Edge]] = {} + for e in el: + key = indices[e.v1] + indices[e.v2] + groups.setdefault(key, []).append(e) + for g_edges in groups.values(): + sorted_edges.extend(g_edges) + return sorted_edges + + +def _split_off_initial_multiple_edges(g, components, virt, assigned, hidden): + edges = _sort_consecutive_multiple_edges(g) + temp = [] + last = None + size = 0 + for cur in edges: + if last is not None: + same = ((cur.v1 == last.v1 and cur.v2 == last.v2) + or (cur.v1 == last.v2 and cur.v2 == last.v1)) + if same: + temp.append(last) + size += 1 + elif size > 0: + temp.append(last) + _md_new_component(g, components, temp, virt, assigned, + hidden, last.v1, last.v2) + temp = [] + size = 0 + last = cur + if size > 0: + temp.append(last) + _md_new_component(g, components, temp, virt, assigned, hidden, + last.v1, last.v2) + + +def _md_new_component(g, components, temp, virt, assigned, hidden, v1, v2): + for e in temp: + if e in g.edges: + g.remove_edge(e) + hidden[e] = True + ve = g.add_virtual_edge(v1, v2) + virt[ve] = True + temp.insert(0, ve) + for e in temp: + assigned[e] = ve + components.append(temp) + + +def _find_split_components(g, components, virt, assigned, hidden, meta, root): + adj = {v: list(g.get_edges(v)) for v in g.vertices} + meta["adj"] = adj + dfs1 = _DFS(g, meta, adj, "low") + dfs1.start(root) + ordered = _order_adj_lists(g, meta) + copied = {v: list(lst) for v, lst in ordered.items()} + # reset edge types for the renumber DFS (preserve nothing across) + dfs2 = _DFS(g, meta, copied, "number") + # NumberDFS reuses parent/treearc/highpt maps – clear etype first + for e in g.edges: + meta["etype"][e] = 0 + for v in g.vertices: + meta["state"][v] = 0 + dfs2.start(root) + meta["ordered_adj"] = {v: list(lst) for v, lst in copied.items()} + meta["edge_count"] = {v: len(g.get_edges(v)) for v in g.vertices} + # reset etype/state for the split DFS + for e in g.edges: + meta["etype"][e] = 0 + for v in g.vertices: + meta["state"][v] = 0 + dfs3 = _SplitCompDFS( + g, meta, meta["ordered_adj"], components, + meta["parent"], meta["tree_arc"], meta["highpt"], + meta["etype"], virt, assigned, hidden, + ) + dfs3.start(root) + + +def get_triconnected_components(g: Skeleton, back_edge: Edge): + components: List[List[Edge]] = [] + virt: Dict[Edge, bool] = {e: False for e in g.edges} + virt[back_edge] = True + assigned: Dict[Edge, Edge] = {} + hidden: Dict[Edge, bool] = {e: False for e in g.edges} + meta: dict = {} + for e in g.edges: + if e.is_self_loop(): + return None + _split_off_initial_multiple_edges(g, components, virt, assigned, hidden) + _find_split_components(g, components, virt, assigned, hidden, meta, + back_edge.v1) + + # build TCNodes + nodes: List[TCNode] = [] + for i, el in enumerate(components): + node = TCNode(str(i)) + sk = Skeleton() + for edge in el: + if virt.get(edge, False): + ve = sk.add_virtual_edge(edge.v1, edge.v2) + ve.id = edge.id + else: + sk.add_edge(edge.v1, edge.v2) + node.skeleton = sk + nodes.append(node) + _classify(nodes) + + # merge components sharing a virtual edge (same type, same id) + result: List[TCNode] = [] + queue = list(nodes) + while queue: + node = queue.pop(0) + if node.ttype == "R": + result.append(node) + continue + delete = False + remove = None + replace = None + for other in queue: + if node.ttype != other.ttype: + continue + for edge in [e for e in node.skeleton.edges if e.virtual]: + # Match the shared virtual edge by id, not by endpoints: + # a bond may carry several parallel virtual edges between + # the same poles, so get_edge(v1, v2) would return an + # arbitrary one and miss the actual shared split edge. + e = next( + (x for x in other.skeleton.edges + if x.virtual and x.id == edge.id), + None, + ) + if e is None: + continue + remove = other + replace = TCNode(other.name) + replace.ttype = other.ttype + rs = Skeleton() + for e2 in node.skeleton.edges: + if e2 is edge: + continue + ne = (rs.add_virtual_edge(e2.v1, e2.v2) if e2.virtual + else rs.add_edge(e2.v1, e2.v2)) + ne.id = e2.id + for e2 in other.skeleton.edges: + if e2 is e: + continue + ne = (rs.add_virtual_edge(e2.v1, e2.v2) if e2.virtual + else rs.add_edge(e2.v1, e2.v2)) + ne.id = e2.id + replace.skeleton = rs + delete = True + break + if delete: + break + if not delete: + result.append(node) + continue + queue.remove(remove) + queue.append(replace) + return result + + +def _classify(nodes: List[TCNode]): + rc = bc = pc = 0 + for n in nodes: + if n.skeleton.count_vertices() == 2: + n.ttype = "B" + n.name = f"B{bc}" + bc += 1 + continue + is_s = True + for v in n.skeleton.vertices_with_edges(): + if len(n.skeleton.get_edges(v)) != 2: + is_s = False + break + if is_s: + n.ttype = "P" + n.name = f"P{pc}" + pc += 1 + else: + n.ttype = "R" + n.name = f"R{rc}" + rc += 1 + + +# ---------------------------------------------------------------------- +# RPST public entry +# ---------------------------------------------------------------------- + + +class RPSTFragment: + def __init__(self): + self.ttype = "" + self.name = "" + self.entry = None + self.exit = None + self.boundary: List = [] + # directed edges (u, v) of the fragment (back-edge / v* mapped out) + self.edges: Set[Tuple[object, object]] = set() + self.children: List["RPSTFragment"] = [] + self.is_loop = False + + +def _build_tctree(nodes: List[TCNode], back_edge: Edge) -> Optional[TCNode]: + """Nest the triconnected components into a tree via shared virtual + edges, then attach trivial (T) children for every real edge.""" + # adjacency: virtual-edge id -> the (<=2) components carrying it + by_vid: Dict[str, List[TCNode]] = {} + for n in nodes: + for e in n.skeleton.edges: + if e.virtual and e.id: + by_vid.setdefault(e.id, []).append(n) + + # root = component containing the back edge + root = None + for n in nodes: + if n.skeleton.get_edge(back_edge.v1, back_edge.v2) is not None: + root = n + break + if root is None: + return None + root.boundary = [back_edge.v1, back_edge.v2] + + visited = {id(root)} + queue = [root] + while queue: + cur = queue.pop(0) + for e in cur.skeleton.edges: + if not (e.virtual and e.id): + continue + for nb in by_vid.get(e.id, []): + if id(nb) in visited: + continue + visited.add(id(nb)) + nb.boundary = [e.v1, e.v2] + cur.children.append(nb) + queue.append(nb) + + # trivial children for every real (non-virtual) edge + tc = 0 + all_nodes = [] + stack = [root] + while stack: + n = stack.pop() + all_nodes.append(n) + stack.extend(n.children) + for n in list(all_nodes): + for e in n.skeleton.edges: + if e.virtual: + continue + t = TCNode(f"T{tc}") + tc += 1 + t.ttype = "T" + t.boundary = [e.v1, e.v2] + t.skeleton = Skeleton() + t.skeleton.add_edge(e.v1, e.v2) + n.children.append(t) + return root + + +def compute_rpst(directed_edges: List[Tuple[object, object]]): + """Compute the RPST of a single-source/single-sink directed graph. + + Returns ``(root_fragment, src, sink)`` or ``None`` when the graph is + not biconnected (the reference returns a null root in that case). + """ + # First-seen node order keeps the whole decomposition deterministic + # (set iteration order must never leak into the triconnected split). + nodes: List[object] = [] + seen: Set[object] = set() + indeg: Dict[object, int] = {} + outdeg: Dict[object, int] = {} + for (u, v) in directed_edges: + for x in (u, v): + if x not in seen: + seen.add(x) + nodes.append(x) + outdeg[u] = outdeg.get(u, 0) + 1 + indeg[v] = indeg.get(v, 0) + 1 + sources = [n for n in nodes if indeg.get(n, 0) == 0] + sinks = [n for n in nodes if outdeg.get(n, 0) == 0] + if len(sources) != 1 or len(sinks) != 1: + return None + src, snk = sources[0], sinks[0] + + # split vertices with >1 in and >1 out (v -> v*) + star: Dict[object, object] = {} + for n in nodes: + if indeg.get(n, 0) > 1 and outdeg.get(n, 0) > 1: + star[n] = (n, "*") # unique sentinel + + sk = Skeleton() + dir_edges: List[Tuple[object, object]] = [] + for (u, v) in directed_edges: + su = star[u] if u in star else u + sk.add_edge(su, v) + dir_edges.append((su, v)) + for n, ns in star.items(): + sk.add_edge(n, ns) + dir_edges.append((n, ns)) + back_edge = sk.add_edge(snk, src) + + comps = get_triconnected_components(sk, back_edge) + if comps is None: + return None + root_tc = _build_tctree(comps, back_edge) + if root_tc is None: + return None + + # ------------------------------------------------------------------ + # RPST refinement on the triconnected-component tree + # ------------------------------------------------------------------ + extra_boundaries = {frozenset((n, ns)) for n, ns in star.items()} + + # (1) remove quasi trivial nodes: T children that are a v->v* edge + def _remove_quasi(n: TCNode): + n.children = [ + c for c in n.children + if not (c.ttype == "T" and frozenset(c.boundary) in extra_boundaries) + ] + for c in n.children: + _remove_quasi(c) + + _remove_quasi(root_tc) + + # (2) contract nodes with exactly one child (replace node by child) + def _parents(n, pmap): + for c in n.children: + pmap[id(c)] = n + _parents(c, pmap) + + changed = True + while changed: + changed = False + pmap: Dict[int, TCNode] = {} + _parents(root_tc, pmap) + stack = [root_tc] + while stack: + n = stack.pop() + if len(n.children) == 1: + child = n.children[0] + if n is root_tc: + root_tc = child + else: + p = pmap[id(n)] + p.children[p.children.index(n)] = child + changed = True + break + stack.extend(n.children) + + # ------------------------------------------------------------------ + # directed maps in real (un-split) space, from the original edges + # ------------------------------------------------------------------ + out_adj: Dict[object, Set[object]] = {} + in_adj: Dict[object, Set[object]] = {} + for (u, v) in directed_edges: + out_adj.setdefault(u, set()).add(v) + in_adj.setdefault(v, set()).add(u) + + unstar = {ns: n for n, ns in star.items()} + + def _real(x): + return unstar.get(x, x) + + def _convert(tc: TCNode) -> Optional[RPSTFragment]: + if tc.ttype == "T" and src in tc.boundary and snk in tc.boundary: + return None + f = RPSTFragment() + f.ttype = tc.ttype + f.name = tc.name + f.boundary = [_real(b) for b in tc.boundary] + for c in tc.children: + cf = _convert(c) + if cf is not None: + f.children.append(cf) + return f + + root = _convert(root_tc) + if root is None: + return None + + def _fill_edges(f: RPSTFragment): + for c in f.children: + _fill_edges(c) + f.edges |= c.edges + if f.ttype == "T" and len(f.boundary) == 2: + a, b = f.boundary + if a != b: + if b in out_adj.get(a, set()): + f.edges.add((a, b)) + if a in out_adj.get(b, set()): + f.edges.add((b, a)) + + _fill_edges(root) + + # orient entry/exit: entry is the boundary node that sources the + # fragment (no incoming edge from within it); fall back to the + # reference rule when both / neither qualify. + def _orient(f: RPSTFragment, is_root: bool): + if is_root: + f.entry, f.exit = src, snk + elif len(f.boundary) == 2: + b0, b1 = f.boundary + cin0 = any(v == b0 for (_u, v) in f.edges) + cin1 = any(v == b1 for (_u, v) in f.edges) + if snk in (b0, b1): + # the global sink can only be a fragment exit + f.exit = snk + f.entry = b0 if b1 == snk else b1 + elif src in (b0, b1): + # the global source can only be a fragment entry + f.entry = src + f.exit = b0 if b1 == src else b1 + elif not cin0 and cin1: + f.entry, f.exit = b0, b1 + elif not cin1 and cin0: + f.entry, f.exit = b1, b0 + else: + entry, exit_ = b0, b1 + coutf = sum(1 for (u, _v) in f.edges if u == entry) + coutg = len(out_adj.get(entry, set())) + if not ((not cin0) or coutf == coutg): + entry, exit_ = exit_, entry + f.entry, f.exit = entry, exit_ + for c in f.children: + _orient(c, False) + + _orient(root, True) + return root, src, snk diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/working_graph.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/working_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..e79f3ff5773f3506b49fbc7b729f87b1ca765c80 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/dtypes/working_graph.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 +''' +"""Mutable adjacency representation used during the Split Miner pipeline. + +The split / join discovery phases need fast structural edits (re-target an +edge, insert a gateway, remove a node) that the immutable pm4py BPMN +object does not support efficiently. We therefore keep an internal +``WorkingGraph`` for the duration of the discovery and only materialise +the final :class:`pm4py.objects.bpmn.obj.BPMN` object at the end (see +:mod:`pm4py.algo.discovery.split_miner.bpmn_export`). +""" +from dataclasses import dataclass, field +from typing import Dict, FrozenSet, List, Literal, Optional, Set, Tuple + +NodeKind = Literal["task", "xor", "and", "or", "start", "end"] + + +@dataclass +class Node: + id: str + kind: NodeKind + label: str = "" + + +@dataclass +class WorkingGraph: + """Adjacency-list representation of a BPMN graph in construction.""" + + nodes: Dict[str, Node] = field(default_factory=dict) + out_edges: Dict[str, List[str]] = field(default_factory=dict) + in_edges: Dict[str, List[str]] = field(default_factory=dict) + + start_id: str = "" + end_id: str = "" + + concurrency: Set[FrozenSet[str]] = field(default_factory=set) + self_loops: Set[str] = field(default_factory=set) + + _id_counter: int = 0 + + # ------------------------------------------------------------------ + # mutation helpers + # ------------------------------------------------------------------ + + def fresh_id(self, prefix: str) -> str: + self._id_counter += 1 + return f"{prefix}_{self._id_counter}" + + def add_node( + self, + kind: NodeKind, + label: str = "", + node_id: Optional[str] = None, + ) -> str: + if node_id is None: + node_id = self.fresh_id(kind) + self.nodes[node_id] = Node(id=node_id, kind=kind, label=label) + self.out_edges.setdefault(node_id, []) + self.in_edges.setdefault(node_id, []) + return node_id + + def add_edge(self, src: str, tgt: str) -> None: + if tgt not in self.out_edges[src]: + self.out_edges[src].append(tgt) + if src not in self.in_edges[tgt]: + self.in_edges[tgt].append(src) + + def remove_edge(self, src: str, tgt: str) -> None: + if tgt in self.out_edges.get(src, []): + self.out_edges[src].remove(tgt) + if src in self.in_edges.get(tgt, []): + self.in_edges[tgt].remove(src) + + def remove_node(self, node_id: str) -> None: + for s in list(self.in_edges.get(node_id, [])): + self.remove_edge(s, node_id) + for t in list(self.out_edges.get(node_id, [])): + self.remove_edge(node_id, t) + self.in_edges.pop(node_id, None) + self.out_edges.pop(node_id, None) + self.nodes.pop(node_id, None) + + # ------------------------------------------------------------------ + # queries + # ------------------------------------------------------------------ + + def successors(self, node_id: str) -> List[str]: + return list(self.out_edges.get(node_id, [])) + + def predecessors(self, node_id: str) -> List[str]: + return list(self.in_edges.get(node_id, [])) + + def edges(self) -> List[Tuple[str, str]]: + return [(s, t) for s, ts in self.out_edges.items() for t in ts] + + def is_concurrent(self, a: str, b: str) -> bool: + return frozenset((a, b)) in self.concurrency diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d77079b93465e591a069cda70ff87349096d678f --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/__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.discovery.split_miner.filtering import abc, max_min diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..cbde5389deb215b601d32372c2b21a03bc10f188 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/abc.py @@ -0,0 +1,40 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Abstract base class for the PDFG filtering phase.""" +from abc import ABC, abstractmethod +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG +from pm4py.algo.discovery.split_miner.dtypes.filtering import FilterResult + + +class Filterer(ABC): + """Reduce a pruned DFG to a sound, low-complexity edge set.""" + + @classmethod + @abstractmethod + def apply( + cls, + pdfg: DFG, + parameters: Optional[Dict[str, Any]] = None, + ) -> FilterResult: + """Return the source/sink and the kept edges.""" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/max_min.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/max_min.py new file mode 100644 index 0000000000000000000000000000000000000000..524d369ba26df84d8c0cf85098523f06104713c5 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/filtering/max_min.py @@ -0,0 +1,244 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Frequency filter with connectedness guarantees for the pruned DFG. + +This reproduces the reference Split Miner ``filterWithGuarantees`` (the +"FWG" filter used by the command-line miner): + +1. A frequency threshold is taken as the ``eta`` order statistic of the + per-node most-frequent incoming/outgoing edges. +2. A max-capacity (widest path) spanning set is computed from source and + to sink so the highest-throughput backbone is always retained. +3. Every edge is kept when it belongs to that backbone or when its + frequency reaches the threshold; the remaining edges are dropped, but + never the sole incoming edge of a node nor the sole outgoing edge of a + node (the connectedness guard). + +This is a faithful port of the Java ``filterWithGuarantees``, validated +to produce the same pruned DFG as ``splitminer.jar`` on the +SM-Experiment logs (see ``..algorithm`` for the validation summary). The +max-capacity backbone plus the connectedness guard frequently make the +result insensitive to ``eta`` — a high threshold still keeps the +backbone — which mirrors the reference tool and is not a bug. +""" +import math +from collections import deque +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Tuple + +from pm4py.algo.discovery.split_miner.dtypes.dfg import DFG +from pm4py.algo.discovery.split_miner.dtypes.filtering import FilterResult +from pm4py.algo.discovery.split_miner.dtypes.log import END_LABEL, START_LABEL +from pm4py.algo.discovery.split_miner.filtering.abc import Filterer +from pm4py.util import exec_utils + + +class Parameters(Enum): + ETA = "split_miner_eta" + + +DEFAULT_ETA = 0.4 + +Edge = Tuple[str, str] + + +def _node_set(dfg: DFG) -> Set[str]: + s: Set[str] = set() + for a, b in dfg.keys(): + s.add(a) + s.add(b) + return s + + +def _find_source_sink(dfg: DFG, nodes: Set[str]) -> Tuple[str, str]: + has_in = {b for (_, b) in dfg.keys()} + has_out = {a for (a, _) in dfg.keys()} + sources = [n for n in nodes if n not in has_in] + sinks = [n for n in nodes if n not in has_out] + if len(sources) != 1 or len(sinks) != 1: + if START_LABEL in nodes and END_LABEL in nodes: + return START_LABEL, END_LABEL + raise ValueError( + f"Filtered PDFG must have exactly one source/sink; " + f"got sources={sources}, sinks={sinks}" + ) + return sources[0], sinks[0] + + +def _edge_rank(edge: Edge, freq: int) -> Tuple[int, str, str]: + """Total order matching the reference DFGEdge comparator. + + Edges are ordered by frequency, then by source label, then by target + label. ``max`` therefore picks the most frequent edge, breaking ties + towards the lexicographically greatest endpoints. + """ + a, b = edge + return (freq, a, b) + + +def _max_frequency_best_edges( + dfg: DFG, source: str, sink: str, nodes: Set[str] +) -> Set[Edge]: + """Per-node most frequent incoming/outgoing edges (deduplicated). + + Mirrors ``bestEdgesOnMaxFrequencies``: every node except the sink + contributes its most frequent outgoing edge and every node except the + source contributes its most frequent incoming edge. + """ + out_edges: Dict[str, List[Edge]] = {n: [] for n in nodes} + in_edges: Dict[str, List[Edge]] = {n: [] for n in nodes} + for (a, b) in dfg.keys(): + out_edges[a].append((a, b)) + in_edges[b].append((a, b)) + + best: Set[Edge] = set() + for n in nodes: + if n != sink and out_edges[n]: + best.add(max(out_edges[n], key=lambda e: _edge_rank(e, dfg[e]))) + if n != source and in_edges[n]: + best.add(max(in_edges[n], key=lambda e: _edge_rank(e, dfg[e]))) + return best + + +def _filter_threshold(dfg: DFG, best_freq_edges: Set[Edge], eta: float) -> int: + """``computeFilterThreshold``: the ``eta`` order statistic. + + The most-frequent best edges are sorted ascending; the threshold is + the frequency at index ``round(N * eta)`` (clamped to the last index). + """ + if not best_freq_edges: + return 0 + ordered = sorted(best_freq_edges, key=lambda e: _edge_rank(e, dfg[e])) + i = int(round(len(ordered) * eta)) + if i >= len(ordered): + i = len(ordered) - 1 + return dfg[ordered[i]] + + +def _max_capacity_best_edges( + dfg: DFG, source: str, sink: str, nodes: Set[str] +) -> Set[Edge]: + """Widest-path backbone from source and to sink (``bestEdgesOnMaxCapacities``). + + A Bellman-Ford style relaxation computes, for every node, the maximum + bottleneck capacity reachable from the source and the symmetric value + towards the sink, recording the edge that realises each optimum. + """ + out_adj: Dict[str, List[Tuple[str, int]]] = {n: [] for n in nodes} + in_adj: Dict[str, List[Tuple[str, int]]] = {n: [] for n in nodes} + for (a, b), f in dfg.items(): + out_adj[a].append((b, f)) + in_adj[b].append((a, f)) + + best: Set[Edge] = set() + + # Forward: widest path from the source. + cap_from: Dict[str, float] = {n: 0 for n in nodes} + cap_from[source] = math.inf + best_pred: Dict[str, Edge] = {} + queue = deque([source]) + in_q: Set[str] = {source} + while queue: + p = queue.popleft() + in_q.discard(p) + cap_p = cap_from[p] + for b, f in out_adj[p]: + c = f if cap_p > f else cap_p + if c > cap_from[b]: + cap_from[b] = c + best_pred[b] = (p, b) + if b not in in_q: + queue.append(b) + in_q.add(b) + best.update(best_pred.values()) + + # Backward: widest path to the sink. + cap_to: Dict[str, float] = {n: 0 for n in nodes} + cap_to[sink] = math.inf + best_succ: Dict[str, Edge] = {} + queue = deque([sink]) + in_q = {sink} + while queue: + n = queue.popleft() + in_q.discard(n) + cap_n = cap_to[n] + for a, f in in_adj[n]: + c = f if cap_n > f else cap_n + if c > cap_to[a]: + cap_to[a] = c + best_succ[a] = (a, n) + if a not in in_q: + queue.append(a) + in_q.add(a) + best.update(best_succ.values()) + + return best + + +class MaxMinFilterer(Filterer): + """Port of the reference ``filterWithGuarantees`` (FWG) filter.""" + + @classmethod + def apply( + cls, + pdfg: DFG, + parameters: Optional[Dict[str, Any]] = None, + ) -> FilterResult: + eta = exec_utils.get_param_value( + Parameters.ETA, parameters or {}, DEFAULT_ETA + ) + nodes = _node_set(pdfg) + source, sink = _find_source_sink(pdfg, nodes) + + # (1) threshold from the most-frequent best edges, + # (2) widest-path backbone that must survive the filter. + freq_best = _max_frequency_best_edges(pdfg, source, sink, nodes) + threshold = _filter_threshold(pdfg, freq_best, eta) + cap_best = _max_capacity_best_edges(pdfg, source, sink, nodes) + + # Live degree bookkeeping for the connectedness guard. + in_deg: Dict[str, int] = {n: 0 for n in nodes} + out_deg: Dict[str, int] = {n: 0 for n in nodes} + for (a, b) in pdfg.keys(): + out_deg[a] += 1 + in_deg[b] += 1 + + kept: Set[Edge] = set() + removable: List[Edge] = [] + for (a, b), f in pdfg.items(): + if (a, b) in cap_best or f >= threshold: + kept.add((a, b)) + else: + removable.append((a, b)) + + # Drop the remaining edges deterministically, but never the sole + # incoming edge of a node nor the sole outgoing edge of a node. + for (a, b) in sorted( + removable, key=lambda e: _edge_rank(e, pdfg[e]) + ): + if in_deg[b] == 1 or out_deg[a] == 1: + kept.add((a, b)) + continue + in_deg[b] -= 1 + out_deg[a] -= 1 + + return FilterResult(edges=kept, source=source, sink=sink) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/heuristics/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/heuristics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..37a0cb49e634aba229a37b38a62c7a5b0db9615a --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/heuristics/__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 +''' +"""Removed module — compatibility shim. + +``pm4py.algo.discovery.split_miner.heuristics`` (``OrSplitHeuristic``, +``ImproperCompletionHeuristic``) belonged to an earlier, approximate +Split Miner 2.0 and was removed when the variant was reworked to +reproduce the reference Java implementation (``MineWithSMTC``) exactly. + +* The OR-split heuristic is now an intrinsic stage of the faithful SM2 + pipeline (``pm4py.algo.discovery.split_miner.or_min.or_split``); it + runs automatically for ``variant='sm2'``. +* The improper-completion heuristic was an approximation with no + equivalent in the reference tool and has been dropped. + +Use the public API instead:: + + pm4py.discover_bpmn_split_miner(log, variant='sm2') +""" +raise ImportError( + "pm4py.algo.discovery.split_miner.heuristics was removed when Split " + "Miner 2.0 was reworked to faithfully match the reference Java tool. " + "The OR-split heuristic now runs automatically for variant='sm2'; the " + "improper-completion heuristic was an approximation and was dropped. " + "Use pm4py.discover_bpmn_split_miner(log, variant='sm2')." +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f302aedc2957bfeea7c65d79033845201feccf1c --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/__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.discovery.split_miner.joins import abc, sese diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe719980672923658d601f7bd084e8b3d041afd --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/abc.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 +''' +"""Abstract base class for the joins-discovery phase.""" +from abc import ABC, abstractmethod +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph + + +class JoinsDiscoverer(ABC): + """Insert join gateways for every node with multiple incoming edges.""" + + @classmethod + @abstractmethod + def apply( + cls, + wg: WorkingGraph, + parameters: Optional[Dict[str, Any]] = None, + ) -> None: + """Mutate ``wg`` in-place by inserting the discovered joins.""" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..337d08b4338512602813f1cf36def4c15246d0ad --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/classic.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 +''' +"""Removed module — compatibility shim. + +``joins.classic`` was an early join discoverer superseded by the +RPST-based SESE join discovery in +``pm4py.algo.discovery.split_miner.joins.sese`` (``SeseJoinsDiscoverer``), +which both Split Miner variants now use. + +Use the public API instead:: + + pm4py.discover_bpmn_split_miner(log) +""" +raise ImportError( + "pm4py.algo.discovery.split_miner.joins.classic was removed; use " + "pm4py.algo.discovery.split_miner.joins.sese.SeseJoinsDiscoverer " + "(wired automatically). " + "Use pm4py.discover_bpmn_split_miner(log)." +) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/sese.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/sese.py new file mode 100644 index 0000000000000000000000000000000000000000..3295c728fd03fd107d2f2d7df02bf67e11b39245 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/joins/sese.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 +''' +"""Join discovery: SESE joins (RPST) + inner OR-joins. + +* ``generateSESEjoins`` repeatedly computes the RPST of the current + model and, for every bond or rigid fragment whose convergence node is + not yet a gateway, inserts a join there. A bond inherits the gateway + type of its matching split; a rigid (and a loop) yields an inclusive + (OR) join. The convergence node is the fragment exit, or the entry for + loop fragments. +* ``generateInnerJoins`` then funnels every remaining multi-incoming + task through a single inclusive (OR) join. + +The inclusive joins are subsequently replaced by the OR-join +minimisation step. + +This is a faithful port of the reference ``generateSESEjoins`` / +``generateInnerJoins``, validated to be byte-identical to +``splitminer.jar`` on the SM-Experiment logs (see ``..algorithm`` for +the validation summary). +""" +from typing import Any, Dict, List, Optional, Set, Tuple + +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph +from pm4py.algo.discovery.split_miner.joins.abc import JoinsDiscoverer +from pm4py.algo.discovery.split_miner.dtypes import rpst_tree + +_GATE_KINDS = {"xor", "and", "or"} + + +def _is_gateway(wg: WorkingGraph, node: str) -> bool: + n = wg.nodes.get(node) + return n is not None and n.kind in _GATE_KINDS + + +def _directed_edges(wg: WorkingGraph) -> List[Tuple[str, str]]: + return [(s, t) for s, ts in wg.out_edges.items() for t in ts] + + +def _collect_fragments(root) -> List: + """RPST fragments in bottom-up order (deepest first).""" + order: List = [] + queue = [root] + while queue: + f = queue.pop(0) + order.insert(0, f) + queue.extend(f.children) + return order + + +def _generate_sese_joins_once(wg: WorkingGraph) -> bool: + edges = _directed_edges(wg) + res = rpst_tree.compute_rpst(edges) + if res is None: + return False + root, _src, _snk = res + + changed: Set[str] = set() + placed = False + for f in _collect_fragments(root): + if f.ttype not in ("B", "R"): + continue + entry, exit_ = f.entry, f.exit + if entry is None or exit_ is None: + continue + exit_is_gate = _is_gateway(wg, exit_) + entry_is_gate = _is_gateway(wg, entry) + if not exit_is_gate: + is_loop = False + gatify, matching = exit_, entry + elif not entry_is_gate: + is_loop = True + gatify, matching = entry, exit_ + else: + continue # both endpoints already gateways + + if gatify in changed: + continue + + if f.ttype == "R": + gtype = "or" + else: + mnode = wg.nodes.get(matching) + if mnode is None or mnode.kind not in _GATE_KINDS: + continue + gtype = mnode.kind + + # fragment-internal predecessors of the convergence node + frag_preds = {u for (u, v) in f.edges if v == gatify} + incoming = list(wg.in_edges.get(gatify, [])) + gate = wg.add_node(gtype, label=gtype) + wg.add_edge(gate, gatify) + for p in incoming: + if p in frag_preds or is_loop: + wg.remove_edge(p, gatify) + wg.add_edge(p, gate) + changed.add(gatify) + placed = True + + return placed + + +def _generate_inner_joins(wg: WorkingGraph) -> None: + for nid in list(wg.nodes.keys()): + n = wg.nodes.get(nid) + if n is None or n.kind in _GATE_KINDS: + continue + preds = list(wg.in_edges.get(nid, [])) + if len(preds) <= 1: + continue + gate = wg.add_node("or", label="or") + for p in preds: + wg.remove_edge(p, nid) + wg.add_edge(p, gate) + wg.add_edge(gate, nid) + + +class SeseJoinsDiscoverer(JoinsDiscoverer): + """RPST-based SESE joins followed by inner inclusive joins.""" + + @classmethod + def apply( + cls, + wg: WorkingGraph, + parameters: Optional[Dict[str, Any]] = None, + ) -> None: + guard = len(wg.nodes) + 5 + while guard > 0 and _generate_sese_joins_once(wg): + guard -= 1 + _generate_inner_joins(wg) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..684b330078f869e038365bcd4816327a7f5e5297 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/__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.discovery.split_miner.or_min import abc, classic, or_split diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/abc.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..4678acf25e0f6df4410272039373b300091fba5f --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/abc.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 +''' +"""Abstract base class for the OR-join minimisation phase.""" +from abc import ABC, abstractmethod +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph + + +class OrJoinMinimizer(ABC): + """Replace trivial OR-joins by their XOR or AND equivalent.""" + + @classmethod + @abstractmethod + def apply( + cls, + wg: WorkingGraph, + parameters: Optional[Dict[str, Any]] = None, + ) -> None: + """Mutate ``wg`` in-place.""" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/classic.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/classic.py new file mode 100644 index 0000000000000000000000000000000000000000..e003c68606f36757791db47f43710d5d34cf76cc --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/classic.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 +''' +"""OR-join minimisation. + +Replace every inclusive (OR) join with the behaviourally equivalent +exclusive (XOR) or parallel (AND) join, following the reference Split +Miner ``replaceIORs`` step. The heavy lifting lives in +:mod:`pm4py.algo.discovery.split_miner.dtypes.gateway_map`, which builds +a gateway map, walks each OR-join back to its dominator and decides +between XOR and AND (inserting token-generator gateways for the parallel +case so the join can always synchronise). +""" +from typing import Any, Dict, Optional + +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph +from pm4py.algo.discovery.split_miner.or_min.abc import OrJoinMinimizer +from pm4py.algo.discovery.split_miner.dtypes.gateway_map import ( + replace_inclusive_joins, +) + + +class ClassicOrJoinMinimizer(OrJoinMinimizer): + """Replace every inclusive (OR) join with an XOR or AND join.""" + + @classmethod + def apply( + cls, + wg: WorkingGraph, + parameters: Optional[Dict[str, Any]] = None, + ) -> None: + replace_inclusive_joins(wg, apply_hagen=True) diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/or_split.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/or_split.py new file mode 100644 index 0000000000000000000000000000000000000000..4493de8a343503a0e81bae124af47a4611c94ca3 --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/or_min/or_split.py @@ -0,0 +1,105 @@ +''' +PM4Py – A Process Mining Library for Python +Copyright (C) 2026 Process Intelligence Solutions GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see this software project's root or +visit . + +Website: https://processintelligence.solutions +Contact: info@processintelligence.solutions +''' +"""Split Miner 2.0 OR-split heuristic. + +An AND-split is promoted to an inclusive +(OR) split when its activity branches form *potential OR* pairs (pairs +observed both concurrently and exclusively, the ``potentialORs`` matrix) +in sufficient number: counting every ordered pair of distinct +activity-target branches that is a potential OR, the split is promoted +when that count exceeds the split's out-degree. Whenever any split is +promoted, ``matchORs`` walks the RPST and turns the exit gateway of +every bond with an inclusive entry into an inclusive gateway too, so the +new OR-split is matched by an OR-join. +""" +from typing import FrozenSet, Set + +from pm4py.algo.discovery.split_miner.dtypes import rpst_tree +from pm4py.algo.discovery.split_miner.dtypes.working_graph import WorkingGraph + +_GATE_KINDS = {"xor", "and", "or"} + + +def apply_or_split_heuristic( + wg: WorkingGraph, + potential_ors: Set[FrozenSet[str]], +) -> None: + """Promote eligible AND-splits to OR-splits and re-match their joins.""" + if not potential_ors: + return + + converted = False + for nid in list(wg.nodes.keys()): + node = wg.nodes.get(nid) + if node is None or node.kind != "and": + continue + succs = wg.successors(nid) + if len(succs) <= 1: + continue + # Only activity (task) branches participate; gateway branches + # are skipped, mirroring the ``instanceof Gateway`` guard. + act_labels = [ + wg.nodes[s].label + for s in succs + if wg.nodes.get(s) is not None and wg.nodes[s].kind == "task" + ] + counter = 0 + for i, a in enumerate(act_labels): + for j, b in enumerate(act_labels): + if i == j: + continue + if frozenset((a, b)) in potential_ors: + counter += 1 + if counter > len(succs): + node.kind = "or" + node.label = "or" + converted = True + + if converted: + _match_ors(wg) + + +def _match_ors(wg: WorkingGraph) -> None: + """For every RPST bond with an inclusive entry, make the exit + inclusive too (port of ``DiagramHandler.matchORs``).""" + edges = [(s, t) for s, ts in wg.out_edges.items() for t in ts] + res = rpst_tree.compute_rpst(edges) + if res is None: + return + root, _src, _snk = res + + queue = [root] + while queue: + frag = queue.pop(0) + queue.extend(frag.children) + if frag.ttype != "B": + continue + entry = wg.nodes.get(frag.entry) if frag.entry else None + exit_ = wg.nodes.get(frag.exit) if frag.exit else None + if ( + entry is not None + and exit_ is not None + and entry.kind == "or" + and exit_.kind in _GATE_KINDS + ): + exit_.kind = "or" + exit_.label = "or" diff --git a/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/sese/__init__.py b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/sese/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3878b7984c452e696fe06bc0fad0f553f7b7654e --- /dev/null +++ b/source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/discovery/split_miner/sese/__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.discovery.split_miner.sese import rpst