Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 52 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ censored observations.
Fit one dataset directly:

```python
from ecoff_fitter import ECOFFitter
from ecoff_fitter import IntervalRegressionFitter

fitter = ECOFFitter(input="demo_files/censored.txt", distributions=1)
fitter = IntervalRegressionFitter(input="demo_files/censored.txt", distributions=1)
result = fitter.generate(percentile=99)
print(result)
```
Expand All @@ -99,6 +99,7 @@ from ecoff_fitter import run_ecoff_analysis
run = run_ecoff_analysis(
"demo_files/multi_assay.txt",
distributions=2,
range_search="mixture",
fit_individual=True,
percentile=99,
)
Expand All @@ -108,8 +109,41 @@ for assay, report in run.individual_reports.items():
print(report.to_text(label=assay))
```

Set `distributions="auto"` in `run_ecoff_analysis` to select a component
count by the AIC or BIC criterion. `max_distributions` sets the largest count
Choose the fitting method and WT selector independently. The two count-based
selectors can use either least squares or interval regression; mixture
selection is available with interval regression only:

```python
run = run_ecoff_analysis(
"demo_files/multi_assay.txt",
fitter="interval_regression",
range_search="first-local-peak",
fit_individual=True,
)

print(run.global_report.to_text(verbose=True))
```

`range_search` accepts `"largest-bin"`, `"first-local-peak"`, or `"mixture"`.
The first-local-peak selector uses the fixed 19-bin log2 MIC grid and requires
`dilution_factor=2`. The largest-bin selector uses the highest-frequency active
bin; `park_from_mic` can exclude higher bins before selection. Count-based
selectors fit one wild-type range. Mixture selection uses the interval-regression
mixture model and supports fixed or automatically selected component counts.

For example, select the largest active bin and fit it with interval regression:

```python
run = run_ecoff_analysis(
data,
fitter="interval_regression",
range_search="largest-bin",
park_from_mic=32,
)
```

Set `range_search="mixture"` and `distributions="auto"` in
`run_ecoff_analysis` to select a component count by the AIC or BIC criterion. `max_distributions` sets the largest count
to consider; `criterion`, `min_delta`, `min_pi`, and `min_separation` control
the selection checks. The selected aggregate count is available as
`run.selected_k`.
Expand All @@ -122,7 +156,9 @@ or more assay columns:
```bash
ecoff-fitter \
--input demo_files/multi_assay.txt \
--distributions 2 \
--fitter interval_regression \
--range_search largest-bin \
--park_from_mic 32 \
--percentile 99 \
--fit_individual \
--outfile demo_files/output.pdf
Expand All @@ -134,13 +170,19 @@ available as `python -m ecoff_fitter`.
| Option | Default | Description |
| --- | --- | --- |
| `--input INPUT` | Required | Input MIC dataset. |
| `--params PARAMS` | None | YAML or TXT parameter file; its values override corresponding command-line values. |
| `--fitter METHOD` | `interval_regression` | `least_squares` or `interval_regression`. |
| `--range_search METHOD` | None | `largest-bin`, `first-local-peak`, or `mixture`. |
| `--params PARAMS` | None | YAML or TXT parameter file; file values override matching options. |
| `--dilution_factor N` | `2` | Ratio between adjacent MIC dilution steps. |
| `--distributions K` | `1` | Number of normal components to fit. The CLI accepts an integer; automatic selection is available in the Python workflow API. |
| `--boundary_support N` | `1` | Number of dilution steps used to extend censoring bounds. Use `None` in a parameter file for unbounded tails. |
| `--percentile P` | `99.0` | Percentile used to calculate the ECOFF; must be between 0 and 100. |
| `--fit_individual` | Off | Fit each assay column as well as the aggregate observations. |
| `--distributions K` | `1` | Number of normal components to fit. |
| `--boundary_support N` | `1` | Number of dilution steps used to extend censoring bounds. |
| `--percentile P` | `99.0` | Percentile used to calculate the ECOFF. |
| `--fit_individual` | Off | Fit each assay column as well as aggregate observations. |
| `--density` | Off | Plot probability density instead of counts. |
| `--detection_level P` | `10.0` | Minimum eligible local-peak size as a percentage of observations. |
| `--park_from_mic MIC` | None | Exclude this MIC and higher bins before largest-bin selection. |
| `--cumulative` / `--no-cumulative` | On | Use cumulative counts or per-bin frequencies in least-squares range fitting. |
| `--first_best` | Off | Stop range search after its score starts increasing. |
| `--outfile PATH` | None | Write a text report (`.txt`) or PDF report (`.pdf`). |
| `--verbose` | Off | Include model details in printed text output. |

