Metadata-Version: 2.4
Name: merkmal
Version: 0.15.0
Summary: Standalone phonological feature systems for historical linguistics
Author-email: Tiago Tresoldi <tiago.tresoldi@lingfil.uu.se>
License-Expression: MIT AND CC-BY-4.0 AND CC-BY-SA-3.0 AND CC-BY-NC-SA-4.0
Project-URL: Homepage, https://github.com/tresoldi/merkmal
Project-URL: Documentation, https://github.com/tresoldi/merkmal#readme
Project-URL: Repository, https://github.com/tresoldi/merkmal
Project-URL: Bug Tracker, https://github.com/tresoldi/merkmal/issues
Keywords: phonology,phonological features,historical linguistics,sequence alignment,cognate detection
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: C
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: build; extra == "dev"
Dynamic: license-file

# merkmal

merkmal maps IPA transcriptions of speech segments to phonological feature
representations under seven built-in feature systems, and computes
dissimilarities between segments from those representations. This package is the
Python interface and `merkmal` command line of the merkmal C99 library. The
extension module, `merkmal._native`, is built against the CPython Limited API
(`cp312-abi3`) and delegates every calculation to the C core; there is no
separate Python implementation and no runtime dependency.

For cross-language workflows and phonological background, see the
[overview guide](https://github.com/tresoldi/merkmal/blob/master/docs/guide/overview.md),
the [feature geometry method](https://github.com/tresoldi/merkmal/blob/master/docs/method/geometry.md),
and the [empirical evaluation](https://github.com/tresoldi/merkmal/blob/master/docs/method/evaluation.md)
in the [repository](https://github.com/tresoldi/merkmal).

## Installation

```sh
python -m pip install merkmal
```

Requires CPython 3.12 or later. Pre-built `cp312-abi3` wheels are published for
Linux (`x86_64` and `aarch64`); other platforms compile the bundled C99 sources
directly during `pip install` using any standard C compiler. To build without
the share-alike (PHOIBLE) and non-commercial (P-base) tables, install from
source with `MERKMAL_DATA_PROFILE=cc-by pip install --no-binary merkmal merkmal`
(see [Installation](https://github.com/tresoldi/merkmal/blob/master/docs/guide/installation.md#data-profiles)).

## Built-in feature systems

Every function taking `system` defaults to `merkmal.DEFAULT_SYSTEM`
(`"distinctive"`):

| System | Kind | Basis | Source |
| --- | --- | --- | --- |
| `distinctive` (default) | categorical | 57 scalar dimensions + 10 ordered scales over CLTS articulatory descriptions | CLTS 2.3.1 |
| `descriptive` | categorical | Direct CLTS articulatory labels scored on geometry leaves, scales and node groups | CLTS 2.3.1 |
| `phoible` | valued | 38 binary features (`+`, `-`, `0`, `?`) over 3,142 segments | PHOIBLE 2.0 |
| `pbase-spe` | valued | 25 SPE features (Chomsky and Halle 1968) | P-base |
| `pbase-jfh` | valued | 15 acoustic features (Jakobson, Fant and Halle 1952) | P-base |
| `pbase-hc`, `pbase-uftc` | valued | Halle and Clements (1983) and Unified Feature Theory (Clements and Hume 1995) | P-base |

Use `distinctive` for sequence alignment, cognate scoring and general phonetic
clustering, `descriptive` when inspecting articulatory labels, and the valued
systems when comparing feature theories (around one third of strict triples
`d(A, B) < d(A, C)` differ across the seven systems). Distances measure phonetic
dissimilarity under a feature description, not the historical probability of a
sound change.

## Quick start

```python
import merkmal

merkmal.list_systems()                            # ['descriptive', 'distinctive', ...]
merkmal.get_features("pʰ")                        # frozenset({'aspirated', 'bilabial', ...})
merkmal.distance("p", "b")                        # 0.125
merkmal.distance("p", "b", system="phoible")      # 0.040540540540540536
merkmal.distance_with_coverage("ai", "au")        # Comparison(score=0.09189..., coverage=1.0, comparability='ok')
merkmal.segment_ipa_merged("tʰoŋ⁵⁵")              # ['tʰ', 'o⁵⁵', 'ŋ']
```

## API overview

| Function or class | Result |
| --- | --- |
| `list_systems()` | Names of the available systems |
| `inventory(system=)` | Listed graphemes of a system's base table, in inventory order |
| `get_features(g, system=)` | `frozenset[str]` of feature labels (`name=state` in valued systems) |
| `is_segment(g, system=)` | `bool`: whether the system recognizes `g` (never raises on unknown input) |
| `diagnose(g, system=)` | Dict explaining a refusal: `ok`, `status`, `valid_prefix`, `offset`, `offending` |
| `distance(a, b, system=, node_weights=)` | Dissimilarity of two graphemes in `[0, 1]` |
| `distance_with_coverage(a, b, system=, node_weights=)` | `Comparison(score, coverage, comparability)` (alias `compatibility_dissimilarity`) |
| `feature_vector(g, system=)`, `vector_labels(system=)` | Fixed-width `tuple[float, ...]` for `g`, and its column names |
| `fixed_space_distance(a, b, system=)` | Mean absolute difference between two fixed-width feature vectors |
| `feature_distance(f1, f2)` | Integer edge count between two features in the geometry tree |
| `sound_distance(features_a, features_b, node_weights=)` | Geometry distance between two caller-supplied feature sets |
| `normalize(g)` | NFC form of `g` with IPA rewrites (`ʧ` -> `tʃ`); for display, not required before lookup |
| `ascii_chao_digits(text)` | Rewrites ASCII `0`–`5` to superscript Chao digits (`ma55` -> `ma⁵⁵`) |
| `segment_ipa(text)` | Orthographic split at every base letter not joined by a tie bar |
| `system_segment_ipa(text, system=)` | Longest-match split against `system`'s inventory and synthesis rules |
| `merge_tone_digits(segments)`, `segment_ipa_merged(text)` | Attaches Chao pitch runs or tone bars to the preceding syllabic segment |
| `split_tone(segment)` | Splits `"o⁵⁵"` into `("o", "⁵⁵")` (`(base, None)` when untoned) |
| `system_fingerprint(system=)` | `(payload, sha256)` identifying the system's data, geometry and scorer |
| `operation_fingerprint(...)` | `(payload, sha256)` combining `system_fingerprint` with call settings |
| `AbstractSegment`, `BundleComparison` | Underspecified feature bundles with exact `[minimum, maximum]` distance intervals |
| `Registry` | Isolated registry holding built-in systems plus runtime `@type categorical` or `@type valued` models |
| `load_geometry(path)`, `geometry_distance(...)` | Experimental scoring under a custom JSON geometry |

Module constants: `DEFAULT_SYSTEM` (`"distinctive"`), `UNICODE_VERSION` (the
compiled-in Unicode normalization version, `"16.0.0"`), and `DATA_PROFILE`
(`"full"` or `"cc-by"`).

## Common workflows

### Screening transcriptions and diagnosing refusals

Unknown systems raise `KeyError`. Unreadable graphemes raise `ValueError`, with
two narrower subclasses so wordlist pipelines can separate source markup from
malformed notation and genuinely missing segments:

- `SourceMarkerError` (`ValueError`, `NativeError`): CLDF/CLTS editorial markers
  (`<?>`, `<<...>>`, `+`, `_`, `#`) — gaps or boundaries in the source, not
  missing sounds;
- `ParseError` (`ValueError`, `NativeError`): malformed tone runs (`a¹²³⁴`),
  tripled length marks, repeated diacritics (`tʰʰ`), or invalid runtime model
  syntax.

When auditing a wordlist without raising exceptions, combine `is_segment()` with
`diagnose()`:

```python
for token in ["tʰ", "pʰ1", "ɑ̠̠", "<?>"]:
    if not merkmal.is_segment(token):
        info = merkmal.diagnose(token)
        print(token, "->", info["status"], "prefix:", info["valid_prefix"], "at:", info["offending"])
# pʰ1 -> unknown grapheme prefix: pʰ at: 1
# ɑ̠̠ -> parse error prefix: ɑ̠ at: ̠
# <?> -> source markup, not a sound prefix:  at: <
```

In categorical systems, unlisted sequences are derived where possible: modified
bases (`aːi³³`, `kʷʰ`), precomposed orthography (`ñ`), diphthongs (`ai` ->
`'diphthong'`, `'n1-open'`, `'n2-close'`, `'move-height-open-close'`), consonant
clusters (`st`), and homorganic or superscript prenasalized stops (`mb`, `ᵐb`,
`ᵑg`). Valued systems derive a diacritic only if minimal pairs in their own
table establish its effect (`kˀ` resolves in `distinctive`, raises in
`pbase-spe`).

### Distances, coverage, and weight presets

Valued tables skip dimensions where either segment is inapplicable (`0`) or
unknown (`?`, `.`). Always inspect `distance_with_coverage()` when comparing
across valued systems or across tonal tiers:

```python
# In PHOIBLE, diphthongs leave changing trajectories unspecified:
cmp = merkmal.distance_with_coverage("ai", "au", system="phoible")
# Comparison(score=0.0, coverage=0.6052631578947368, comparability='ok')

# Bare tone against a segment is cross-tier, never compared on segmental features:
merkmal.distance_with_coverage("˥", "a")
# Comparison(score=1.0, coverage=0.0, comparability='cross-tier')
```

`node_weights` adjusts branch weights in the geometry (`"ignore-tone"`,
`"ignore-length"`, `"ignore-secondary"`, `"ignore-prosodic"`, `"segmental"`,
`"tone-heavy"`, `"tone-only"`, `"flat"`):

```python
merkmal.distance("a⁵⁵", "a¹¹")                                 # 0.1809...
merkmal.distance("a⁵⁵", "a¹¹", node_weights="ignore-tone")     # 0.0
```

### Numeric feature vectors

`feature_vector()` returns a `soundvectors`-encoded `tuple[float, ...]` whose
columns (`vector_labels()`) match the active scorer's dimensions: `+1.0`
present, `-1.0` applicable and absent, `0.0` inapplicable, `math.nan` unknown
(`?` in valued tables), and `(0, 1]` for ordered scales (`i / n`). Two graphemes
have equal vectors if and only if their distance is `0.0`.

```python
labels = merkmal.vector_labels(system="phoible")
vec = merkmal.feature_vector("p", system="phoible")
dict(zip(labels[:4], vec[:4], strict=True))
# {'advancedTongueRoot': 0.0, 'anterior': 0.0, 'approximant': -1.0, 'back': 0.0}
```

### Underspecified and reconstructed segments (`AbstractSegment`)

`AbstractSegment` represents an archiphoneme or proto-segment as a bundle of
allowed values per dimension rather than forcing a single stand-in letter
([abstract-segments.md](https://github.com/tresoldi/merkmal/blob/master/docs/method/abstract-segments.md)):

```python
# Smallest bundle compatible with {m, n, ŋ}: place columns carry their union
proto_nasal = merkmal.AbstractSegment.covering(["m", "n", "ŋ"])
proto_nasal.compatible("m")                    # True
proto_nasal.compatible("p")                    # False

# Or start from a concrete grapheme and relax specific dimensions:
proto_stop = merkmal.AbstractSegment.from_grapheme("t").with_cells(voice="?")
res = proto_stop.compare("d")
# BundleComparison(distance=0.0, coverage=0.897..., minimum=0.0, maximum=0.1027..., why='ok')

res_s = proto_nasal.compare("s")
# BundleComparison(distance=0.625, coverage=0.670..., minimum=0.4712..., maximum=0.6800..., why='ok')
```

`res.minimum` and `res.maximum` are the exact extremes of the coverage-weighted
distance across all valid completions of the unspecified cells.

### Custom runtime models (`Registry`)

`Registry` holds the built-in systems and accepts caller-defined `@type
categorical` and `@type valued` models in the
[runtime model format](https://github.com/tresoldi/merkmal/blob/master/docs/guide/runtime-model-format.md):

```python
registry = merkmal.Registry()
registry.add_model_text(
    """
    @format_version 1
    @model mini-spe
    @type valued
    @feature voice Laryngeal
    @feature labial Labial
    grapheme p voice=- labial=+
    grapheme b voice=+ labial=+
    grapheme t voice=- labial=-
    """,
    manifest={
        "name": "mini-spe",
        "version": "1.0.0",
        "source": "Example table",
        "interpretation": "phonemic",
        "license": "CC-BY-4.0",
    },
)
registry.distance("p", "b", system="mini-spe")  # 0.6 (Laryngeal 1/2 vs. Labial 1/3)
```

`Registry` mirrors the module-level API (`list_systems`, `inventory`,
`get_features`, `is_segment`, `diagnose`, `distance`, `distance_with_coverage`,
`feature_vector`, `vector_labels`, `fixed_space_distance`, `system_segment_ipa`,
`system_fingerprint`, `operation_fingerprint`, `model_manifest`), and
`AbstractSegment(..., registry=registry)` builds bundles over custom systems.
Manifest validation runs before native registration, so a malformed manifest
never leaves a model half-registered.

### Provenance and caching

Key any cached distance table or published benchmark on
`operation_fingerprint()` (plus `merkmal.UNICODE_VERSION`), never on the package
version alone:

```python
payload, digest = merkmal.operation_fingerprint(
    system="distinctive",
    node_weights="ignore-tone",
    tokenization_policy="system",
)
```

For language-indexed PHOIBLE phoneme inventories, segment frequencies with
explicit sample-bias summaries, and inventory-to-inventory comparisons, see the
companion package
[`merkmal-typology`](https://github.com/tresoldi/merkmal/blob/master/python/typology/README.md).

## Command line

Installing `merkmal` provides the `merkmal` executable (also runnable as
`python -m merkmal`):

```sh
merkmal systems
merkmal features pʰ
merkmal --system phoible features bʰ
merkmal diagnose pʰ "pʰ̳zz" "<?>"
merkmal distance ai au
merkmal distance --node-weights ignore-tone a¹ a⁵
merkmal normalize ʧ
merkmal segment "tʃa pʰa"
merkmal --system distinctive segment "tʃa kpa"
merkmal fingerprint --node-weights ignore-tone
```

- `--system` (`-s`) precedes the subcommand. On `segment`, naming `--system`
  switches from orthographic `segment_ipa` to longest-match
  `system_segment_ipa`; `normalize` is system-independent and refuses `--system`.
- `--node-weights` (`-w`) selects a geometry preset on `distance` and
  `fingerprint` (accepted before or after the subcommand).
- `diagnose` and `segment` read newline-delimited input from standard input when
  given `-` or when piped with no positional text.
- Human-readable default output may evolve; scripts should request `--json` (one
  JSON object), `--jsonl` (one JSON object per record), or `--tsv` (header row +
  tab-separated records with `\\`, `\t`, `\n` escaped):

| Subcommand | `--json` object | `--jsonl` / `--tsv` fields |
| --- | --- | --- |
| `systems` | `{"systems": [...]}` | `system` |
| `features` | `{"system", "grapheme", "features": [...]}` | `grapheme`, `feature` |
| `diagnose` | `{"system", "diagnoses": [...]}` | `system`, `grapheme`, `ok`, `status`, `valid_prefix`, `offset`, `offending` |
| `distance` | `{"system", "a", "b", "distance", "coverage", "comparability"}` (+ `"node_weights"` when set) | same fields |
| `normalize` | `{"input", "normalized"}` | `input`, `normalized` |
| `segment` | `{"text", "segments": [...]}` (+ `"system"` when set) | `index`, `segment` |
| `fingerprint` | `{"system", "sha256", "payload"}` (+ `"node_weights"` when set) | same fields |

Exit status is `0` on success, `1` on data errors (unknown system or unreadable
grapheme, written to `stderr` with `stdout` empty), and `2` on CLI usage errors.

## Development

```sh
python -m pip install -e ".[dev]"
python -m pytest python/tests -q
python -m build --sdist --wheel
```

## License and citation

Code is MIT (`LICENSE`). Because the compiled extension embeds upstream feature
tables with attribution, share-alike and non-commercial terms, the distribution
is licensed as `MIT AND CC-BY-4.0 AND CC-BY-SA-3.0 AND CC-BY-NC-SA-4.0`. Cite
both `merkmal` ([`CITATION.cff`](https://github.com/tresoldi/merkmal/blob/master/CITATION.cff))
and the upstream source of each feature system used; full attributions are in
the bundled `NOTICE` file.
