linear-continuous-process-mapper 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. linear_continuous_process_mapper-0.1.0/.github/workflows/ci.yml +94 -0
  2. linear_continuous_process_mapper-0.1.0/.gitignore +40 -0
  3. linear_continuous_process_mapper-0.1.0/.python-version +1 -0
  4. linear_continuous_process_mapper-0.1.0/LICENSE +21 -0
  5. linear_continuous_process_mapper-0.1.0/PKG-INFO +152 -0
  6. linear_continuous_process_mapper-0.1.0/README.md +129 -0
  7. linear_continuous_process_mapper-0.1.0/lcm/__init__.py +44 -0
  8. linear_continuous_process_mapper-0.1.0/lcm/constants.py +13 -0
  9. linear_continuous_process_mapper-0.1.0/lcm/data/__init__.py +0 -0
  10. linear_continuous_process_mapper-0.1.0/lcm/data/data_loader.py +49 -0
  11. linear_continuous_process_mapper-0.1.0/lcm/data/data_processor.py +52 -0
  12. linear_continuous_process_mapper-0.1.0/lcm/domain/__init__.py +0 -0
  13. linear_continuous_process_mapper-0.1.0/lcm/domain/graph_analyzer.py +43 -0
  14. linear_continuous_process_mapper-0.1.0/lcm/graph_builders/__init__.py +4 -0
  15. linear_continuous_process_mapper-0.1.0/lcm/graph_builders/abstract_graph_builder.py +18 -0
  16. linear_continuous_process_mapper-0.1.0/lcm/graph_builders/last_activity_based.py +65 -0
  17. linear_continuous_process_mapper-0.1.0/lcm/graph_builders/sequence_based.py +62 -0
  18. linear_continuous_process_mapper-0.1.0/lcm/graph_builders/set_based.py +56 -0
  19. linear_continuous_process_mapper-0.1.0/lcm/logger_config.py +22 -0
  20. linear_continuous_process_mapper-0.1.0/lcm/services/__init__.py +0 -0
  21. linear_continuous_process_mapper-0.1.0/lcm/services/graph_service.py +19 -0
  22. linear_continuous_process_mapper-0.1.0/lcm/services/process_analytics_service.py +132 -0
  23. linear_continuous_process_mapper-0.1.0/lcm/visualization/__init__.py +0 -0
  24. linear_continuous_process_mapper-0.1.0/lcm/visualization/sankey_visualizer.py +175 -0
  25. linear_continuous_process_mapper-0.1.0/marimo_app.py +357 -0
  26. linear_continuous_process_mapper-0.1.0/programmatic_example.py +233 -0
  27. linear_continuous_process_mapper-0.1.0/pyproject.toml +46 -0
  28. linear_continuous_process_mapper-0.1.0/resources/interface-screenshot-annotated.png +0 -0
  29. linear_continuous_process_mapper-0.1.0/resources/interface-screenshot.png +0 -0
  30. linear_continuous_process_mapper-0.1.0/tests/test_lcm.py +319 -0
  31. linear_continuous_process_mapper-0.1.0/uv.lock +1552 -0