Expand Down
42 changes: 19 additions & 23 deletions src/ecoff_fitter/__init__.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,26 @@
"""
ECOFF Fitter — Estimate epidemiological cutoff values (ECOFFs)
using interval regression on MIC (Minimum Inhibitory Concentration) data.
"""ECOFF analysis tools for MIC data.

Single-fit API
--------------
from ecoff_fitter import ECOFFitter
Direct interval-regression fitting:

fitter = ECOFFitter(input="mic_data.csv")
result = fitter.generate(percentile=99)
from ecoff_fitter import IntervalRegressionFitter

Multi-fit / workflow API
------------------------
from ecoff_fitter import run_ecoff_analysis
fitter = IntervalRegressionFitter(input="mic_data.csv")
result = fitter.generate(percentile=99)

run = run_ecoff_analysis(
"mic_data.csv",
fit_individual=True,
)
Multi-assay workflow:

print(run.global_report.to_text())
from ecoff_fitter import run_ecoff_analysis

CLI
---
python -m ecoff_fitter --input mic_data.csv
run = run_ecoff_analysis("mic_data.csv", fitter="interval_regression")
"""

from importlib.metadata import PackageNotFoundError, version

from .core import ECOFFitter
from .intervals import IntervalRegressionFitter
from .workflow import ECOFFRun, run_ecoff_analysis

__all__ = [
"ECOFFitter",
"IntervalRegressionFitter",
"run_ecoff_analysis",
"ECOFFRun",
]
Expand All @@ -43,11 +32,18 @@


def main() -> None:
"""Entry point for `python -m ecoff_fitter`."""
"""Run the command-line entry point.


Returns:
None.

Args:
None."""
from .cli import main as cli_main

cli_main()


if __name__ == "__main__":
main()
main()
118 changes: 94 additions & 24 deletions src/ecoff_fitter/cli.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,50 @@
#!/usr/bin/env python3
"""
Command-line interface for ECOFFitter.
Command-line interface for ECOFF analysis.

Usage example:
python -m ecoff_fitter.cli --input data/mic_data.csv --distributions 2 --percentile 99
"""

import argparse
from typing import Any, List, Optional
from ecoff_fitter import ECOFFitter
from typing import List, Optional
from ecoff_fitter.report import GenerateReport, CombinedReport
from ecoff_fitter.defence import validate_output_path
from ecoff_fitter.utils import read_multi_obs_input
from unittest.mock import MagicMock, patch
from ecoff_fitter.workflow import run_ecoff_analysis


def _parse_optional_int(value: str) -> int | None:
"""Parse a non-negative integer or the word ``none``.

Args:
value (str): Text supplied for an optional integer argument.

Returns:
int | None: Parsed integer, or None when disabled.
"""
if value.strip().lower() == "none":
return None
try:
parsed = int(value)
except ValueError as error:
raise argparse.ArgumentTypeError("must be an integer or 'none'") from error
if parsed < 0:
raise argparse.ArgumentTypeError("must be a non-negative integer or 'none'")
return parsed


def build_parser() -> argparse.ArgumentParser:
"""Create and configure the command-line argument parser."""
"""Create and configure the command-line argument parser.


