Metadata-Version: 2.4
Name: pm4py-ucm
Version: 0.9.1
Summary: Use Case Map (URN/UCM) extension for PM4Py — process mining → jUCMNav
Author: pm4py-ucm contributors
License: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/ProcessMining-uOttawa/pm4py-ucm
Project-URL: Documentation, https://processmining-uottawa.github.io/pm4py-ucm/
Project-URL: Issues, https://github.com/ProcessMining-uOttawa/pm4py-ucm/issues
Project-URL: Changelog, https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/CHANGELOG.md
Keywords: process-mining,pm4py,use-case-maps,ucm,urn,jucmnav,requirements-engineering
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: graphviz>=0.20
Requires-Dist: Pillow>=10.0
Requires-Dist: scikit-learn>=1.3
Provides-Extra: pm4py
Requires-Dist: pm4py>=2.7; extra == "pm4py"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.5; extra == "viz"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pm4py>=2.7; extra == "dev"
Requires-Dist: matplotlib>=3.5; extra == "dev"
Requires-Dist: bandit>=1.7; extra == "dev"
Requires-Dist: lxml>=4.9; extra == "dev"
Provides-Extra: docs
Requires-Dist: pdoc>=14; extra == "docs"
Dynamic: license-file

<p align="center">
  <img src="https://raw.githubusercontent.com/ProcessMining-uOttawa/pm4py-ucm/main/web/assets/logo.png" alt="PM4Py-UCM — Process Mining with Use Case Maps" width="380">
</p>

<h1 align="center">pm4py-ucm</h1>