@@ -0,0 +1,94 @@
1
+ name: "CI"
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+ branches:
9
+ - main
10
+
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+ strategy:
15
+ fail-fast: false
16
+ matrix:
17
+ python-version: ["3.11", "3.13"]
18
+ steps:
19
+ - name: Checkout โฌ‡๏ธ
20
+ uses: actions/checkout@v7.0.1
21
+
22
+ - name: Set up Python ๐Ÿ
23
+ uses: actions/setup-python@v7.0.0
24
+ with:
25
+ python-version: ${{ matrix.python-version }}
26
+
27
+ - name: Install uv ๐Ÿ“ฆ
28
+ uses: astral-sh/setup-uv@v9.0.0
29
+
30
+ - name: Install dependencies ๐Ÿ“ฆ
31
+ run: uv sync
32
+
33
+ - name: Run tests ๐Ÿงช
34
+ run: uv run pytest
35
+
36
+ build:
37
+ runs-on: ubuntu-latest
38
+ needs: test
39
+ outputs:
40
+ already-published: ${{ steps.version-check.outputs.already-published }}
41
+ steps:
42
+ - name: Checkout โฌ‡๏ธ
43
+ uses: actions/checkout@v7.0.1
44
+
45
+ - name: Set up Python ๐Ÿ
46
+ uses: actions/setup-python@v7.0.0
47
+ with:
48
+ python-version: "3.13"
49
+
50
+ - name: Install uv ๐Ÿ“ฆ
51
+ uses: astral-sh/setup-uv@v9.0.0
52
+
53
+ - name: Check if version already published ๐Ÿ”
54
+ id: version-check
55
+ run: |
56
+ NAME=$(python -c "import tomllib; d=tomllib.load(open('pyproject.toml','rb')); print(d['project']['name'])")
57
+ VERSION=$(python -c "import tomllib; d=tomllib.load(open('pyproject.toml','rb')); print(d['project']['version'])")
58
+ STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://pypi.org/pypi/$NAME/$VERSION/json)
59
+ if [ "$STATUS" = "200" ]; then
60
+ echo "already-published=true" >> $GITHUB_OUTPUT
61
+ else
62
+ echo "already-published=false" >> $GITHUB_OUTPUT
63
+ fi
64
+
65
+ # Built on pull requests too, so a packaging error shows up before the merge.
66
+ - name: Build ๐Ÿ—๏ธ
67
+ run: uv build
68
+
69
+ - name: Upload dist artifacts ๐Ÿ“ค
70
+ uses: actions/upload-artifact@v7.0.1
71
+ with:
72
+ name: dist
73
+ path: dist/
74
+
75
+ publish:
76
+ runs-on: ubuntu-latest
77
+ needs: build
78
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.build.outputs.already-published == 'false'
79
+ environment: pypi
80
+ permissions:
81
+ contents: read
82
+ id-token: write
83
+ steps:
84
+ - name: Download dist artifacts ๐Ÿ“ฅ
85
+ uses: actions/download-artifact@v8.0.1
86
+ with:
87
+ name: dist
88
+ path: dist/
89
+
90
+ - name: Install uv ๐Ÿ“ฆ
91
+ uses: astral-sh/setup-uv@v9.0.0
92
+
93
+ - name: Publish to PyPI ๐Ÿš€
94
+ run: uv publish
@@ -0,0 +1,40 @@
1
+ # Byte-compiled / optimized files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Virtual environments
7
+ btgvenv/
8
+ venv/
9
+ .venv/
10
+ env/
11
+ .env
12
+
13
+ # Jupyter Notebook
14
+ .ipynb_checkpoints/
15
+
16
+ # Flask / Plotly Dash
17
+ instance/
18
+ .webassets-cache
19
+ *.log
20
+
21
+ # Caches
22
+ .cache/
23
+ .pytest_cache/
24
+
25
+ # IDEs and OS files
26
+ .vscode/
27
+ .idea/
28
+ .DS_Store
29
+ *.swp
30
+
31
+ # Build / Packages
32
+ build/
33
+ dist/
34
+ *.egg-info/
35
+
36
+ # Datasets
37
+ datasets/
38
+ logs/
39
+
40
+ __marimo__/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ICS University St.Gallen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.5
2
+ Name: linear-continuous-process-mapper
3
+ Version: 0.1.0
4
+ Summary: Linear continuous process maps of event logs as Plotly Sankey figures.
5
+ Project-URL: Homepage, https://github.com/aaronkurz/linear-continuous-process-mapper-marimo
6
+ Project-URL: Repository, https://github.com/aaronkurz/linear-continuous-process-mapper-marimo
7
+ Author: ICS University St. Gallen
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: event log,process map,process mining,sankey
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
14
+ Requires-Python: >=3.11
15
+ Requires-Dist: networkx>=3.2
16
+ Requires-Dist: pandas>=2.2
17
+ Requires-Dist: plotly>=5.20
18
+ Requires-Dist: pm4py>=2.7.11
19
+ Provides-Extra: notebook
20
+ Requires-Dist: kaleido>=1.0.0; extra == 'notebook'
21
+ Requires-Dist: marimo>=0.21.1; extra == 'notebook'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # LCM Marimo
25
+
26
+ # Linear Continuous Process Mapper
27
+
28
+ A prototypical implementation of linear and continuous process maps for the exploratory analysis of sequential behavior in event logs. This Python application builds upon interactive Sankey diagrams to provide effective visualizations of process behavior. The system loads event logs, constructs process maps using different abstractions (such as sequence-based, set-based, and last-activity-based), and visualizes them to display relevant insights in a precise yet interpretable way.
29
+
30
+ ## Overview
31
+ ![Annotated interface screenshot](resources/interface-screenshot-annotated.png)
32
+ UI of the application. Users choose an event log from the `logs/` folder via the event log selector (H), and can either analyze it as-is or apply further transformations by editing the marimo notebook. The UI supports folding activities (A) and activity selection (B). Furthermore, users can select from the three generic LCMs: sequence-, set-, or last-activity abstraction (C) and choose whether to visualize self-loops and empty traces (D). After selecting the desired visualization controls, they can refresh the visualization (E), which refreshes the Sankey diagram (F). Here, they can freely reposition nodes to adjust the visualization to their needs. More details about edges and nodes are revealed on hover (G). The current settings are also available as a `generate` call to copy into a notebook cell (I).
33
+
34
+ ## How to Run
35
+
36
+ This is the marimo version of the LCPM.
37
+
38
+ To get started:
39
+
40
+ ```
41
+ uv sync
42
+ ```
43
+
44
+ Then to run:
45
+ ```
46
+ uv run marimo run marimo_app.py
47
+ ```
48
+
49
+ Or to edit;
50
+ ```
51
+ uv run marimo edit marimo_app.py
52
+ ```
53
+
54
+ ### Event logs
55
+
56
+ Put event logs in the `logs/` folder and choose one from the **Event log** dropdown at the top of the app. Both `.xes` and `.csv` files are supported. A CSV needs these columns:
57
+
58
+ - `case:concept:name`: case ID
59
+ - `concept:name`: activity
60
+ - `time:timestamp`: timestamp
61
+
62
+ The included `logs/log.csv` is a preprocessed subset of **BPI Challenge 2020:
63
+ Domestic Declarations** by Boudewijn van Dongen (2020), Version 1,
64
+ 4TU.ResearchData.
65
+ Source: https://doi.org/10.4121/uuid:3f422315-ed9d-4882-891f-e180b5b4feb5
66
+
67
+ The subset contains 8,260 cases and 46,375 events; all included cases start
68
+ in 2018. It was converted from `DomesticDeclarations2H.xes` to CSV, retaining
69
+ only case ID, activity, and timestamp, with timestamps expressed in UTC.
70
+
71
+ This dataset is licensed under
72
+ [Creative Commons Attributionโ€“NonCommercial 4.0 International (CC BY-NC 4.0)](https://creativecommons.org/licenses/by-nc/4.0/).
73
+ Its reuse and redistribution are subject to that license, including its
74
+ attribution and noncommercial-use conditions. The repositoryโ€™s MIT license
75
+ applies to the code, not to this dataset.
76
+
77
+ ## Install
78
+
79
+ ```
80
+ pip install linear-continuous-process-mapper
81
+ ```
82
+
83
+ This installs the `lcm` library only. The interactive notebook needs the extra: `pip install "linear-continuous-process-mapper[notebook]"`.
84
+
85
+ ## Programmatic Use
86
+
87
+ The widgets in `marimo_app.py` are one way to call the `lcm` library. The same maps can be drawn from code, without any widgets. To fix a state you found interactively, copy the call from **Reproduce this map in code** below the map.
88
+
89
+ `programmatic_example.py` is a worked analysis of the included log in this style. It compares map types, folds activities, measures what each activity adds to a map, and transforms the log before mapping it. It has no widgets and is meant to be read with its code visible, so open it in edit mode:
90
+
91
+ ```
92
+ uv run marimo edit programmatic_example.py
93
+ ```
94
+
95
+ ```python
96
+ import lcm
97
+
98
+ lcm_service = lcm.get_service(lcm.load_event_log("logs/log.csv"))
99
+
100
+ figure, metadata = lcm_service.generate(
101
+ activities=None, # None keeps all of them; folded ones go by their fold name
102
+ map_type=lcm.MapType.SEQUENCE_BASED, # or "sequence_based"
103
+ allow_loops=True, # has no effect on sequence-based maps
104
+ visualize_empty_cases=True,
105
+ folds={"Rejections": ["Declaration REJECTED by ADMINISTRATION", "Declaration REJECTED by SUPERVISOR"]},
106
+ )
107
+ ```
108
+
109
+ All arguments are optional and invalid choices raise a `ValueError`. `figure` is a Plotly figure and `metadata` is a dict of counts. `generate` starts from the full log on every call, so one service can draw many maps. In a marimo notebook, every cell needs its own variable names:
110
+
111
+ ```python
112
+ # One cell
113
+ set_map, set_metadata = lcm_service.generate(map_type="set_based")
114
+ set_map
115
+ ```
116
+
117
+ ```python
118
+ # Another cell
119
+ last_activity_map, last_activity_metadata = lcm_service.generate(map_type="last_activity_based")
120
+ last_activity_map
121
+ ```
122
+
123
+ Display the figure directly. Wrapping it in `mo.ui.plotly()` leaves a blank plot, because that wrapper does not support Sankey traces.
124
+
125
+ ## Project Structure
126
+
127
+
128
+ **marimo_app.py** - The main entry point for running the application, via a marimo notebook. It is also the example of
129
+ interactive use of the library.
130
+
131
+ **programmatic_example.py** - An example analysis that uses the library from code, without widgets.
132
+
133
+ **lcm** - The library, independent of marimo. `lcm/__init__.py` wires together all components (data processors, graph
134
+ builders, analyzers) in `get_service`. It contains the main analytical components:
135
+
136
+ - **data** - Event log data handling using PM4Py. Loads XES and CSV files, orders each case's events by timestamp,
137
+ applies folds, filters by activities, and creates the variants for analysis
138
+ - **domain** - Graph analysis algorithms that enrich process graphs with business metrics including flow analysis,
139
+ leakage detection, termination ratios, and node balancing
140
+ - **graph_builders** - Multiple strategies for constructing process graphs from event data: set-based prefix graphs,
141
+ sequence-based prefix trees, and last-activity-based graphs with configurable loop handling
142
+ - **services** - High-level orchestration services that coordinate graph construction and the complete analytics
143
+ pipeline from raw data to visualizations
144
+ - **visualization** - Interactive Sankey diagram generator using Plotly that converts enriched process graphs into
145
+ color-coded flow visualizations with hover details and activity legends
146
+
147
+ **tests** - Tests of the library. Run them with `uv run pytest`.
148
+
149
+ ## Repository Authors
150
+ - [@moritzfaes](https://github.com/moritzfaes)
151
+ - [@hvoelzer](https://github.com/hvoelzer)
152
+ - [@aaronkurz](https://github.com/aaronkurz)
@@ -0,0 +1,129 @@
1
+ # LCM Marimo
2
+
3
+ # Linear Continuous Process Mapper
4
+
5
+ A prototypical implementation of linear and continuous process maps for the exploratory analysis of sequential behavior in event logs. This Python application builds upon interactive Sankey diagrams to provide effective visualizations of process behavior. The system loads event logs, constructs process maps using different abstractions (such as sequence-based, set-based, and last-activity-based), and visualizes them to display relevant insights in a precise yet interpretable way.
6
+
7
+ ## Overview
8
+ ![Annotated interface screenshot](resources/interface-screenshot-annotated.png)
9
+ UI of the application. Users choose an event log from the `logs/` folder via the event log selector (H), and can either analyze it as-is or apply further transformations by editing the marimo notebook. The UI supports folding activities (A) and activity selection (B). Furthermore, users can select from the three generic LCMs: sequence-, set-, or last-activity abstraction (C) and choose whether to visualize self-loops and empty traces (D). After selecting the desired visualization controls, they can refresh the visualization (E), which refreshes the Sankey diagram (F). Here, they can freely reposition nodes to adjust the visualization to their needs. More details about edges and nodes are revealed on hover (G). The current settings are also available as a `generate` call to copy into a notebook cell (I).
10
+
11
+ ## How to Run
12
+
13
+ This is the marimo version of the LCPM.
14
+
15
+ To get started:
16
+
17
+ ```
18
+ uv sync
19
+ ```
20
+
21
+ Then to run:
22
+ ```
23
+ uv run marimo run marimo_app.py
24
+ ```
25
+
26
+ Or to edit;
27
+ ```
28
+ uv run marimo edit marimo_app.py
29
+ ```
30
+
31
+ ### Event logs
32
+
33
+ Put event logs in the `logs/` folder and choose one from the **Event log** dropdown at the top of the app. Both `.xes` and `.csv` files are supported. A CSV needs these columns:
34
+
35
+ - `case:concept:name`: case ID
36
+ - `concept:name`: activity
37
+ - `time:timestamp`: timestamp
38
+
39
+ The included `logs/log.csv` is a preprocessed subset of **BPI Challenge 2020:
40
+ Domestic Declarations** by Boudewijn van Dongen (2020), Version 1,
41
+ 4TU.ResearchData.
42
+ Source: https://doi.org/10.4121/uuid:3f422315-ed9d-4882-891f-e180b5b4feb5
43
+
44
+ The subset contains 8,260 cases and 46,375 events; all included cases start
45
+ in 2018. It was converted from `DomesticDeclarations2H.xes` to CSV, retaining
46
+ only case ID, activity, and timestamp, with timestamps expressed in UTC.
47
+
48
+ This dataset is licensed under
49
+ [Creative Commons Attributionโ€“NonCommercial 4.0 International (CC BY-NC 4.0)](https://creativecommons.org/licenses/by-nc/4.0/).
50
+ Its reuse and redistribution are subject to that license, including its
51
+ attribution and noncommercial-use conditions. The repositoryโ€™s MIT license
52
+ applies to the code, not to this dataset.
53
+
54
+ ## Install
55
+
56
+ ```
57
+ pip install linear-continuous-process-mapper
58
+ ```
59
+
60
+ This installs the `lcm` library only. The interactive notebook needs the extra: `pip install "linear-continuous-process-mapper[notebook]"`.
61
+
62
+ ## Programmatic Use
63
+
64
+ The widgets in `marimo_app.py` are one way to call the `lcm` library. The same maps can be drawn from code, without any widgets. To fix a state you found interactively, copy the call from **Reproduce this map in code** below the map.
65
+
66
+ `programmatic_example.py` is a worked analysis of the included log in this style. It compares map types, folds activities, measures what each activity adds to a map, and transforms the log before mapping it. It has no widgets and is meant to be read with its code visible, so open it in edit mode:
67
+
68
+ ```
69
+ uv run marimo edit programmatic_example.py
70
+ ```
71
+
72
+ ```python
73
+ import lcm
74
+
75
+ lcm_service = lcm.get_service(lcm.load_event_log("logs/log.csv"))
76
+
77
+ figure, metadata = lcm_service.generate(
78
+ activities=None, # None keeps all of them; folded ones go by their fold name
79
+ map_type=lcm.MapType.SEQUENCE_BASED, # or "sequence_based"
80
+ allow_loops=True, # has no effect on sequence-based maps
81
+ visualize_empty_cases=True,
82
+ folds={"Rejections": ["Declaration REJECTED by ADMINISTRATION", "Declaration REJECTED by SUPERVISOR"]},
83
+ )
84
+ ```
85
+
86
+ All arguments are optional and invalid choices raise a `ValueError`. `figure` is a Plotly figure and `metadata` is a dict of counts. `generate` starts from the full log on every call, so one service can draw many maps. In a marimo notebook, every cell needs its own variable names:
87
+
88
+ ```python
89
+ # One cell
90
+ set_map, set_metadata = lcm_service.generate(map_type="set_based")
91
+ set_map
92
+ ```
93
+
94
+ ```python
95
+ # Another cell
96
+ last_activity_map, last_activity_metadata = lcm_service.generate(map_type="last_activity_based")
97
+ last_activity_map
98
+ ```
99
+
100
+ Display the figure directly. Wrapping it in `mo.ui.plotly()` leaves a blank plot, because that wrapper does not support Sankey traces.
101
+
102
+ ## Project Structure
103
+
104
+
105
+ **marimo_app.py** - The main entry point for running the application, via a marimo notebook. It is also the example of
106
+ interactive use of the library.
107
+
108
+ **programmatic_example.py** - An example analysis that uses the library from code, without widgets.
109
+
110
+ **lcm** - The library, independent of marimo. `lcm/__init__.py` wires together all components (data processors, graph
111
+ builders, analyzers) in `get_service`. It contains the main analytical components:
112
+
113
+ - **data** - Event log data handling using PM4Py. Loads XES and CSV files, orders each case's events by timestamp,
114
+ applies folds, filters by activities, and creates the variants for analysis
115
+ - **domain** - Graph analysis algorithms that enrich process graphs with business metrics including flow analysis,
116
+ leakage detection, termination ratios, and node balancing
117
+ - **graph_builders** - Multiple strategies for constructing process graphs from event data: set-based prefix graphs,
118
+ sequence-based prefix trees, and last-activity-based graphs with configurable loop handling
119
+ - **services** - High-level orchestration services that coordinate graph construction and the complete analytics
120
+ pipeline from raw data to visualizations
121
+ - **visualization** - Interactive Sankey diagram generator using Plotly that converts enriched process graphs into
122
+ color-coded flow visualizations with hover details and activity legends
123
+
124
+ **tests** - Tests of the library. Run them with `uv run pytest`.
125
+
126
+ ## Repository Authors
127
+ - [@moritzfaes](https://github.com/moritzfaes)
128
+ - [@hvoelzer](https://github.com/hvoelzer)
129
+ - [@aaronkurz](https://github.com/aaronkurz)
@@ -0,0 +1,44 @@
1
+ """Linear continuous process maps as Plotly Sankey figures.
2
+
3
+ lcm_service = lcm.get_service(lcm.load_event_log("logs/log.csv"))
4
+ figure, metadata = lcm_service.generate(map_type="sequence_based")
5
+ """
6
+
7
+ import pandas as pd
8
+
9
+ from lcm.constants import MapType
10
+ from lcm.data.data_loader import LOG_SUFFIXES, load_event_log
11
+ from lcm.data.data_processor import DataProcessor
12
+ from lcm.domain.graph_analyzer import GraphAnalyzer
13
+ from lcm.graph_builders import (
14
+ LastActivityBasedGraphBuilder,
15
+ SequenceBasedPrefixTreeBuilder,
16
+ SetBasedPrefixGraphBuilder,
17
+ )
18
+ from lcm.services.graph_service import GraphService
19
+ from lcm.services.process_analytics_service import ProcessAnalyticsService
20
+
21
+ __all__ = [
22
+ "LOG_SUFFIXES",
23
+ "MapType",
24
+ "ProcessAnalyticsService",
25
+ "get_service",
26
+ "load_event_log",
27
+ ]
28
+
29
+
30
+ def get_service(event_log: pd.DataFrame) -> ProcessAnalyticsService:
31
+ """Create a service for `event_log`; `generate` then draws maps from it."""
32
+ graph_service = GraphService(
33
+ {
34
+ MapType.SET_BASED: SetBasedPrefixGraphBuilder(),
35
+ MapType.SEQUENCE_BASED: SequenceBasedPrefixTreeBuilder(),
36
+ MapType.LAST_ACTIVITY_BASED: LastActivityBasedGraphBuilder(),
37
+ }
38
+ )
39
+ return ProcessAnalyticsService(
40
+ event_log=event_log,
41
+ data_processor=DataProcessor(),
42
+ graph_service=graph_service,
43
+ graph_analyzer=GraphAnalyzer(),
44
+ )
@@ -0,0 +1,13 @@
1
+ from enum import StrEnum
2
+
3
+ CASE_ID_COL = "case:concept:name"
4
+ ACTIVITY_COL = "concept:name"
5
+ TIMESTAMP_COL = "time:timestamp"
6
+ # Stands in for the activities of a case that has none of the selected ones.
7
+ EMPTY_TRACE = "EMPTY TRACE"
8
+
9
+
10
+ class MapType(StrEnum):
11
+ SET_BASED = "set_based"
12
+ SEQUENCE_BASED = "sequence_based"
13
+ LAST_ACTIVITY_BASED = "last_activity_based"
@@ -0,0 +1,49 @@
1
+ from pathlib import Path
2
+
3
+ import pm4py
4
+ import pandas as pd
5
+ from lcm.constants import TIMESTAMP_COL
6
+ from lcm.data.data_processor import check_columns
7
+ from lcm.logger_config import setup_logger
8
+
9
+ logger = setup_logger(__name__)
10
+
11
+ # File types the notebook's log picker offers and `load_event_log` accepts.
12
+ LOG_SUFFIXES = (".csv", ".xes")
13
+
14
+
15
+ def load_xes_log(file_path: str) -> pd.DataFrame:
16
+ try:
17
+ event_log = pm4py.read_xes(file_path, variant="rustxes")
18
+ return event_log
19
+ except Exception as e:
20
+ logger.error(f"Error loading event log from: {file_path}: {e}")
21
+ return None
22
+
23
+
24
+ def load_csv_log(file_path: str) -> pd.DataFrame:
25
+ event_log = pd.read_csv(file_path)
26
+ # Parsed here rather than via `parse_dates`, which would raise its own
27
+ # error before `load_event_log` can report the missing column.
28
+ if TIMESTAMP_COL in event_log.columns:
29
+ event_log[TIMESTAMP_COL] = pd.to_datetime(event_log[TIMESTAMP_COL])
30
+ return event_log
31
+
32
+
33
+ def load_event_log(file_path) -> pd.DataFrame:
34
+ """Load a .csv or .xes event log and check it has the columns we need."""
35
+ path = Path(file_path)
36
+ suffix = path.suffix.lower()
37
+ if suffix == ".csv":
38
+ event_log = load_csv_log(str(path))
39
+ elif suffix == ".xes":
40
+ event_log = load_xes_log(str(path))
41
+ if event_log is None:
42
+ raise ValueError(f"Could not read XES log '{path.name}'.")
43
+ else:
44
+ raise ValueError(
45
+ f"Unsupported log type '{suffix}'; expected one of {', '.join(LOG_SUFFIXES)}."
46
+ )
47
+
48
+ check_columns(event_log, f"'{path.name}'")
49
+ return event_log
@@ -0,0 +1,52 @@
1
+ import pandas as pd
2
+ from typing import Dict, List, Tuple
3
+ from lcm.constants import CASE_ID_COL, ACTIVITY_COL, TIMESTAMP_COL, EMPTY_TRACE
4
+
5
+
6
+ def check_columns(event_log: pd.DataFrame, source: str = "The event log") -> None:
7
+ """Raise a ValueError if `event_log` lacks a column the maps need."""
8
+ missing = [
9
+ col
10
+ for col in (CASE_ID_COL, ACTIVITY_COL, TIMESTAMP_COL)
11
+ if col not in event_log.columns
12
+ ]
13
+ if missing:
14
+ raise ValueError(f"{source} is missing column(s): {', '.join(missing)}.")
15
+
16
+
17
+ class DataProcessor:
18
+ """Handles all data transformation and preparation logic."""
19
+
20
+ def prepare_traces(self, event_log: pd.DataFrame) -> List[List[str]]:
21
+ """Return the activities of each case in timestamp order."""
22
+ check_columns(event_log)
23
+ events = event_log.dropna(subset=[ACTIVITY_COL]).sort_values(
24
+ TIMESTAMP_COL, kind="stable"
25
+ )
26
+ return events.groupby(CASE_ID_COL)[ACTIVITY_COL].agg(list).tolist()
27
+
28
+ def apply_folds(
29
+ self, traces: List[List[str]], folds: Dict[str, List[str]]
30
+ ) -> List[List[str]]:
31
+ """Rename every folded activity to its fold name."""
32
+ if not folds:
33
+ return traces
34
+ mapping = {act: name for name, members in folds.items() for act in members}
35
+ return [[mapping.get(act, act) for act in trace] for trace in traces]
36
+
37
+ def create_variants(
38
+ self,
39
+ traces: List[List[str]],
40
+ selected_activities: List[str],
41
+ visualize_empty_cases: bool,
42
+ ) -> Tuple[List[List[str]], int]:
43
+ """Reduce traces to the selected activities; also count the emptied ones."""
44
+ selected = set(selected_activities)
45
+ filtered = [[act for act in trace if act in selected] for trace in traces]
46
+ variants = [trace for trace in filtered if trace]
47
+ empty_cases = len(filtered) - len(variants)
48
+
49
+ if visualize_empty_cases:
50
+ variants += [[EMPTY_TRACE] for _ in range(empty_cases)]
51
+
52
+ return variants, empty_cases
@@ -0,0 +1,43 @@
1
+ import networkx as nx
2
+
3
+
4
+ class GraphAnalyzer:
5
+ """Enriches graphs with domain-specific metrics (leakage, termination, etc.)."""
6
+
7
+ def enrich_graph_with_metrics(
8
+ self, G: nx.MultiDiGraph, knockout_threshold: float = 0.5
9
+ ) -> nx.MultiDiGraph:
10
+ leakage_gt_0_count = 0
11
+ terminal_count = 0
12
+ G_enriched = G.copy()
13
+ for node in G_enriched.nodes():
14
+ incoming_weight = sum(
15
+ G_enriched.edges[pred, node, key]["weight"]
16
+ for pred in G_enriched.predecessors(node)
17
+ for key in G_enriched[pred][node]
18
+ )
19
+ outgoing_weight = sum(
20
+ G_enriched.edges[node, succ, key]["weight"]
21
+ for succ in G_enriched.successors(node)
22
+ for key in G_enriched[node][succ]
23
+ )
24
+ weight = G_enriched.nodes[node].get("weight", 0)
25
+ leakage = incoming_weight - outgoing_weight
26
+ terminated_cases = weight - outgoing_weight
27
+ termination_ratio = terminated_cases / weight if weight > 0 else 0
28
+
29
+ G_enriched.nodes[node]["metrics"] = {
30
+ "incoming_flow": incoming_weight,
31
+ "outgoing_flow": outgoing_weight,
32
+ "leakage": leakage,
33
+ "termination_ratio": termination_ratio,
34
+ "is_balanced": incoming_weight == outgoing_weight,
35
+ "is_terminal": termination_ratio >= knockout_threshold,
36
+ }
37
+ if leakage > 0:
38
+ leakage_gt_0_count += 1
39
+ if termination_ratio >= knockout_threshold:
40
+ terminal_count += 1
41
+ G_enriched.graph["leakage_gt_0_count"] = leakage_gt_0_count
42
+ G_enriched.graph["terminal_count"] = terminal_count
43
+ return G_enriched
@@ -0,0 +1,4 @@
1
+ from .set_based import SetBasedPrefixGraphBuilder
2
+ from .last_activity_based import LastActivityBasedGraphBuilder
3
+ from .sequence_based import SequenceBasedPrefixTreeBuilder
4
+ from .abstract_graph_builder import AbstractGraphBuilder
@@ -0,0 +1,18 @@
1
+ import networkx as nx
2
+ from abc import ABC, abstractmethod
3
+ from typing import List
4
+
5
+
6
+ class AbstractGraphBuilder(ABC):
7
+ """Abstract base class for all graph builder"""
8
+
9
+ @abstractmethod
10
+ def build(
11
+ self, variants: List[List[str]], allow_loops: bool = True
12
+ ) -> nx.MultiDiGraph:
13
+ pass
14
+
15
+ @property
16
+ @abstractmethod
17
+ def name(self) -> str:
18
+ """User friendly name for the builder strategy"""