Returns:
argparse.ArgumentParser: Configured command-line parser.

Args:
None."""
parser = argparse.ArgumentParser(
prog="ecoff_fitter",
description="Estimate epidemiological cutoff values (ECOFFs) using interval regression on MIC data.",
description="Estimate epidemiological cutoff values (ECOFFs) from MIC data.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)

Expand All @@ -32,12 +56,22 @@ def build_parser() -> argparse.ArgumentParser:
"with columns 'MIC' and assay name."
),
)
parser.add_argument(
"--fitter",
choices=("least_squares", "interval_regression"),
help="Model fitting method: least squares or interval regression.",
)
parser.add_argument(
"--range_search",
choices=("largest-bin", "first-local-peak", "mixture"),
help="Wild-type selector: largest bin, first local peak, or mixture model.",
)
parser.add_argument(
"--params",
help=(
"Optional path to a parameter file (YAML, TXT, or key=value list) "
"defining dilution_factor, distributions, and boundary_support. "
"Overrides manual CLI options if provided."
"Optional YAML or TXT parameter file for dilution, component count, "
"censoring support, percentile, and range-search settings. File "
"values override matching options."
),
)
parser.add_argument(
Expand All @@ -50,19 +84,45 @@ def build_parser() -> argparse.ArgumentParser:
"--distributions",
type=int,
default=1,
help="Number of normal components to fit.",
help="Number of normal components for interval regression or mixture selection.",
)
parser.add_argument(
"--boundary_support",
type=int,
type=_parse_optional_int,
default=1,
help="boundary support for censored data handling (None to disable).",
help="Number of dilution steps used as support for censored observations.",
)
parser.add_argument(
"--density",
action="store_true",
help="Plot MIC distribution as density rather than counts.",
)
parser.add_argument(
"--detection_level",
type=float,
default=10.0,
help="Minimum eligible local-peak size as a percentage of observations.",
)
parser.add_argument(
"--park_from_mic",
type=float,
help=(
"Exclude this MIC and higher bins before largest-bin selection."
),
)
parser.add_argument(
"--cumulative",
action=argparse.BooleanOptionalAction,
default=True,
help=(
"Fit cumulative frequencies; use --no-cumulative for per-bin frequencies."
),
)
parser.add_argument(
"--first_best",
action="store_true",
help="Stop range search after its score starts increasing.",
)
parser.add_argument(
"--percentile",
type=float,
Expand Down Expand Up @@ -93,21 +153,31 @@ def main(argv: Optional[List[str]] = None) -> None:
Args:
argv (Optional[List[str]]): Argument list to parse; defaults to the
process command line.
"""

Returns:
None."""
parser = build_parser()
args = parser.parse_args(argv)
if args.range_search == "mixture" and args.distributions < 2:
parser.error("--range_search mixture requires --distributions of at least 2")

try:
run = run_ecoff_analysis(
args.input,
params=args.params,
dilution_factor=args.dilution_factor,
distributions=args.distributions,
boundary_support=args.boundary_support,
percentile=args.percentile,
fit_individual=args.fit_individual,
density=args.density,
)
workflow_args = {
"params": args.params,
"dilution_factor": args.dilution_factor,
"distributions": args.distributions,
"boundary_support": args.boundary_support,
"percentile": args.percentile,
"fit_individual": args.fit_individual,
"density": args.density,
"fitter": args.fitter or "interval_regression",
"range_search": args.range_search,
"detection_level": args.detection_level,
"cumulative": args.cumulative,
"first_best": args.first_best,
"park_from_mic": args.park_from_mic,
}
run = run_ecoff_analysis(args.input, **workflow_args)

text = "\n\nECOFF RESULTS\n=====================================\n\n"
text += run.global_report.to_text("GLOBAL FIT", verbose=args.verbose)
Expand Down
Loading
Loading