Metadata-Version: 2.4
Name: clmsynth
Version: 0.7.5
Summary: Synthetic label generator with configurable cluster-label matching (CLM) against ground-truth clusters
Author-email: Arootin Gharibian <arootin.gharibian@vsb.cz>, Milos Kudelka <milos.kudelka@vsb.cz>
Maintainer-email: Arootin Gharibian <arootin.gharibian@vsb.cz>
License-Expression: MIT
Project-URL: Homepage, https://github.com/A-Gharibian/CLMSynth
Project-URL: Repository, https://github.com/A-Gharibian/CLMSynth
Project-URL: Documentation, https://github.com/A-Gharibian/CLMSynth/tree/main/docs
Project-URL: Changelog, https://github.com/A-Gharibian/CLMSynth/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/A-Gharibian/CLMSynth/issues
Project-URL: Paper, https://doi.org/10.1016/j.softx.2026.103077
Keywords: synthetic-data,clustering,benchmark,cluster-label-matching,evaluation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: <3.16,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: numpy>=2.0
Requires-Dist: pandas>=3.0
Requires-Dist: scipy>=1.13
Requires-Dist: scikit-learn>=1.4.2
Requires-Dist: matplotlib>=3.8.4
Provides-Extra: yaml
Requires-Dist: PyYAML>=6.0.1; extra == "yaml"
Provides-Extra: dev
Requires-Dist: pandas-stubs; extra == "dev"
Requires-Dist: scipy-stubs; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: bandit; extra == "dev"
Provides-Extra: test
Requires-Dist: pytest>=9; extra == "test"
Requires-Dist: PyYAML>=6.0.1; extra == "test"
Dynamic: license-file

# Cluster–label matched dataset synthesizer