[![tests](https://github.com/ProcessMining-uOttawa/pm4py-ucm/actions/workflows/tests.yml/badge.svg)](https://github.com/ProcessMining-uOttawa/pm4py-ucm/actions/workflows/tests.yml)
[![docs](https://github.com/ProcessMining-uOttawa/pm4py-ucm/actions/workflows/docs.yml/badge.svg)](https://processmining-uottawa.github.io/pm4py-ucm/)
[![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-blue)](https://www.python.org/)
[![License: GPL v3+](https://img.shields.io/badge/license-GPLv3%2B-blue.svg)](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/LICENSE)
[![Streamlit V6](https://img.shields.io/badge/Streamlit-V6%20workspace-FF4B4B?logo=streamlit&logoColor=white)](https://pm4py-ucm.streamlit.app/)

**Use Case Map (UCM) extension for [PM4Py](https://github.com/process-intelligence-solutions/pm4py).**

`pm4py-ucm` adds first-class support for the [Use Case Map][ucm-wiki]
modelling notation — part of the ITU-T Z.151 *User Requirements Notation*
(URN) standard, supported by the open-source [jUCMNav][jucmnav] tool — to
PM4Py-style process-mining workflows.

The package is structured as a **drop-in companion** to PM4Py's existing
BPMN support: every public helper has the same shape (`read_*`, `write_*`,
`discover_*_inductive`, `view_*`, `convert_to_*`) so adopting UCM as an
additional output of process mining is a one-word change in user code.

```python
import pm4py
import pm4py_ucm

log = pm4py.read_xes("running-example.xes")
ucm = pm4py_ucm.discover_ucm_inductive(log)
pm4py_ucm.view_ucm(ucm)
pm4py_ucm.write_ucm(ucm, "running-example.jucm")  # opens in jUCMNav
pm4py_ucm.write_bpmn(ucm, "running-example.bpmn")  # opens in bpmn.io, Camunda
```

**Ways to get started:**

- **The web app**, hosted at https://pm4py-ucm.streamlit.app/ — click, don't code: upload an XES/CSV log, tune the miner, download the result. See [Web front-end](#web-front-end).
- **Five Jupyter tutorials** in [`demo/`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/README.md), on two sample logs shipped with the repository:
  - [`pm4py_ucm_tutorial.ipynb`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/pm4py_ucm_tutorial.ipynb) — discovery, UCM/BPMN rendering, `.jucm`/`.png`/`.svg` and BPMN 2.0 export, performer mining, hierarchical decomposition, `.jucm` round-trips.
  - [`scenario_synthesis_tutorial.ipynb`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/scenario_synthesis_tutorial.ipynb) — concurrency-aware variants, loop counters, and both OR-fork condition encodings (variant-driven and data-driven).
  - [`model_families_tutorial.ipynb`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/model_families_tutorial.ipynb) — one model per attribute value, the dynamic-stub umbrella, performance overlays and heat-map, pairwise comparison, the family statistics report.
  - [`dashboards_tutorial.ipynb`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/dashboards_tutorial.ipynb) — the fact table, metric catalog, widgets, targets and scorecard, the ƒ formula language, suggested dashboards, the HTML export.
  - [`sessions_tutorial.ipynb`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/sessions_tutorial.ipynb) — saving, sharing and resuming a web-app project.
- **[API reference](https://processmining-uottawa.github.io/pm4py-ucm/)** — every public helper and module, generated from the docstrings.
- **[`docs/`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/README.md)** — the narrative documents: metric definitions, design notes, measurements.
- The rest of this README — a tour of the public API.

[ucm-wiki]: https://en.wikipedia.org/wiki/Use_Case_Maps
[jucmnav]: https://github.com/JUCMNAV/projetseg-update

## Web front-end

The [Streamlit](https://streamlit.io) front-end is the **V6** app
([`web/streamlit_app_v6.py`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/web/streamlit_app_v6.py)),
deployed at **https://pm4py-ucm.streamlit.app/**: a left-rail workspace over
the views below, with a global **log filter** and **activity renaming**
applied before mining across every view, and a **cost screen** that sizes a
log before the miner is started. The full walkthrough is in
[`web/README.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/web/README.md).

- **Model** — upload an event log (XES or CSV), tune the inductive
  miner / decomposition / performer settings interactively, optionally
  **filter the log** (range sliders over activity- and variant-frequency
  ranks, an exclude list, a date range, a **cycle-time percentile** band
  that keeps the fastest or slowest cases by end-to-end duration, and an
  **attribute filter** written in the ƒ metric language — e.g.
  `attr("Channel") == "Web" and duration() > 5`) and **rename or merge
  activities**
  before mining, preview the diagram in UCM or BPMN notation, and download
  the rendered PNG, the `.jucm` file, a standard **BPMN 2.0** file, or the
  **filtered log itself** as XES/CSV. The filter and rename are global — every view below (and its
  exports) mines the same transformed log.

  ![Model view](https://raw.githubusercontent.com/ProcessMining-uOttawa/pm4py-ucm/main/web/PM4Py-UCM-Model.png)

- **Scenarios** — concurrency-aware variant clustering + one
  executable jUCMNav `ScenarioDef` per variant. Both variant-driven
  and data-driven OR-fork encodings are exposed; the view surfaces
  headline metrics (variant count, sequence variants, compression
  ratio, fitness %, per-fork condition-mining accuracies) and, behind a
  single **Prepare downloads** button, offers four downloads: the `.jucm`
  with the synthesized scenario group, `variants.csv`,
  `case_variant_map.csv`, and (data-driven mode) `condition_mining.csv`.
  Runs on flat and decomposed UCMs alike.

  ![Scenarios view](https://raw.githubusercontent.com/ProcessMining-uOttawa/pm4py-ucm/main/web/PM4Py-UCM-Scenarios.png)

  A **Simulation** section at the bottom then *runs* those scenarios the way
  jUCMNav does and colours the model with what they walked — either the
  **coverage** of any subset, or an **A vs B** comparison of two — with every
  element hoverable. The choice is saved with the project and reproduced by an
  exported script.

  ![Scenario execution](https://raw.githubusercontent.com/ProcessMining-uOttawa/pm4py-ucm/main/web/PM4Py-UCM-Simulation.png)

- **Family** — a **deterministic advisor** ranks the case attributes by
  discriminative power (which one yields genuinely different processes), then
  pick 1–2 (with per-value filters and a pre-mining coverage heatmap) and mine
  one model per combination. A
  single **Prepare downloads** button then builds the per-cell zip, the
  combined `.jucm`, the dynamic-stub umbrella `.jucm`, the grid PNG, and
  the interactive HTML statistics report — download-only artifacts built
  on request, so browsing the grid stays fast.

  ![Family view](https://raw.githubusercontent.com/ProcessMining-uOttawa/pm4py-ucm/main/web/PM4Py-UCM-Family.png)

- **Compare** — rank the family members on a heat-mapped statistics
  table and compare any two side by side (models, activity/edge
  deltas, aligned choice shares).

  ![Compare view](https://raw.githubusercontent.com/ProcessMining-uOttawa/pm4py-ucm/main/web/PM4Py-UCM-Compare.png)

- **Dashboards** — build widgets from a metric catalog over the same
  filtered/renamed log: filters (including a date range), segmentation,
  targets with a **scorecard** that drills into the segments that breached
  them, and a **ƒ custom-formula language**. A widget is drawn as a KPI,
  gauge, histogram, box plot, bar, line, pie/donut or heatmap table —
  whichever the metric and segmentation support — and the grid is
  drag-reordered and drag-resized. An **Activity** axis puts every activity
  on one bar chart or heatmap, and the log's concurrency-aware
  **behavioural variants** are a segment axis and filter like any case
  attribute. **✦ Suggest** proposes whole dashboards from the log itself —
  its bottlenecks, rework, decision points and the attributes that split
  its cases — each widget with the number that justifies it. A log can hold
  several named dashboards, exported one at a time or all in one
  self-contained interactive HTML file. See
  [`docs/dashboards.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/dashboards.md) and
  [`docs/dashboard_suggestions.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/dashboard_suggestions.md).

  ![Dashboards view](https://raw.githubusercontent.com/ProcessMining-uOttawa/pm4py-ucm/main/web/PM4Py-UCM-Dashboard.png)

A **Performance overlay** sidebar section puts frequencies and times on
activities and edges in every view's outputs, with an optional **heat-map**
that colours and thickens them by value. Its default counts are
**replay-based**: they measure how often the log walks each part of the
model, so the numbers **conserve** — an activity's count matches the count
on its own edges, parallel branches all carry their fork's inflow, and a
choice's branches sum to it. (Event counts and directly-follows counts,
still available, measure different things and disagree with each other
wherever the model has concurrency or a silently skipped branch.) The view
reports how much of the log the model explains alongside them. See
[Performance overlays](#performance-overlays) and
[`docs/metrics.md` §9](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/metrics.md).

**Save, share & resume.** A configured session — log reference, CSV
mapping, renaming, filters, performers, overlays, decomposition, family and
scenario settings, the open view and your dashboards — round-trips through a
project file: a small **settings file** (`.ucmproj.json`, configuration
only, no event data) or a self-contained **project bundle** (`.ucmproj.zip`,
configuration + the log). Only *inputs* are stored; the model, scenarios,
family and reports recompute on load. See
[`docs/sessions.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/sessions.md).

**Export the analysis as runnable Python.** The same **Project** group emits
the session as a plain-Python **script** (`.py`, with a CLI entry point) and
a **Jupyter notebook** (`.ipynb`) that reproduce it over the public
`pm4py_ucm` API — log loading, rename and filters, mining, decomposition,
performers, overlays, and optionally the scenario, family and dashboard
pipelines. It is a deterministic template emitter, no LLM involved: a way to
graduate a GUI exploration into a version-controllable pipeline. See
[`docs/code_export.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/code_export.md).

Run locally, from a checkout, with:

```bash
pip install -r web/requirements.txt
streamlit run web/streamlit_app_v6.py
```

**Every app older than V6 is deprecated.** `web/streamlit_app.py`, the
deployment's main file, is a shim that runs V6. The older apps are kept
runnable so earlier results stay reproducible, and each says so when it
starts, but they receive no new features — including settings added to the
session registry, which they save but do not restore.

| App | File | Status |
|---|---|---|
| **V6** | [`streamlit_app_v6.py`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/web/streamlit_app_v6.py) | **Current.** Deployed at https://pm4py-ucm.streamlit.app/ |
| V5 | [`streamlit_app_v5.py`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/web/streamlit_app_v5.py) | Deprecated — workspace shell + Dashboards, no cost screen, no Simulation |
| V3 | [`streamlit_app_v3.py`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/web/streamlit_app_v3.py) | Deprecated — the earlier four-tab app |
| V2 | [`streamlit_app_v2.py`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/web/streamlit_app_v2.py) | Deprecated — model + scenarios only |
| V4, V1 | — | Removed; they live in git history |

## Why UCM alongside BPMN?

BPMN is excellent for procedural choreographies, but it forces a single
abstraction level: every flow object is a step in *the* process. UCM, by
contrast, is a *scenario* notation. Its elements (path nodes — start
points, responsibilities, OR/AND forks and joins, stubs, timers, …) are
laid over a backdrop of **components**, which lets a single map describe a
behaviour that crosses architectural boundaries. This makes UCM a natural
target when the discovered process tree describes a workflow that spans
multiple services or organisational units, or when the goal is requirements
engineering rather than execution. See ITU-T Recommendation Z.151 for the
full notation reference.

## Installation

```bash
pip install "pm4py-ucm[pm4py]"  # recommended: core package + pm4py, needed for discovery
pip install pm4py-ucm           # core package + graphviz Python bindings, without pm4py
pip install "pm4py-ucm[viz]"    # add matplotlib for inline notebook display
pip install "pm4py-ucm[dev]"    # everything for development (pytest, pm4py, matplotlib, bandit, lxml)
```

Python 3.10 or later is required.

`pm4py` is an optional extra rather than a hard dependency, so the core
install gives you the UCM object model, the layout engine and the jUCMNav
and BPMN exporters, but `discover_ucm_inductive()`, `discover_scenarios()`
and the other discovery entry points raise `ImportError` without it.
Install the `[pm4py]` extra unless you are only building or reading models
by hand. The core package also installs `Pillow` (multi-map images) and
`scikit-learn` (the data-driven scenario conditions).

From a local checkout, the same extras work with an editable install:

```bash
pip install -e ".[dev]"
```

The graphviz **system binary** must be on `PATH` for rendering (the
`graphviz` Python wheel only provides bindings):

```bash
# Debian / Ubuntu
sudo apt-get install graphviz
# macOS
brew install graphviz
# Windows
choco install graphviz
```

## Quick tour

### Build a UCM by hand

```python
from pm4py_ucm import UCM, write_ucm

ucm = UCM(name="OnlineShop")
m = ucm.add_map(name="ShoppingFlow")

start = m.add_node(UCM.StartPoint(name="start"))
login = m.add_node(UCM.RespRef(resp_def=ucm.get_or_add_responsibility("Login")))
fork  = m.add_node(UCM.OrFork(name="choose"))
search = m.add_node(UCM.RespRef(resp_def=ucm.get_or_add_responsibility("Search")))
browse = m.add_node(UCM.RespRef(resp_def=ucm.get_or_add_responsibility("Browse")))
join   = m.add_node(UCM.OrJoin())
checkout = m.add_node(UCM.RespRef(resp_def=ucm.get_or_add_responsibility("Checkout")))
end    = m.add_node(UCM.EndPoint(name="end"))

m.add_connection(start, login)
m.add_connection(login, fork)
m.add_connection(fork, search, condition="search")    # label on the OR branch
m.add_connection(fork, browse, condition="browse")    # label on the OR branch
m.add_connection(search, join)
m.add_connection(browse, join)
m.add_connection(join, checkout)
m.add_connection(checkout, end)

write_ucm(ucm, "online_shop.jucm")  # open in jUCMNav
```

### Mine a UCM from an event log

```python
import pm4py
import pm4py_ucm

log = pm4py.read_xes("log.xes")
ucm = pm4py_ucm.discover_ucm_inductive(log)
pm4py_ucm.view_ucm(ucm)                                # UCM notation
pm4py_ucm.save_vis_ucm(ucm, "diagram_ucm.png")         # UCM notation
pm4py_ucm.save_vis_ucm(ucm, "diagram_bpmn.png",        # BPMN notation
                       style="bpmn")
pm4py_ucm.write_ucm(ucm, "log.jucm")
```

`discover_ucm_inductive` is a thin wrapper around
`pm4py.discover_process_tree_inductive` followed by the bundled
process-tree → UCM converter. PM4Py's own tuning parameters for the
inductive miner are forwarded through a **`discovery_parameters`** entry in
the `parameters` dict — most usefully `noise_threshold`, which trades model
detail against how much of the log the model can reproduce:

```python
ucm = pm4py_ucm.discover_ucm_inductive(
    log,
    parameters={"discovery_parameters": {"noise_threshold": 0.2}},
)
```

`noise_threshold` defaults to PM4Py's `0.0`, which keeps everything: on a
noisy log that is a busier model that fits every case. Raising it filters
infrequent behaviour out of the model (the web app starts at `0.2`). The
same entry carries `activity_key` / `timestamp_key` / `case_id_key` for logs
whose columns are not XES-named. A tree you mined yourself can be passed
instead as `parameters={"process_tree": tree}`.

`save_vis_ucm` picks the format from the file extension: `.png`, or `.svg`
for a navigable vector drawing (stubs link to their plug-in maps, elements
carry hover text). Both support two visual styles:

* **`style="ucm"` (default)** — Z.151 / jUCMNav notation: filled circle
  for the start point, perpendicular bar for the end point, `×` glyph
  with the responsibility name underneath, thick perpendicular bar for
  AND-fork / AND-join (synchronisation bars), small filled dot for
  OR-fork / OR-join, diamond reserved for stubs.
* **`style="bpmn"`** — BPMN-friendly look: activity boxes for
  responsibilities, gateway diamonds with `X` / `+` markers for
  XOR / AND gateways, thin-border start circle and thick-border end
  circle (the canonical BPMN end event).

Both styles preserve the swim-lane layout (one rectangle per
component, never overlapping unless nested) and wrap long
responsibility names onto two or three lines so the diagram stays
compact.

### `.jucm` layout matches the PNG layout

When writing a `.jucm` file, pm4py-ucm uses graphviz's `dot` engine to
compute the coordinates — exactly the same engine that drives the PNG
renderer. Open the resulting file in jUCMNav and you'll see the same
arrangement of nodes and component rectangles as in the rendered PNG.

If the graphviz binary isn't on `PATH`, the exporter falls back
silently to the bundled Sugiyama-style layouter so writing still
works; the visual result will be a layered drawing rather than a
graphviz one. Force the built-in layouter explicitly with:

```python
pm4py_ucm.write_ucm(ucm, "log.jucm",
                    parameters={"layout_engine": "builtin"})
```

### Export to standard BPMN 2.0

`write_bpmn` writes the same model as a BPMN 2.0 XML file with diagram
interchange, so it opens in bpmn.io, Camunda Modeler, Signavio or
`pm4py.read_bpmn`, laid out like the `style="bpmn"` preview:

```python
pm4py_ucm.write_bpmn(ucm, "log.bpmn")
xml = pm4py_ucm.convert_to_bpmn_xml(ucm)      # the same, as a string
```

The whole UCM is **one pool whose lanes are the components** (nested
components nest as child lanes); responsibilities become tasks, OR/AND forks
and joins exclusive/parallel gateways, routing bends waypoints. A **static
stub is a call activity** to the plug-in's own process (every map is a
process with its own diagram), and a **dynamic stub a collapsed sub-process**
that chooses *inclusively* among its plug-ins, guarded by the binding
preconditions — Z.151 semantics. Node centres transfer 1:1 from the UCM
coordinates, and performance metadata travels as `<ucm:metric>` extension
elements on tasks and flows. Keyword options adjust the output:

| Option | Effect |
|---|---|
| `annotate="edges"` (default) / `"all"` / `"none"` | The selected edge overlay text becomes the flow's label; `"all"` adds text annotations under tasks; `"none"` keeps the file plain. |
| `heatmap_node="frequency"`, `heatmap_edge="mean_time"` | Colour tasks and flows with the PNG heat-map's ramps (readable by bpmn.io and Camunda). |
| `sizes="canonical"` | Standard BPMN shape sizes, with the layout scaled to fit them. |
| `stubs="inline"` | Nest plug-ins as collapsed sub-processes instead of call activities. `pm4py.read_bpmn` needs this, and bpmn.io can drill into a sub-process but not follow a call activity — so the web app's downloads use it. |
| `routing="orthogonal"` | Elbowed flows. |
| `data="objects"` | Scenario variables as data objects. |
| `lanes="none"`, `lane_names="with_kind"`, `metrics="none"`, `validate=False` | Drop the lanes, add the component kind to lane names, omit the metric extensions, skip the structural check. |

`write_bpmn_family(family, "family.zip", assembled=umbrella)` writes one
`.bpmn` per cell plus the assembled family. The mapping, its decisions and
its limits are in
[`docs/bpmn_export.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/bpmn_export.md).

### Mine performers too — surface them as URN components

If the log records who performed each activity (typically the
`org:resource` or `org:role` event attribute), pm4py-ucm mines the
activity→performer mapping and uses it to populate URN components
automatically: each unique performer becomes a `ComponentElement`, each
`Responsibility` is linked to its performer, and on every map the
`RespRef` symbol for that activity is drawn inside the component's
rectangle.

This is **on by default**: `discover_ucm_inductive` looks for
`org:resource`, then `org:role`, then `org:group`, and does nothing when the
log has none of them. Choose the attribute, or switch it off, through
`resource_attribute`:

```python
import pm4py
import pm4py_ucm

log = pm4py.read_xes("log.xes")

# One-shot: mine + bind in a single call, preferring roles over individuals.
ucm = pm4py_ucm.discover_ucm_inductive(log, parameters={
    "resource_attribute": ["org:role", "org:resource"],  # priority list
})

# Or, the explicit three-step flow with more control.
performers = pm4py_ucm.discover_resources(
    log,
    attribute_priority=["org:role", "org:resource"],
    strategy="mode",        # or "first", "all", "unbound"
    min_support=0.0,        # default — pick the modal performer
                            # even when no single one owns a majority
)
ucm = pm4py_ucm.discover_ucm_inductive(
    log, parameters={"resource_attribute": False})   # no automatic mining
pm4py_ucm.bind_performers(ucm, performers)

pm4py_ucm.write_ucm(ucm, "log.jucm")
```

#### Component discovery vs activity binding

There are two related questions to answer when mining resources:

* **Which activities have a clearly-identified performer?** This is what
  `discover_resources` answers — it returns one performer per activity
  using the configured aggregation strategy (`mode` by default). An
  activity with many performers spread roughly equally gets bound to
  the modal one; an activity with no `org:resource` annotation at all
  is omitted.
* **Which actors exist in the log?** This is what `discover_components`
  answers — it returns the full *vocabulary* of every distinct
  performer value that appears anywhere in the log, sorted. The
  high-level `discover_ucm_inductive` calls both, so every distinct
  actor becomes a URN `ComponentElement` even when no single
  responsibility is cleanly bound to it. The unbound components show
  up in the URN tree but not as rectangles on the map.

This matters for logs with a dispersed resource pool — e.g. the BPI
Road Traffic Fines log has 148 distinct `org:resource` values where the
modal performer of *Create Fine* owns only 5.7% of events. Without these
two adjustments (modal binding without majority support, and full
component-vocabulary discovery), only one of the 148 actors would
appear in the resulting URN spec.

In the rendered diagram and the exported `.jucm`, each activity now
appears inside the rectangle of the team that owns it. See
[Definitions vs references](#definitions-vs-references) below for the
data-model story.

### Read an existing jUCMNav file

```python
from pm4py_ucm import read_ucm

ucm = read_ucm("requirements.jucm")
print(ucm)                          # → UCM(name='…', maps=…, responsibilities=…)
for n in ucm.maps[0].nodes:
    print(n)
```

### Screen what a log will cost before mining it

On a log with a large alphabet or near-unique cases the inductive miner can
run for minutes, or not finish at all — one 543k-event log with 274
activities did not complete in 900s. `pm4py_ucm.algo.complexity` answers
"is this worth starting?" in a single pass, before any mining:

```python
import pandas as pd
from pm4py_ucm.algo import complexity

profile = complexity.profile_log(df)          # one pass, no mining
print(profile.as_dict())
# {'events': 543283, 'cases': 7734, 'activities': 274,
#  'seq_variants': 7665, ..., 'variant_ratio': 0.9911}

risk = complexity.screen_mining(profile)
if risk.high:
    print(risk.reason)                        # a reason, not an ETA
    print(risk.triggers)                      # what tripped it
```

`variant_ratio` is the tell: distinct sequences per case, approaching `1.0`
when almost every case is unique, which is the shape that makes the miner's
fall-through search expensive.

**The verdict is deliberately a reason, not a duration.** The statistics
that rank logs correctly cannot time them, so `MiningRisk` carries no
prediction. Replay is different — it is close to linear in cases, so it
*can* be measured, with a time-boxed probe that extrapolates:

```python
est = complexity.estimate_replay(df, tree, time_budget=5.0)
if est.complete:
    clustering = est.clustering       # the probe finished; nothing left to run
else:
    print(f"about {est.estimated_total_s:.0f}s for {est.total_cases:,} cases")
    print(f"{est.noise_rate:.0%} of sampled cases did not fit the model")
```

Across twelve logs the extrapolation landed within 0.79×–1.39× of the real
time. The measurements behind all of this — including why no miner setting
is a fast path — are in [`docs/miner_performance.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/miner_performance.md).

**The remedy is reducing the log, not a faster miner.** On logs like these,
`disable_fallthroughs=True` and PM4Py's DFG-based IMd return structurally
identical flower models — every activity, no control flow — which leaves
nothing to cluster or synthesize scenarios from. Keeping the most frequent
variants or the most frequent activities is what actually helps.

## Process-tree → UCM mapping

The converter implements the following correspondences between PM4Py's
process tree operators and UCM constructs. UCM has no native loop, so loops
are encoded as an OR-fork/OR-join pair guarded by `[redo]` / `[exit]`
conditions — the canonical idiom in jUCMNav.

| Process tree                            | UCM construct                                                                 |
|-----------------------------------------|-------------------------------------------------------------------------------|
| Activity leaf with label `A`            | `RespRef` referencing a `Responsibility` named `A`                            |
| Silent (τ) leaf                         | A direct `NodeConnection` with no responsibility                              |
| `→ (sequence)` of children              | Children chained with `EmptyPoint` connectors (collapsed by simplifier)        |
| `× (xor)` choice                        | `OrFork` → branches → `OrJoin`                                                |
| `+ (parallel)`                          | `AndFork` → branches → `AndJoin`                                              |
| `o (interleaving)`                      | Treated as `+ (parallel)`                                                     |
| `∨ (or)`                                | Treated as `× (xor)`                                                          |
| `↻ (loop, do, redo)`                    | `OrJoin` → *do* → `OrFork` with `[redo]` back-edge and `[exit]` forward edge   |

After conversion, an `EmptyPoint` simplification pass collapses chains of
unnamed degree-2 connectors so that the resulting map renders compactly.

## Hierarchical decomposition

For complex process trees, a single flat UCM map quickly becomes visually
overwhelming. The optional `decomposition=` keyword splits the result into a
**root map plus plug-in (sub-)maps connected by Stubs**. Four public entry
points take it, and all four interpret it identically:
`discover_ucm_inductive`, `convert_to_ucm`, `discover_scenarios` and
`discover_ucm_family`. The same
`PluginBinding` machinery the package already uses for hand-built models
ties everything together — every round-trip stays byte-stable through the
exporter and importer.

```python
import pm4py
import pm4py_ucm

log = pm4py.read_xes("running-example.xes")

# Default: one flat map
flat = pm4py_ucm.discover_ucm_inductive(log)
assert len(flat.maps) == 1

# Hierarchical: a root map + one plug-in per "phase" / branch / loop body
hier = pm4py_ucm.discover_ucm_inductive(log, decomposition="auto")
assert len(hier.maps) >= 1

pm4py_ucm.view_ucm(hier)                          # all maps stacked in one PNG
pm4py_ucm.view_ucm(hier, map=hier.maps[1].name)   # just one plug-in, by map name
pm4py_ucm.write_ucm(hier, "out.jucm")             # opens in jUCMNav as root+plug-ins
```

The `decomposition` argument accepts:

| Value          | Effect                                                                                 |
|----------------|----------------------------------------------------------------------------------------|
| `None` / `"off"` | No decomposition. Output byte-stable with pre-decomposition exports.                |
| `"auto"`       | All four boundary rules on; `max_leaves_per_map` and `min_leaves_to_decompose` **fitted to the tree shape** at conversion time — see `suggest_decomposition`. |
| `"aggressive"` | Fixed preset: same boundary rules, `max_leaves_per_map=10`.                            |
| `dict`         | Any subset of the keys below; unspecified keys take the fixed defaults in that table. A size dimension may be the string `"auto"` to fit just that one to the shape. |

Anything else — another string, another type — raises `ValueError`.

`pm4py_ucm.suggest_decomposition(tree)` returns the shape-fitted dict
directly if you want to inspect or tweak it. It scales the two size knobs
with the tree's activity-leaf count `N` rather than fixing magic numbers:

- `max_leaves_per_map = clamp(round(k·√N), 6, 40)` — **sub-linear**, so a big
  tree does not simply get proportionally more maps. `k` is 1.5 by default
  and 1.0 for `level="fine"`, which is the only other level.
- `min_leaves_to_decompose = clamp(round(0.15·N), 3, 12)`, and never above
  `max_leaves_per_map - 1`. This floor, not the cap, is what actually
  controls fragmentation: a large tree gets bigger plug-ins instead of
  dozens of tiny maps, and a small tree falls below it and renders flat.
- `balance_ratio` stays `0.2`.

An empty or `None` tree falls back to `8` / `4`.

Configurable keys:

| Key                         | Default | Meaning                                                                                                                                  |
|-----------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------|
| `on_root_sequence`          | `True`  | Each child of a top-level `→` becomes a plug-in. Root map reads as a chain of phase stubs.                                                |
| `on_parallel`               | `True`  | Each `+` branch becomes a plug-in. AND-fork/join vertical-expansion cost is replaced by a single stub per branch.                          |
| `on_alternative`            | `True`  | Each `×` (XOR) / `∨` (OR) branch becomes a plug-in. OR-fork/join stays on the parent map; alternative bodies move into per-branch plug-ins. |
| `on_loop`                   | `True`  | Each `*` operator's entire expansion becomes a plug-in. Parent map reads as forward flow with one stub for the iteration. A loop at the *root* of the tree is wrapped in a synthetic sequence so the root map gets a single loop stub. |
| `max_leaves_per_map`        | `20`    | Hard cap; over-sized maps recursively force-cut the largest operator-subtree until the cap is met.                                         |
| `min_leaves_to_decompose`   | `4`     | Floor — subtrees smaller than this stay inlined regardless of rules.                                                                       |
| `balance_ratio`             | `0.2`   | Sibling share threshold under `→` and `+`. A child needs at least this fraction of the parent's leaves to be pulled out independently.     |

Unknown keys raise `ValueError`.

When the UCM has multiple maps, `view_ucm` and `save_vis_ucm` compose
every map vertically into a single PNG (`Pillow` does the stacking).
Each panel has a title strip and adjacent panels are separated by a thin
horizontal rule. Bound stubs gain a `→ <plug-in name>` external label so
the reader can follow each stub to its plug-in map.

## Scenario synthesis

The `discover_scenarios` pipeline turns an event log into an
*executable* UCM: a `.jucm` carrying one URN `ScenarioDef` per
behavioural variant discovered in the log, with typed variables,
per-loop integer counters, and mutually-exclusive OR-fork conditions
that let jUCMNav step through each scenario deterministically.

```python
import pm4py
import pm4py_ucm

log = pm4py.read_xes("log.xes")

# Variant-driven (default) — lossless replay of every observed variant
ucm, clustering = pm4py_ucm.discover_scenarios(log)
pm4py_ucm.write_ucm(ucm, "log.jucm")
pm4py_ucm.write_variants_report(clustering, "variants.csv")
pm4py_ucm.write_case_variant_map(clustering, "case_variant_map.csv")

# Data-driven — mine per-fork decision trees over case attributes,
# emit conditions like `Broker == Spot_Health_Insurance && Claim_Value <= 1417646`
ucm_dd, _ = pm4py_ucm.discover_scenarios(
    log, condition_strategy="data-driven",
    decision_tree_max_depth=3,
)
group = ucm_dd.scenario_groups[0]
pm4py_ucm.write_ucm(ucm_dd, "log.data_driven.jucm")
pm4py_ucm.write_condition_mining_report(group, "condition_mining.csv")
```

`discover_scenarios` mines the tree itself, at PM4Py's default noise
threshold of `0.0` unless told otherwise. It takes the same
`discovery_parameters` entry as `discover_ucm_inductive`, so scenarios
for a noise-filtered model need nothing more; the cases the filtered tree
cannot replay are reported as noise:

```python
ucm, clustering = pm4py_ucm.discover_scenarios(
    log, parameters={"discovery_parameters": {"noise_threshold": 0.2}})
print(clustering.fitness_percentage, len(clustering.noise_case_ids))
```

A tree you mined yourself can still be handed over as
`parameters={"process_tree": tree}`; `discovery_parameters` is then ignored
(with a warning), since nothing is mined. (Up to 0.9.0 that was the only
way to set a noise threshold here: `discovery_parameters` was not read.)

The long-running entry points — `discover_scenarios`, `discover_ucm_family`,
`compute_family_stats` — take a `progress_callback(stage, done, total)`.

### What the synthesizer populates

- **`EnumerationType` `VariantId`** with values `[v1, v2, …]`
  (variant-driven only), plus one `EnumerationType` per case-constant
  string attribute the log carries (data-driven only).
- **`Variable`s** — a `variant_id` enum (variant-driven) or one variable
  per mined case attribute (data-driven), plus one `integer` per loop
  operator in the discovered tree (contextually named e.g.
  `Loop_AnalyzeClaim`).
- **One `ScenarioDef` per variant**, each with an `Init` per variable
  (variant-driven initialises `variant_id`; data-driven initialises
  each attribute to a representative value for its variant — mode for
  enum/bool, scaled median for integer), plus a per-loop counter init
  capped at `max_loop_iterations` (default 2; `suggest_loop_iterations(tree)`
  tells how many iterations each loop needs for a scenario to reach every
  branch inside it), plus `ScenarioStartPoint`
  / `ScenarioEndPoint` refs. Names carry a short discriminator
  (`v3_TwoCloseAssessmen`, `v8_QuickAssessment`); descriptions start
  with a plain-English `Intent:` line.
- **Arc conditions on every non-loop OR-fork** — variant-driven writes
  `variant_id == v_i` disjunctions (with an inside-loop variant that
  combines the disjunction with counter thresholds); data-driven writes
  mined boolean expressions over case attributes.
- **A `LoopEntryGuard` OR-fork** per loop, spliced between the loop's
  upstream arc and its `LoopJoin`, with mutually-exclusive `counter > 0`
  / `counter <= 0` conditions. This restores the semantics
  "counter = number of body executions" — including zero. When a
  loop's post-loop continuation is a `Stub`, an `OrJoin` is spliced
  before the stub so its plug-in binding stays complete.

### Before running scenarios in jUCMNav: check the hit-count ceiling

jUCMNav declares an infinite loop as soon as a **single element** has
been entered as many times as its *maximum hit count* preference allows
(*Preferences → jUCMNav → Scenario Traversal*). That ceiling is a
setting, not a property of your model. Set below what a model
legitimately needs, jUCMNav abandons the offending visit, its AND-joins
then starve, and the scenario never reaches its end point — producing a
Problems view full of blocked joins and unreached end points for a model
that is perfectly correct.

A model whose discovered tree nests loops around parallel branches
enters some elements once per iteration of *every* enclosing loop, so it
can need a far higher ceiling than a flat one. Across the 28 models of
our evaluation most need 2–6; one, a depth-3 loop nest, needs 10 — and
against a preference set to exactly 10 it reported eight errors that
were entirely artefacts of the setting.

jUCMNav's own default is 1000, which is ample. If yours has been
lowered, raise it before concluding that a generated model is broken.
To find what a specific model needs:

```python
from pm4py_ucm.algo.scenario_traversal import required_max_hit_count

need, scenario, element = required_max_hit_count(ucm)
print(f"set jUCMNav's maximum hit count to at least {need} "
      f"(driven by {element} in {scenario})")
```

The same module executes every scenario offline under jUCMNav's
traversal semantics, so a model can be checked before it is opened in
the tool at all — it reports blocked AND-joins, unreached end points,
and forks where no branch (or more than one) is enabled:

```python
from pm4py_ucm.algo.scenario_traversal import check_traversal

for problem in check_traversal(ucm):
    print(problem)
```

That simulator is public API in its own right — see
[Scenario simulation, coverage and A/B comparison](#scenario-simulation-coverage-and-ab-comparison)
for running the scenarios, not just screening them.

### Concurrency-aware variants

Two traces that differ only in the interleaving order of activities
inside a parallel block share the same **choice signature** and
therefore the same variant. `X → (Y ∥ Z) → W` traces `X-Y-Z-W` and
`X-Z-Y-W` cluster as one; sequence-variant analysis splits them. The
`compression_ratio` (concurrency-aware / sequence-variant count) on
`ClaimsPaymentLog` is 0.146, meaning naive clustering over-counts by
~7×.

Loop iteration counts are coarsened to `{0, 1, ≥2}` by default to keep
the variant count small; pass `coarsen_loops=False` to distinguish
every iteration count.

**Traces that don't fit, and traces that ran out of search.** Replaying a
trace the tree cannot produce yields `NOFIT` — and so does a trace whose
search hit its state budget. The two are kept apart, so a time limit does
not pass for a finding: `cluster()` takes `max_replay_states` (default
200 000), `choice_signature.replay()` takes a `stats` dict, and the cases
that merely ran out of budget surface separately as
`ClusteringResult.budget_exhausted_case_ids`:

```python
from pm4py_ucm.algo.discovery.variants import clustering

result = clustering.cluster(log, tree, max_replay_states=200_000)
gave_up = result.budget_exhausted_case_ids      # a time limit, not a misfit
```

That distinction matters when reporting fitness: a case in `gave_up` would
likely fit given more search, so counting it as non-fitting understates the
model. Anything reported off the back of it should say so.

### Reading a variant expression

Each variant is summarised as a compact **partial-order expression**
(shown in `variants.csv`, the Scenarios view, and scenario
descriptions). It is a per-variant *projection* of the discovered
process tree — it shows what this behavioural variant actually did, not
the whole model:

| Syntax | Source | Meaning |
|--------|--------|---------|
| `A` | activity leaf | activity `A` was executed here — no choice, no loop |
| `X -> Y` | sequence | `X`, then `Y` |
| `[A]` | XOR / OR | a **choice** point; branch `A` is the one this variant took (another variant may show `[B]` here) |
| `(X \|\| Y)` | AND (parallel) | `X` and `Y` ran concurrently — any interleaving is the same variant |
| `A^0` / `A^1` / `A^>=2` | loop | loop body `A` ran zero / exactly once / two-or-more times (the coarsened `{0, 1, ≥2}` bucket) |

Two conventions worth knowing: a parallel branch this variant **skipped**
shows as `[tau]` (the silent choice was taken), so `(E || [tau])` means
"`E`, in parallel with an optional branch that was skipped here"; and a
parallel of a single activity with nothing (`A || tau`) simplifies to
just `A`.

### Two condition-encoding strategies

| Strategy       | Arc conditions                                                                | Trade-off                                                                                                     |
|----------------|-------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
| `variant`      | `variant_id == v_i` disjunctions per branch                                   | **Lossless** — replaying scenario `v_i` reproduces `v_i`'s choice signature exactly. Doesn't *explain* choices. |
| `data-driven`  | Boolean expressions over case attributes, mined per-fork by decision trees    | Business-readable rules on every fork; requires case-constant attributes; **abandons with a warning** otherwise. |

Inside-loop OR-forks (XORs sitting inside a loop body): variant-driven
combines `variant_id` with the enclosing counter to distribute branches
across iterations. Data-driven falls back, only for inside-loop forks,
to a deterministic `true`/`false` split — case attributes are static per
case and can't disambiguate per-iteration choices.

### Reports

Three CSVs alongside the `.jucm`:

- **`variants.csv`** — one row per variant with frequency, sequence-
  variant count, linearization count, partial-order expression, and a
  truncated case-ID list. Trailing rows for `noise` and `totals`
  (fitness + compression).
- **`case_variant_map.csv`** — one row per case, mapping case ID to
  variant ID (or `noise` for non-conforming cases).
- **`condition_mining.csv`** — data-driven mode only. One row per
  `(OR-fork, branch)` with accuracy, sample size, feature set,
  `skipped_reason` (`inside_loop`, `no_labelled_cases`), and the
  post-minimisation expression emitted on the arc.

### Interaction with decomposition

`discover_scenarios` accepts the same `decomposition=` argument as
`discover_ucm_inductive` and honours it fully: OR-forks that land in
plug-in maps receive the same conditions they would in the flat case,
and loops pushed into plug-in maps get their counter machinery
(LoopEntryGuard, decrement responsibility) spliced into the correct
map. Each UCM `OrFork` / `OrJoin` / `LoopFork` / `LoopJoin` carries a
stable id linking it back to the tree node it came from, so
correlation survives arbitrary decomposition boundaries.

## Scenario simulation, coverage and A/B comparison

Synthesized scenarios are executable, so they can be **run** — offline,
under jUCMNav's own traversal semantics, without opening jUCMNav. A token
leaves each enabled start point; an OR-fork takes the branch whose guard
holds, an AND-fork spawns one token per arm, an AND-join waits for all of
them, and a stub descends into its plug-in.

```python
import pm4py
import pm4py_ucm

tree = pm4py.discover_process_tree_inductive(log, noise_threshold=0.2)
ucm, clustering = pm4py_ucm.discover_scenarios(
    log, parameters={"process_tree": tree})

for result in pm4py_ucm.traverse_all(ucm):          # one per scenario
    status = "clean" if result.ok else "problems"
    print(f"{result.scenario}: {status}, {result.steps} steps")
    for problem in result.problems:
        print("   ", problem)
```

`traverse_all` raises `NoScenariosError` when the model declares none,
rather than reporting "no problems found" — a caller asking whether a model
executes cleanly must never be told *yes* on the strength of having run
nothing. `traverse_scenario(ucm, scenario)` runs a single one.

Each result reports the same four problem kinds jUCMNav's Problems view
does (blocked AND-join, unreached end point, no branch enabled, several
branches enabled), plus `peak_hit_count` — see
[the hit-count ceiling](#before-running-scenarios-in-jucmnav-check-the-hit-count-ceiling)
— and `visits`, the net hit count per element the run actually executed.

### What a scenario covered

`visits` is what makes coverage possible: it is keyed by `(type name, model
id)` rather than object identity, so a run can be compared against another,
serialised, or matched back onto a rendered diagram.

```python
results = pm4py_ucm.traverse_all(ucm)

cov = pm4py_ucm.coverage(ucm, results[:1])          # or any subset
print(cov.elements)          # (53, 97)   path nodes covered / total
print(cov.paths)             # (53, 108)  path segments covered / total
print(cov.by_kind())         # {'RespRef': (16, 28), 'OrFork': (6, 11), ...}
```

**Elements and paths are reported separately, not as one percentage.** A run
can walk every node and still miss segments — an alternative branch carrying
no responsibility *is* a segment and nothing else — so the split says whether
what is left uncovered is real behaviour or just empty paths. On
`ClaimsPaymentLog` mined as above (18 scenarios, all clean) a single
scenario covers 53 of 97 elements; all 18 together reach 93/97 elements and
99/108 paths. (The numbers in this section are for that model; at the
default noise threshold of `0.0` the log yields 24 scenarios.)

Coverage is measured against the **whole model**, every map included, which
is why one scenario reads low: it walks one path through a model that
contains every path. That is the honest number.

### Two scenarios, side by side

```python
cmp = pm4py_ucm.compare(ucm, results[0], results[1])
print(len(cmp.a_only), len(cmp.b_only), len(cmp.both))   # 7 25 99
print(f"{cmp.agreement:.0%}")                            # 76%
print(len(cmp.neither))                                  # never walked by either
```

`agreement` is the Jaccard index — the share of everything either scenario
walked that **both** walked. Two scenarios sharing a start point can never
score 0, so a very low number means they diverge almost immediately.

### Painting either onto the diagram

`coverage_render` and `comparison_render` turn a `Coverage` or a
`Comparison` into colours and hover text keyed by `id(element)`, ready for
the renderer:

```python
from pm4py_ucm.algo.scenario_coverage import comparison_render
from pm4py_ucm.visualization.ucm import svg

highlight = comparison_render(ucm, cmp)
open("compare.svg", "w", encoding="utf-8").write(
    svg.model_to_svg(ucm, "ucm", coverage=highlight))
```

A/B is painted **dark green** (A only), **dark orange** (B only) and
**purple** (both); the pair separates by lightness as well as hue, so it
survives a greyscale printout and does not lean on the red-green axis.
Supplying a highlight suspends the performance heat-map, since the two
compete for the same colour channel.

The web app's Scenarios view exposes all of this without code, and both the
saved project and the exported Python script carry the selection — see
[`docs/scenario_simulation.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/scenario_simulation.md) for the design
note behind it.

## Model families (attribute-partitioned discovery)

Many logs mix cases that follow *different processes* — a cancer-care
log contains distinct pathways per cancer type, a claims log may route
work differently per country. `discover_ucm_family` partitions the log
by the values of **one or two case-level attributes** and mines one
model per combination; the family can then be exported as separate
models, rendered side by side, or assembled into a single
**overarching model** where UCM's own variability constructs carry the
family: **dynamic stubs are variation points, plug-in maps are
variants, and scenario strategies are configurations**.

```python
# Which attributes are worth partitioning on? Best first, with a rationale.
for score in pm4py_ucm.rank_partition_attributes(log)[:3]:
    print(score.name, score.score, score.rationale)

family = pm4py_ucm.discover_ucm_family(
    log, ["cancer_type", "age"],       # 1–2 attributes; numerics are binned
    decomposition="auto", min_cases=20,
)

pm4py_ucm.write_ucm_family(family, "family.zip")        # one .jucm per cell
pm4py_ucm.save_vis_ucm_family(family, "grid.png")       # stack / matrix view
pm4py_ucm.view_ucm_family(family)                       # the same, inline

umbrella = pm4py_ucm.assemble_ucm_family(family, mode="umbrella")
pm4py_ucm.write_ucm(umbrella, "family_umbrella.jucm")   # opens in jUCMNav
```

The umbrella's root map is the **shared skeleton** of the cell
processes (computed by anti-unifying the per-cell process trees), with
a dynamic stub only where behaviour actually diverges; each stub's
plug-ins are guarded by preconditions over the attributes
(`cancer_type == Breast && age_group == _40_59`). Behaviourally
identical variants share one plug-in with a domain-factored condition;
**resource variation counts as variation** (the same activity done by
different actors becomes a variation point, each variant drawn inside
its actor); and by default each combination gets **executable path
scenarios** — one per behavioural variant of its sub-log, with
`family_variant` branch conditions and loop counters, so jUCMNav's
traversal walks genuinely different paths per strategy.

Full documentation — partitioning policy, skeleton merge rules,
dedup/conditions, path scenarios, grid resolution, value filtering —
in [`docs/model_families.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/model_families.md). The web app's
**Family** view exposes all of it interactively, including a
pre-mining coverage heatmap and per-attribute value filters.

### Family statistics reports

Compare the family's processes quantitatively — and hand the result
to collaborators as **one self-contained interactive HTML file**:

```python
stats = pm4py_ucm.compute_family_stats(family)     # needs family.log_df
stats.process_frame()                              # pandas: one row per cell
pm4py_ucm.write_family_report(family, "report.html", stats=stats)
```

`compute_family_stats` yields four statistics levels per family member:
**process** (cases, case durations, rework rate, start/end activities,
variant counts, replay fitness), **activity** (frequency, case coverage,
repeats, sojourn and service times), **edge** (directly-follows frequency
and waiting times) and **choice** — OR-fork branch counts *aligned across
the family* through the shared skeleton, so the same decision point is one
comparable row for every combination. Each level is a pandas frame
(`process_frame()`, `activity_frame()`, `edge_frame()`,
`choice_count_frame()`, `choice_share_frame()`), and every metric is defined
in [`docs/metrics.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/metrics.md).

`write_family_report` renders it all into a zero-dependency HTML
report that opens offline in any browser: sortable heat-mapped
ranking tables, a pair-comparison view (any two members side by side
with their **model images embedded**, delta cards, activity Δ/ratio
tables), 100% stacked branch-share bars per choice, and a model
gallery. Every share and time is shown next to its `n`, and metrics
the log cannot support are omitted rather than faked. The web app's
**Compare** view serves the same statistics interactively and
offers the report as a download.

## Performance overlays

Frequencies and times computed from the log, displayed on activities
and edges and exported as jUCMNav metadata:

```python
pm4py_ucm.annotate_performance(
    ucm, log,
    node_metrics=["frequency", "median_time"],
    edge_metrics=["percentage", "mean_time"],
)
pm4py_ucm.save_vis_ucm(ucm, "annotated.png")   # small gray overlay text
pm4py_ucm.write_ucm(ucm, "annotated.jucm")     # per-metric metadata lines
```

Activity metrics: `frequency`, `case_coverage`, `relative_frequency`,
`repeat_frequency` (rework), and (for interval logs with a
`start_timestamp` column) `mean/median/min/max/std/p90/p95/total_time`
service times, plus the `sojourn_*` variants on any timestamped log.
Edge metrics: directly-follows `frequency`, `case_frequency`,
`relative_frequency`, OR-fork branch `percentage`, and the
`mean/median/min/max/std/p90/p95/total_time` waiting times — attributed
via activity-to-activity *segments* that walk through bends, joins,
forks, and static stubs (so decomposed models are covered too). The
one or two metrics selected per layer control what is drawn on the diagram, but
**every** available metric is exported as its own `perf_<metric>`
metadata line for jUCMNav's properties view; the family assemblies
annotate the shared skeleton from the whole log and each variant
plug-in from its own sub-log. Overlay walkthrough in
[`docs/model_families.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/model_families.md#2-performance-overlays).

The frequencies above count events and directly-follows pairs. The
**replay-based** counts — the web app's default, which conserve across forks
and joins — are the `traversal_frequency` (activities and edges) and
`traversal_percentage` (edges) metrics. They need a replay of the log on the
tree the model was built from:

```python
tree = pm4py.discover_process_tree_inductive(log, noise_threshold=0.2)
ucm = pm4py_ucm.discover_ucm_inductive(log, parameters={"process_tree": tree})

traversal = pm4py_ucm.compute_traversal_stats(tree, log)
print(f"{traversal.fitting_ratio:.0%} of cases fit the model exactly")
pm4py_ucm.annotate_performance(
    ucm, log,
    node_metrics=["traversal_frequency"],
    edge_metrics=["traversal_frequency", "traversal_percentage"],
    traversal=traversal, tree=tree,
)
```

Cases that do not fit are aligned to their nearest model path by default, so
the counts cover the whole log; pass `repair=False` to count only the cases
that fit exactly.

Beyond the text sub-line, an optional **heat-map** colours and thickens
activities and edges by the *first* chosen metric of each layer — across the
**Model, Family and Compare** views alike (a **time** metric reads red, any
other blue; darker/thicker = higher). Its **scale** control offers three modes:
**Local (per map)** (each diagram to its own min/max), **Per family member
(across its maps)** (each Family/Compare member against its own range, pooled
over its decomposed maps — the whole model in the Model view), and **Global
(across family members)** (every member against **one shared range**, so a
colour is comparable across members). It is a render-time overlay of the same
`perf_<metric>` values — the model and `.jucm` are unchanged — exposed by
`model_to_svg(ucm, style, heatmap=True, node_metric=…, edge_metric=…,
heatmap_global=…, node_span=…, edge_span=…)`; `classic.heat_span(models, …)`
computes the shared cross-member span.

**📏 [`docs/metrics.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/metrics.md) is the readable, complete list
of every metric definition** — activity, edge, process and choice —
with units, timestamp semantics, aggregation rules, and the deliberate
edge-case decisions (negative waiting on overlapping intervals, tie
handling, and the working-calendar caveat: all times are raw wall-clock,
with no weekends/holidays subtracted). It is the semantic contract the
metric-validation suite enforces against pm4py.

## Dashboards

The engine behind the web app's Dashboards view is plain Python in
`pm4py_ucm.algo.dashboards`. A dashboard is a list of JSON **widget specs**
(a catalog metric, its parameters, an aggregation, filters, segmentation, a
visualisation, an optional target) evaluated over a per-case **fact table**:

```python
from pm4py_ucm.algo import dashboards

table = dashboards.build_fact_table(log, log_name="claims")

# Whole dashboards proposed from the log itself — deterministic, no LLM.
proposals = dashboards.suggest_dashboards(table)
print([p["name"] for p in proposals])
# ['Overview', 'Bottlenecks', 'Rework and flow', 'Segments']
overview = proposals[0]
print(overview["why"])                       # each proposal says why

result = dashboards.compute_widget(overview["specs"][0], table)
print(result["title"], result["text"])       # median case duration 15.2 d

dashboards.write_dashboard(                   # self-contained interactive HTML
    "overview.html", table, specs=overview["specs"], name=overview["name"])
```

Passing `behaviour=clustering` (from `discover_scenarios`) to
`build_fact_table` adds each case's concurrency-aware variant as a case
attribute, so widgets can segment and filter by behaviour.
The widget spec, the metric catalog and the ƒ formula language are specified
in [`docs/dashboards.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/dashboards.md);
the suggestion rules in
[`docs/dashboard_suggestions.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/dashboard_suggestions.md);
[`demo/dashboards_tutorial.ipynb`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/dashboards_tutorial.ipynb)
walks through all of it.

## Module layout

```
pm4py_ucm/
├── api.py                                 # high-level read_/write_/discover_/view_
├── objects/ucm/
│   ├── obj.py                             # UCM object model (URN metamodel)
│   ├── validate.py                        # structural well-formedness (jUCMNav arity rules)
│   ├── conversion/from_process_tree.py    # PM4Py process tree → UCM
│   ├── conversion/decomposition.py        # hierarchical decomposition rules + presets
│   ├── exporter/variants/jucm.py          # UCM → jUCMNav .jucm (XMI 2.0)
│   ├── exporter/variants/bpmn.py          # UCM → BPMN 2.0 XML + BPMNDI
│   ├── importer/variants/jucm.py          # jUCMNav .jucm → UCM
│   ├── layout/layouter.py                 # built-in layered auto-layout
│   ├── layout/graphviz_layouter.py        # graphviz positions, matching the PNG
│   └── util/                              # name wrapping, component colours
├── algo/
│   ├── complexity.py                      # cost screening: profile / risk / replay estimate
│   ├── performance.py                     # frequency/time overlays on activities + edges
│   ├── traversal.py                       # conserving traversal counts from a replay
│   ├── scenario_traversal.py              # jUCMNav's scenario execution, offline
│   ├── scenario_coverage.py               # coverage + A/B comparison over a traversal
│   ├── dashboards/                        # user-defined dashboards over a fact table
│   │   ├── contract.py                    # widget/spec schema shared with the browser island
│   │   ├── catalog.py                     # the metric catalog
│   │   ├── engine.py                      # fact table + metric evaluation
│   │   ├── formula.py                     # the ƒ custom-formula language
│   │   ├── suggest.py                     # dashboards proposed from the log itself
│   │   └── view.py                        # self-contained interactive HTML export
│   └── discovery/
│       ├── ucm/
│       │   ├── algorithm.py               # discovery dispatcher (mirrors BPMN)
│       │   └── variants/inductive.py      # inductive-miner-based discovery
│       ├── resources/                     # activity → performer mining
│       ├── variants/                      # concurrency-aware variant clustering
│       │   ├── choice_signature.py        # replay algorithm + signature canonicalisation
│       │   ├── parses.py                  # the shared replay, computed once per log+tree
│       │   └── clustering.py              # per-variant clustering + fitness / compression
│       ├── scenarios/                     # scenario synthesis on top of a UCM + clustering
│       │   ├── synthesis.py               # variables, ScenarioDefs, LoopEntryGuard, conditions
│       │   ├── decision_mining.py         # data-driven strategy: sklearn tree → jUCMNav expr
│       │   ├── expression_minimizer.py    # boolean simplifier for mined expressions
│       │   └── reports.py                 # variants.csv / case_variant_map.csv / condition_mining.csv
│       └── families/                      # attribute-partitioned model families
│           ├── partition.py               # case-attribute detection + log partitioning
│           ├── advisor.py                 # which attributes are worth partitioning on
│           ├── family.py                  # ModelFamily container + zip/dir export
│           ├── algorithm.py               # per-cell discovery driver
│           ├── assembly.py                # combined + skeleton-umbrella assembly
│           ├── scenarios.py               # per-cell path scenarios on the umbrella
│           ├── stats.py                   # FamilyStats: process/activity/choice comparison
│           └── report.py                  # self-contained interactive HTML report
├── util/progress.py                       # progress_callback plumbing for the long loops
└── visualization/ucm/
    ├── visualizer.py                      # apply / view / save (mirrors BPMN)
    ├── svg.py                             # navigable inline SVG (stub links, hover text)
    ├── stacked.py                         # vertical multi-map composition
    ├── family_grid.py                     # family stack/matrix rendering (adaptive DPI)
    ├── parameters.py                      # render parameter names
    └── variants/classic.py                # graphviz-based renderer
```

The object model in `objects/ucm/obj.py` mirrors the [jUCMNav EMF
metamodel][jucmnav-meta] (`urn`, `urncore`, `ucm.map`) closely enough to
emit XMI files that load directly in jUCMNav.

[jucmnav-meta]: https://github.com/JUCMNAV/projetseg-update/tree/master/seg.jUCMNav/src/seg/jUCMNav/emf

## Cleaning a log by variant

Clustering already records which case fell into which behavioural variant, so
choosing a few variants selects a sub-log directly:

```python
tree = pm4py.discover_process_tree_inductive(log, noise_threshold=0.2)
ucm, clustering = pm4py_ucm.discover_scenarios(
    log, parameters={"process_tree": tree})

# Keep the two most frequent variants (they are ordered by frequency)
kept = pm4py_ucm.filter_log_by_variants(log, clustering, ["v1", "v2"])

# Scenario names work too, so a selection made in the app can be replayed
kept = pm4py_ucm.filter_log_by_variants(
    log, clustering, ["v1_QuickAssessment", "v2_AnalyzeClaim"])
```

A `DataFrame` comes back with the original columns and row order, so it
re-mines exactly like the log it came from.

**This is how a noisy log gets cleaned.** A case that did not replay on the
tree is *noise* and belongs to no variant, so selecting every variant already
removes it — no further threshold to tune:

```python
names = [s.name for g in ucm.scenario_groups for s in g.scenarios]
clean = pm4py_ucm.filter_log_by_variants(log, clustering, names)
```

(On a tree mined at the default noise threshold of `0.0` every case replays,
so there is nothing to remove; the cleaning comes from a filtered model, as
above.)

An unrecognised name raises rather than being skipped: silently dropping one
would silently shrink the result, and a log quietly missing cases is worse
than no log. `pm4py_ucm.resolve_variant_names` exposes the same lookup on its
own.

In the web app this is the **Export the log for the selected variants** panel
at the bottom of the Scenarios view's Simulation section — the picker that
chooses what to highlight also chooses what to keep, downloadable as XES or
CSV.

## Structural validation

A UCM is not just a bag of nodes: jUCMNav's metamodel fixes how many path
segments may enter and leave each kind. A responsibility sits on exactly
one path, a fork has one way in and several out, a join the reverse.

```python
from pm4py_ucm import validate_ucm, check_ucm

problems = validate_ucm(ucm)      # a list; empty means well-formed
for p in problems:
    print(p)      # [DiscoveredMap] RespRef 'Assess Claim' (id 12): 2 incoming (expected 1)

check_ucm(ucm)                    # or raise, for a caller that would rather fail
```

**You do not normally call either.** The check is wired into the points where
a model is *generated* and where it is *written*, so a malformed UCM cannot
reach you in the first place:

| Function | When it checks |
|---|---|
| `convert_to_ucm` | the converted result (a `UCM` passed straight through is not checked — it was not produced here) |
| `discover_ucm_inductive` | the mined model |
| `discover_scenarios` | via synthesis, below |
| `synthesize_scenarios` | after splicing loop guards and condition forks |
| `discover_ucm_family` | each cell as it is mined, naming the cell |
| `assemble_ucm_family` | the finished container, both modes |
| `write_ucm` | before writing; nothing is written if it fails |
| `write_bpmn` | likewise |

Each takes `validate=True` by default and raises `ValueError` otherwise.

Generation and export fail for **different reasons**, and say so. A generator
failure is a bug in this library — it built the model from your process tree,
so no input of yours can be at fault — and the message asks you to report it.
An export failure need not be: jUCMNav accepts files this check rejects, so a
model imported from elsewhere may be malformed through no fault of anyone
here, and round-tripping it has to stay possible:

```python
pm4py_ucm.write_ucm(ucm, "out.jucm", parameters={"validate": False})
ucm = pm4py_ucm.discover_ucm_inductive(log, validate=False)   # and at generation
```

Why gate generation at all, when export already refuses? Because export is the
*last* moment the fault can be caught, and a caller who never exports walks
straight past it — a malformed UCM renders and even traverses without
complaint. Checking where the model is built turns the whole class of fault
from detectable into unobservable downstream. Synthesis carries its own gate
rather than relying on `discover_scenarios`, because it is what *mutates* an
already-sound model, and callers reach it directly: the web app builds the UCM
and calls it itself.

Family assembly is checked **once, on the completed model** rather than per
map: mid-assembly a stub is legitimately arity-invalid until its plug-in
bindings are wired. And nothing is checked while *rendering* — cells are
validated once at mine time, so drawing the family grid, which is the
expensive step and the one repeated on every redraw, pays nothing. Validating
a whole family costs about a thousandth of the mining it sits beside.

The check is structural only. Whether a model deadlocks, or whether its
guards select exactly one branch, is
[`scenario_traversal`](#scenario-simulation-coverage-and-ab-comparison)'s
question — and that answer is only trustworthy on a model that is sound to
begin with.

## Definitions vs references

For the full Python object model in one picture, see
[`docs/ucm_class_diagram.svg`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/ucm_class_diagram.svg) (vector,
paper-ready) or the [PNG preview](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/ucm_class_diagram.png). The
[PlantUML source](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/ucm_class_diagram.puml) can be re-rendered or
extended for figures in academic papers.

UCM keeps a sharp distinction between a *definition* (a reusable named
concept declared once at the URN level) and each visual *reference* to it
on a map. The object model surfaces this distinction explicitly:

| Definition (one) | Reference (many) | Where reference lives |
|---|---|---|
| `UCM.Responsibility` (an activity) | `UCM.RespRef` (the "✕" symbol) | inside a map's `nodes` list |
| `UCM.ComponentElement` (an actor / team / role / system) | `UCM.ComponentRef` (the labelled rectangle) | inside a map's `cont_refs` list |

A definition lives on the URN container (`ucm.responsibilities`,
`ucm.components`). Each *visual occurrence* on a diagram is a separate
reference object that points back to the definition via `resp_def` (for
`RespRef`) or `cont_def` (for `ComponentRef`). Many references may share
the same definition — that is exactly what lets the same activity or the
same actor appear in multiple places without being declared twice.

A third link — `Responsibility.performer` — runs *between definitions*:
it expresses the semantic fact that a given activity is performed by a
given actor/team. This is a logical binding, independent of layout. The
visual binding (`RespRef.cont_ref → ComponentRef`) is derived from it
whenever a map is built or `UCM.bind_performers()` is called.

```text
─ URN level ──────────────────────────────────────────
 Responsibility "Login" ──performer──> ComponentElement "AuthService"
            ▲                                  ▲
            │ resp_def                         │ cont_def
─ Map level ──────────────────────────────────────────
   RespRef #5  ─────cont_ref─────────>  ComponentRef #12
   (drawn as ✕)                         (drawn as a rectangle)
```

Build them through the helpers:

```python
from pm4py_ucm import UCM

ucm = UCM(name="Example")
m   = ucm.add_map(name="MainMap")

# --- DEFINITIONS (one per concept, declared on the URN container) ---
login_def = ucm.get_or_add_responsibility("Login")          # Responsibility
actor_def = ucm.get_or_add_component(                       # ComponentElement
    "User", kind=UCM.ComponentElement.Kind.ACTOR)

# --- REFERENCES (many per definition, drawn on the map) -------------
login_node = m.add_node(UCM.RespRef(resp_def=login_def))    # RespRef
actor_box  = m.add_component_ref(actor_def, width=200, height=120)

# A path node may declare which component reference visually contains it:
login_node.cont_ref = actor_box
```

In the exported `.jucm` you'll see this distinction reflected as the
bidirectional links jUCMNav uses internally:

```xml
<responsibilities name="Login" id="35" respRefs="36"/>
<components       name="User"  id="45" contRefs="46" kind="Actor"/>
…
<nodes   xsi:type="ucm.map:RespRef" id="36" respDef="35" contRef="46" …/>
<contRefs xsi:type="ucm.map:ComponentRef" id="46" contDef="45" nodes="36" …/>
```

The `respRefs`/`contRefs` attributes on a definition list back-references
to every occurrence of it; `respDef`/`contDef` on the reference point
forward to the definition. The exporter computes the back-references
automatically — you only need to set the forward links.

## Compatibility with jUCMNav

The exporter produces files in the modern jUCMNav format (matches output
of jUCMNav 5.5 and later):

* Root element `<urn:URNspec>` declares four namespaces — `xmi`, `xsi`,
  `urn` (`http:///urn.ecore`), and `ucm.map` (`http:///ucm/map.ecore`).
  The `urncore` and `grl` packages do not need declarations because
  their concepts use unqualified element names inside the URN
  containment tree.
* URN-level metadata (`urnVersion="1.27"`, `specVersion="4"`, `name`,
  `author`, `created`, `modified`, `nextGlobalID`) lives on the root
  as **attributes**, not child elements.
* Children of `<urn:URNspec>` appear in the canonical order
  **ucmspec → grlspec → urndef**. Children of `<urndef>` appear in the
  order **responsibilities → specDiagrams → components**. Children of a
  `<specDiagrams>` UCMmap appear as **nodes → contRefs → connections**.
* Connections are **anonymous** — `<connections>` carries no `id`
  attribute. Endpoints use integer node IDs (`source="18" target="19"`).
* Nodes refer to their connections via XPath fragments
  (`succ="//@urndef/@specDiagrams.0/@connections.7"`), the only style
  available because connections lack IDs.
* `<condition>` elements distinguish a human-readable `label` (e.g.
  `"TrueBranch"`) from the logical `expression` (default `"true"`).
* `nextGlobalID` is exactly `max(all IDs) + 1` — the integer ID jUCMNav
  would assign to the next newly-created element.
* Every node and component is given coordinates before export (see
  [`.jucm` layout matches the PNG layout](#jucm-layout-matches-the-png-layout)),
  so the diagram is immediately readable in jUCMNav's editor.

## Documentation

- **Narrative documents** live in
  [`docs/`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/tree/main/docs). Its
  [index](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/README.md)
  lists each one by the question it answers and says what kind it is — a
  contract the tests enforce (metrics, dashboards), a design note (BPMN
  export, scenario simulation, sessions, code export, model families), a
  dated measurement study (miner performance) or a proposal not yet built.
- **API reference** — every public helper and every module, rendered from
  the docstrings by [pdoc](https://pdoc.dev):
  **<https://processmining-uottawa.github.io/pm4py-ucm/>**. It is redeployed
  on every push to `main`; the docs index explains how to build it locally.
- **Tutorials** — the notebooks in
  [`demo/`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/demo/README.md),
  and three short scripts in
  [`examples/`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/tree/main/examples)
  (a hand-built map, inductive mining, scenario synthesis).
- **Web app** — [`web/README.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/web/README.md).
- **Release history** — [`CHANGELOG.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/CHANGELOG.md).

## Testing

```bash
pip install -e ".[dev]"
pytest
```

The suite runs on Python 3.10–3.14 in CI. See
[`tests/README.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/tests/README.md)
for a per-module map of it (purpose and test count), and
[`CONTRIBUTING.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/CONTRIBUTING.md)
for what to run before opening a pull request and the rules the suite
enforces.

Much of the suite does **not** require PM4Py: the process-tree → UCM
converter accepts duck-typed trees (`operator.value`, `children`, `label`),
which the tests use to exercise every operator in isolation, and the tests
that do need PM4Py skip themselves when it is absent. The
`tests/test_export_import.py` suite verifies that round-trip through the
jUCMNav XMI back-end is byte-deterministic.

The performance and family-statistics metrics are validated in
`tests/test_metric_validation.py` against four independent oracles —
a hand-computed distinct-value fixture, algebraic invariants,
metamorphic transforms, and simulation ground truth — with an optional
differential check against pm4py's own DFG/duration functions. The
metrics they enforce are specified in [`docs/metrics.md`](https://github.com/ProcessMining-uOttawa/pm4py-ucm/blob/main/docs/metrics.md).

### Security scan

A lightweight static scan runs locally — no repository code-scanning or
CI minutes required:

```bash
bandit -r pm4py_ucm web -ll     # medium+ severity; ships in .[dev]
```

The medium/high baseline is clean, and `tools/release_check.py` runs this
scan as part of the release gate, so no release goes out with a medium- or
high-severity finding. The scenario-traversal guard evaluator compiles jUCMNav
expressions through a closed grammar before `eval` (no attribute access,
subscripts, string literals or fused operators such as `**`), and a test pins
the escapes it refuses. The `.jucm` importer refuses DTDs
before parsing (`_forbid_dtd`) so untrusted `.jucm` input cannot trigger
XML entity-expansion ("billion laughs") — a zero-dependency alternative
to `defusedxml`. Event-log (XES) parsing is delegated to PM4Py.

## License

GPL-3.0-or-later. [PM4Py][pm4py-gpl], an optional dependency, is
distributed by its authors under AGPL-3.0. The jUCMNav metamodel reproduced
(in spirit) here is itself distributed under EPL-2.0; this package only
re-implements the metamodel in Python and does not bundle any jUCMNav
source.

[pm4py-gpl]: https://github.com/process-intelligence-solutions/pm4py/blob/release/LICENSE