[![PyPI](https://img.shields.io/pypi/v/clmsynth)](https://pypi.org/project/clmsynth/)
[![Release](https://img.shields.io/github/v/release/A-Gharibian/CLMSynth?include_prereleases&sort=semver)](https://github.com/A-Gharibian/CLMSynth/releases)
[![Python](https://img.shields.io/badge/python-3.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-blue)](https://github.com/A-Gharibian/CLMSynth/blob/main/pyproject.toml)
[![License: MIT](https://img.shields.io/badge/license-MIT-yellow)](https://github.com/A-Gharibian/CLMSynth/blob/main/LICENSE.txt)
[![CI](https://img.shields.io/github/actions/workflow/status/A-Gharibian/CLMSynth/ci.yml?branch=main&label=CI)](https://github.com/A-Gharibian/CLMSynth/actions/workflows/ci.yml)
[![Project status: active](https://img.shields.io/badge/repo%20status-active-brightgreen)](https://www.repostatus.org/#active)
[![Cite](https://img.shields.io/badge/cite-CITATION.cff-blueviolet)](https://github.com/A-Gharibian/CLMSynth/blob/main/CITATION.cff)

CLMSynth generates synthetic label columns on top of existing or generated clusters, 
with mathematically controlled agreement
(recall, class balance, spatial placement, or a solved target metric) 
against the ground-truth clusters.

A generated dataset carries the original features, the ground-truth cluster IDs, and one or more synthetic
labels whose relationship to those clusters is characterized by user-defined configuration.

## Install

Requires Python 3.12 or newer.

```bash
pip install "clmsynth[yaml]"
```

This installs the console
scripts `clmsynth`, `clmsynth-config`, and `clmsynth-wizard`. The `yaml` extra adds
PyYAML, which reads and writes config files other than `.json`; the wizard and
`clmsynth-config` need it. `pip install clmsynth` alone runs the engine,
`run_pipeline`, and `.json` configs.

A first run that needs no network or extra uses the small `fabricated_data` config
bundled in the wheel, and writes to `./OUTPUT`:

```bash
python -m clmsynth.main "$(python -c "from importlib.resources import files; print(files('clmsynth') / 'test_data_config_offline.json')")"
```

**Start with the wizard.** `clmsynth-wizard` asks a question per setting and
writes a runnable config, which is the entry point that needs no files from the
repository. `clmsynth-config` renders a config from `upstream_payload.yaml`
instead, and that file ships in the source distribution and the repository, not
in the wheel.

Working on CLMSynth itself, from a clone:

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

To pin the exact versions used for verification rather than the compatible
ranges, install those first:

```bash
pip install -r requirements.txt
```

[//]: # (Or as a conda environment &#40;mirrors the same versions&#41;:)

[//]: # ()
[//]: # (```bash)

[//]: # (conda env create -f environment.yml)

[//]: # (conda activate clmsynth)


Optional, depending on which source/utility you use:

```bash
pip install git+https://github.com/CN-TU/mdcgenpy    # only needed for data_source: "mdcgen"
```

`mdcgenpy` is GPL-3.0, so CLMSynth never ships it: you install it yourself. Every dependency
CLMSynth ships is permissively licensed.

## Use directly 

**CLMSynth** integrates with both downstream and upstream Python pipelines,
and can run without a config file (`load_config` is the only thing that reads one).
For example, you can run: `your algorithm → CLMSynth → measure → tune the
algorithm`; The engine is one pure function of two arrays, a dictionary, and a seed.
The dictionary below (from the `clm_label` documented in the manual) runs directly:


```python
import numpy as np
from clmsynth import generate_clm_labels, clustering_mcc

clusters = np.repeat([0, 1, 2], 200)                        # an arbitrary ground truth
X = np.repeat([[0., 0.], [5., 0.], [0., 5.]], 200, axis=0)  # a feature space, shape (n, d)
# configuration that can also be supplied through a YAML file:
cfg = {
    "num_classes": 3,
    "matching_mode": "custom",
    "assignment_matrix": [{"clusters": [k], "label": k} for k in range(3)],
    "target_metric": {"type": "mcc", "value": 0.6, "tolerance": 0.01},
}

for target in (0.2, 0.4, 0.6, 0.8):
    cfg["target_metric"]["value"] = target
    labels = generate_clm_labels(clusters, X, cfg, seed=42)   # pandas.Series, one entry per point
    achieved = clustering_mcc(clusters, labels)               # 0.1925, 0.4025, 0.6075, 0.8025
    ...                                                       # pass the dataset to an algorithm.
```

For several labels attached to one dataset rather than one label per call, the route
is `build_context` → `generate_additional_labels` → `DatasetContext.to_dataframe`,
which ends in a frame of features, `Cluster_n` and `Label_n` columns. A fetcher's
frame is only a `DataFrame` carrying a `GroundTruth_*` column so that a
local array can be built without going through the datasource route.

### Diagnostics
Every error and warning the engine raises carries a `[CLM-###]` code
(`1xx` config `ValueError`, `15x` `InfeasibleAllocationError`, `2xx` `MissingConfigKey` (a `KeyError` subclass), and `3xx` Warnings),
defined in `clm_errors.py`. The full catalog is available in the CLMSynth
User Manual under the *Configuration Troubleshooting Reference* section. Each code
has a reproducible case in `docs/troubleshooting_catalog/`, a YAML config and the
log it produced; running and reproducing  the catalogue needs the `yaml` extra.

An invalid configuration 1xx error aborts the whole run for every dataset except:
[CLM-102/105/119/125/127/133], which are raised against each dataset's own cluster count,
cluster IDs or feature columns, so a failure of configuration for one dataset does not apply to a batch of datasets.
[CLM-120] (no recall level of a `target_metric` fits a dataset) leaves only that dataset's
label out: the dataset is still written, and the run continues. So does [CLM-154], a
`target_metric` with `strict: true` that misses its tolerance.
A missing required key (2xx) stops the run too: such a key has no default, so no dataset
can be labelled.
For byoc, [CLM-104] and [CLM-105] are additionally checked across the whole batch before
any work begins, so an ID mismatch refuses the run before a file is written and names
every erroneous dataset; everything else is reported per dataset, and the run continues.

**Diagnostics are either exceptions or logged (but not returned).** 
For example, requesting `mcc: 0.9` against clusters of 300/200/100 returns an ordinary `Series` of the right
length with the right label counts but with the achieved MCC of `0.5196`, which is
the same solution if `0.6` was requested as a target. The result logs and plots report the achieved target.

| band                                | is           | how you read the code                             |
|-------------------------------------|--------------|---------------------------------------------------|
| `[CLM-1xx]` `[CLM-15x]` `[CLM-2xx]` | an exception | `e.code`: `except ValueError as e: e.code == 102` |
| `[CLM-3xx]`                         | a warning    | match `[CLM-###]` in the message text             |

For troubleshooting the warnings and exceptions, refer to the troubleshooting section of the user manual.

## Quick start

**The wizard:** run `clmsynth-wizard`. It asks a question for every setting,
writes the config as YAML or JSON,
and can run the pipeline. Works for every source, including user-provided (`byoc`) data.
CLMSynth is fully functional from a config file; the wizard helps to *create* one.

1. How to generate a config (edit `upstream_payload.yaml`, or pass your own file). The
   shipped payload labels `fcps/hepta` [[4]](#references) from `clustbench`: 212 points
   in 3-D, 7 clusters, one rule per cluster. The `clm_label` block is checked with the
   engine's own checks before it is written; what needs the dataset is checked by the run.
   ```bash
   python -m clmsynth.generate_config                    # reads upstream_payload.yaml, writes test_data_config.yaml
   python -m clmsynth.generate_config my_payload.yaml    # or an explicit payload (and optionally an output path)
   python -m clmsynth.generate_config my_payload.yaml my_config.json   # a .json output path writes JSON
   ```

2. Run the pipeline:
   ```bash
   python -m clmsynth.main                   # reads test_data_config.yaml
   python -m clmsynth.main my_config.yaml    # or an explicit config path
   python -m clmsynth.main my_config.yaml --no-viz   # skip the plots; matplotlib is never imported
   python -m clmsynth.main my_config.yaml --keep-failed   # keep a failed run's config and log
   python -m clmsynth.main a.json b.json c.yaml --jobs 2  # a batch: each config in its own process
   ```
   In a batch every config is a run of its own:
   `--jobs` (default 1) sets how many run at once. Above 1, each run gets `OMP_NUM_THREADS`,
   `OPENBLAS_NUM_THREADS` and `MKL_NUM_THREADS` of 1 unless you set them, so the runs do not each start a thread
   per core. A SIGTERM to the batch process alone starts no further config and lets the running ones finish;
   a scheduler, Ctrl-C or `timeout` signals the whole process group and stops them too.

## Output

Each run creates a folder:

```
OUTPUT/{YYYYMMDD}_{HHMMSS}_{Source}/
├── info/
│   ├── {YYYYMMDD}_{HHMMSS}_{Source}.yaml    # the config as the run read it, .json for a
│   │                                        #   .json config: defaults filled in, seeds
│   │                                        #   and datasets as they ran
│   ├── {YYYYMMDD}_{HHMMSS}_{Source}.log     # the run's log
│   └── {source}-{battery}-{dataset}.txt     # seeds + config + MCC/ARI (as shown on plots);
│                                            #   under scope: pair, the reachable pair MCC;
│                                            #   under a target, what the engine reported
├── csv/{source}-{battery}-{dataset}.csv     # features + Cluster_n + Label_n
├── png/{source}-{battery}-{dataset}-Cluster_0.png
└── png/{source}-{battery}-{dataset}-Label_0.png   # one per generated label
```

- `{Source}` is the display name: `clustbench` → **Clustbench**, `mdcgen` → **MDCGen**,
  `fabricated_data` → **Fabricated**, `byoc` → **BYOC**, Bring Your Own Clusters.
- The base folder is `global_settings.output_dir` (default `OUTPUT`).
- A run that fails before writing a dataset removes its folder. `--keep-failed`
  keeps it, with the config and the log of why it failed.
- **Exit status:**
  - 0: every dataset written with all its labels.
  - 1: nothing written, for a reason beyond the config: a dataset its source
    could not deliver (a failed download; a data CSV that is missing, unreadable
    or refused by byoc's import checks, `[CLM-133]` among them), an output folder
    that cannot be created, PyYAML missing for a `.yaml` config, a crash.
  - 2: the command line or the config is wrong: a usage error, a missing or
    malformed config, a missing required key (`[CLM-2xx]`), a `[CLM-1xx]` refusal
    from the labeling. Nothing is written.
    `clmsynth-config` exits 2 for a payload that is missing, malformed or of the
    wrong shape, or whose `clm_label` block the engine refuses (`[CLM-1xx]`,
    `[CLM-2xx]`).
  - 3: incomplete: some datasets written, others skipped or without all their
    labels; the run's last warning counts them. A failed download may succeed
    when the job is resubmitted; anything else repeats until the config or the
    data change.
  - 130 interrupted (Ctrl-C or SIGINT), 143 terminated (SIGTERM).

  Any other status comes from the shell, the scheduler or a wrapper such as
  `timeout` or `xargs`; a `[CLM-nnn]` code with the same number is unrelated. A
  batch reads its configs as a run reads its datasets: 0 when every config
  exited 0, 3 when some wrote their datasets and others did not, otherwise 1, or
  2 when every config exited 2. A signal's status comes first.
- **Column naming:** ground-truth class labeling such as `Cluster_0`, `Cluster_1`, …
  (by position, `source_labeling: labels0` surfaces as `Cluster_0`); generated
  labels become `Label_0`, `Label_1`, … (0-indexed, one per `n_labels`).
- The MCC/ARI printed in each plot subtitle and in the `.txt` summary are
  computed from the output CSV.

### Data sources

- **`clustbench`**, geometries downloaded from Gagolewski's **A Framework for Benchmarking Clustering Algorithms**
  [[1]](#references), whose Python API is imported as `clustbench` and which supplies this source's config key. 
  Every available reference labeling (`labels0`, `labels1`, …) is fetched.
- **`mdcgen`**, fully synthetic geometries via `mdcgenpy` [[2]](#references).
  Use when specific properties (dimensionality, overlap, outliers) are needed that the clustering-benchmarks datasets
  may not cover.
- **`fabricated_data`**, offline fallback. Cluster IDs are integers `0..K-1`, as in the other generated sources;
  the generator's readable class names are mapped to codes on import. The `labels_only_4class` preset emits 
  **cluster IDs with no feature columns at all**, a valid CLM run, since recall, balance, allocation, and spillover
  do not need feature values.
- **`byoc`**, bring-your-own-clusters: your own CSV with feature columns and one cluster-id column (see below).

### Bring-your-own-clusters (`byoc`)

Point the pipeline at your own CSV, feature columns with **exactly one** cluster-id column, and it generates CLM labels 
against *your* clusters:

```yaml
global_settings:
  data_source: "byoc"
  output_dir: "OUTPUT"

byoc_suite:
  batteries: ["local"]          # fixed label, kept for pipeline uniformity
  input_dir: "INPUT"            # folder holding your CSV(s)
  datasets: ["my_clusters"]     # file STEMS (no ".csv"); one output per file
  cluster_column: "group"       # the single ground-truth cluster column
  tag_columns: ["outcome"]      # optional: carried through, never features
  standardize: false            # optional: min-max rescale features to [0,1] at import
  seed: 42

label_generation:
  # ... identical to any other source ...
  clm_label:
    num_classes: 2
    matching_mode: "perfect"
```

- Every column other than `cluster_column` becomes a feature unless `tag_columns` names it
  (original names are kept, so plot axes show them as imported). Features must be numeric;
   a non-numeric column that is not declared a tag **rejects the file**.
- **`tag_columns`** lists columns that travel with the data without entering the CLM matching: an outcome variable,
  a second labeling from another method, an identifier. They are copied to the output CSV unchanged, are excluded from
  the geometry and from `standardize`, and need not be numeric.
- One `cluster_column` is required; the run is **rejected** (logged, dataset skipped) if it is missing or names
  more than one column.
- `standardize: true` min-max rescales the features to `[0, 1]` at import, applied once, before both the
   geometry/centroid math and the written CSV. Off by default.
- Cluster IDs are integers, in the file and wherever the config names a cluster (`single_match`,
  `assignment_matrix`, `competing_noise`); `1.0`, `"C1"` or `true` is refused (`[CLM-133]` in the file,
  `[CLM-141]` in the config). The column's name is free.

### `matching_mode` reference

- `perfect`, fixed cluster↔label bijection; label counts are forced to the paired cluster sizes. 
   Requires `num_classes == K`. `balance`, `proportions`, `skew_rule` and `skew_params` are
   neither read nor validated (`[CLM-302]` warns when any is set).
- `single` routes label `l*`'s point budget into cluster `k*`. 
   **Note:** the current implementation places up to `recall_target × m_{l*}` points of `l*` into `k*`,
   so it requires `|k*| ≥ m_{l*}`.
- `random`, labels drawn from the resolved proportions, ignoring cluster structure entirely.
   `centroid_dependence` is ignored there (`[CLM-311]`), so data without features runs.
- `custom`, one or more explicit `assignment_matrix` rules, each routing a `recall_target` 
   fraction of one label's points into a set of clusters. Supports surjective (many clusters → one label),
   partial, and overlapping alignments. Unclaimed cluster capacity follows `spillover_rule`.

### Target-metric solving

`target_metric` (only under `single`/`custom`) has two scopes. In both, the
solver varies only the recall level; every setting above (`split_rule`,
`spillover_rule`, `competing_noise`, `proportions`) is held fixed across
probes, so noise structure changes the solved recall rather than being
applied after it.

- **`scope: "global"` (default)**, targets the whole-partition metric. A single
  global recall level is solved (coarse grid scan → Brent's method) so the achieved 
  MCC or ARI meets the requested value within tolerance. When the grid alone finds no
  recall level that fits, or misses the target, the search also looks between two
  neighbouring grid levels where the outcome changes: a level that fits next to one
  refused with `[CLM-15x]`, or `[CLM-152]` next to another code. If the target exceeds
  what the geometry/proportions can
  reach, the solver returns its closest feasible value and logs a
  non-convergence warning. Works for `type: mcc` and `type: ari`.
- **`scope: "pair"` (`type: mcc`, `single` mode only)**, targets the `2×2` MCC
  of the `single_match` cluster/label pair (that cluster vs. the rest against
  that label vs. the rest). This inverts in **closed form**, so it is an
  exact solve, and the delivered pair MCC is measured afterward and reported as achieved
  (see Section 2.2.2, Generative conditions, of the
  [article](https://doi.org/10.1016/j.softx.2026.103077)).
  The whole-partition `R_K` and ARI reported on the plots then serve as
  independent views of the same labeling.

A miss is delivered as the closest value with a warning. With `strict: true`
(either scope) a delivered value outside `value ± tolerance` is refused with
`[CLM-154]` and the label is not written; without a `tolerance`, strict asks for
the exact value.

> **What metric is being solved.** The global MCC is the multiclass Gorodkin's
> `R_K` that `clustering_mcc` computes (permutation-invariant via Hungarian
> matching), while the pair MCC is the `2×2` Matthews φ that `clustering_mcc_pair`
> computes for a single cluster/label pair. The global `R_K` and ARI between an
> `M`-label and a `K`-cluster partition have no closed form, so their solver is
> numerical; which is why `scope: pair` is exact. For that reason the pair (binary)
> measure is the natural choice for
> single-label to single-cluster matching, whereas the scikit-learn multiclass
> implementation (`R_K`) is meant for multi-label cases. The pair MCC can still be
> requested against a target cluster inside a custom-distribution configuration to
> check one label's precision and recall (rather than its specificity). If you are
> only interested in a single target label and cluster, prefer
> `matching_mode: single` with `scope: pair` over a custom distribution coupled
> with a binary MCC solver [[3]](#References).

## Citing

If you use this software as a benchmark, you can export the citation file from the
project information panel and cite the software itself. Sharing the results in Zenodo
and linking it to the software repository there is encouraged, so that results from
different studies can be compared. The software description has been published in SoftwareX [[5]](#References); 
cite the [paper](https://doi.org/10.1016/j.softx.2026.103077) only if you discuss CLM, target-metric solution,
or general benchmarking solution in clustering and classification, and CLMSynth is relevant
to your discussion.

## References

1. Gagolewski, M. (2022). A framework for benchmarking clustering algorithms.
   *SoftwareX*, 20, 101270. <https://doi.org/10.1016/j.softx.2022.101270>
2. Iglesias, F., Zseby, T., Ferreira, D., et al. (2019). MDCGen:
   Multidimensional Dataset Generator for Clustering. *Journal of
   Classification*, 36, 599–618. <https://doi.org/10.1007/s00357-019-9312-3>
3. Gorodkin, J. (2004). Comparing two K-category assignments by a K-category
   correlation coefficient. *Computational Biology and Chemistry*, 28(5–6),
   367–374.
4. Thrun, M. C., & Ultsch, A. (2020). Clustering benchmark datasets exploiting the
   fundamental clustering problems. *Data in Brief*, 30, 105501.
   <https://doi.org/10.1016/j.dib.2020.105501>
5. Gharibian, A., Kudělka, M. (2026). A synthetic data generator for cluster and label matching evaluation,
SoftwareX, Volume 36, 103077. <https://doi.org/10.1016/j.softx.2026.103077>
