diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml old mode 100644 new mode 100755 diff --git a/.github/workflows/gui-build.yml b/.github/workflows/gui-build.yml old mode 100644 new mode 100755 diff --git a/.github/workflows/mypy.yml b/.github/workflows/mypy.yml old mode 100644 new mode 100755 diff --git a/.github/workflows/pypi.yaml b/.github/workflows/pypi.yaml old mode 100644 new mode 100755 diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 2668edc..cd9da3b --- a/README.md +++ b/README.md @@ -2,64 +2,33 @@ # ECOFFitter -**ECOFFitter** is a Python tool for fitting interval regression models -to censored Minimum Inhibitory Concentration (MIC) data.\ -It provides a command-line interface (CLI) to process input MIC -distributions, estimate epidemiological cutoffs (ECOFFs), and generate -model outputs and diagnostic plots. +**ECOFFitter** fits interval-censored normal models to Minimum Inhibitory +Concentration (MIC) observations and estimates epidemiological cutoff values +(ECOFFs). It supports a single distribution, a finite mixture, and automatic +selection of the number of mixture components. Text and PDF reports can include +aggregate results and optional per-assay results. -The package supports: +Demo input files are in `demo_files/`. -- interval-censored, left-censored, - right-censored, and uncensored MIC data -- mixed datasets with variable - censoring -- automated output files (PDF reports, text outputs, plots) -- configuration via parameter files +## Installation -Demo input files are provided in `demo_files/` to illustrate basic use. - ---- - -## 🛠 Installation - -### Install from source - -Assuming in project directory (after git cloning): +Install from a local checkout: ```bash pip install -e . ``` ---- - -## 📥 Input - -### 1. MIC Data Input File - -The MIC dataset describes the distribution of Minimum Inhibitory Concentration (MIC) values and the number of isolates observed at each dilution. +## Input data -Alternatively, an array or single-column file of observed MICs can be supplied (ie 1 row per sample). +Input can be a CSV, TSV, TXT, XLSX, or XLS file, or a DataFrame, array-like +sequence, or mapping when using the Python API. MIC values may be exact (for +example `0.25`), left-censored (such as `<=0.125`), or right-censored (such as +`>64`). Ratio values such as `1/2` are accepted; the numerator is used as the +MIC value. -It must be a **tabular file** in one of these formats: - -- `.csv` -- `.tsv` -- `.txt` -- `.xlsx` / `.xls` - -#### Required columns - -| Column | Type | Description | -| -------------- | --------------- | ---------------------------------------------------------------------------------------------------------- | -| `MIC` | float or string | MIC dilution (e.g., `0.125`, `0.25`, `1`, `2`, …). Can include censored values such as `<=0.125` or `>64`. | -| `observations` | integer | Number of isolates observed at that MIC dilution. | - -or - -A single column/array of observed MIC values. - -#### Example (from `demo_files/censored.txt`) +A single-column input contains one MIC per row. Duplicate MIC values are +aggregated into counts. A canonical single-fit table has `MIC` and +`observations` columns: ```text MIC observations @@ -75,22 +44,21 @@ MIC observations >8 2196 ``` -- censored values (e.g >16) are automatically detected and handled - -### 2. Parameter File (`--params`) +For aggregate and per-assay analyses, use a table with a `MIC` column and one +or more assay columns. Counts across assay columns are summed for the aggregate +fit. Each assay is fitted separately when individual fits are enabled. -This is an **optional** configuration file (YAML, TXT, or `key=value` list) that overrides CLI arguments. +Supported input extensions are `.csv`, `.tsv`, `.txt`, `.xlsx`, and `.xls`. +For Excel files, the first worksheet is used unless a sheet is selected through +the Python API. -Typical fields include: +## Configuration -| Key | Description | -| ------------------ | ----------------------------------------------------------------------------- | -| `dilution_factor` | Fold-change between MIC dilutions (e.g., `2`). | -| `distributions` | Number of Gaussian mixture components. | -| `boundary_support` | How many dilution steps to extend upper and/or lower tails for censored data. | -| `percentile` | Percentile used to compute the ECOFF (e.g., `99`). | +The optional `--params` file can be YAML or TXT (`key=value`). Values in this +file override the corresponding manually supplied parameters. Supported keys +are `dilution_factor`, `distributions`, `boundary_support`, and `percentile`. -#### Example (`demo_files/params.txt`) +TXT example (`demo_files/params.txt`): ```text dilution_factor=2 @@ -99,80 +67,90 @@ boundary_support=1 percentile=99 ``` -or YAML: +YAML example: -```text +```yaml dilution_factor: 2 distributions: 2 boundary_support: 1 percentile: 99 ``` -## 📤 Output - -The tool produces one or more of the following: - ---- - -### 1. Text Output +Set `boundary_support` to `None` in a parameter file to use unbounded tails for +censored observations. -If `--outfile` ends in `.txt`, the tool writes: +## Python API -- ECOFF estimate -- fitted mean & variance (per component) -- mixture weights (if multiple distributions) +Fit one dataset directly: -### 2. PDF Report +```python +from ecoff_fitter import ECOFFitter -If `--outfile` ends in `.pdf`, the tool writes: - -- histogram of observed MICs -- fitted distribution curve(s) -- ECOFF location marker -- fitted mean & variance (per component) -- mixture weights (if multiple distributions) +fitter = ECOFFitter(input="demo_files/censored.txt", distributions=1) +result = fitter.generate(percentile=99) +print(result) +``` -## 🚀 Command-Line Usage +Run the aggregate and optional per-assay workflow: -Once installed, you can call the CLI. +```python +from ecoff_fitter import run_ecoff_analysis -Example using demo files: +run = run_ecoff_analysis( + "demo_files/multi_assay.txt", + distributions=2, + fit_individual=True, + percentile=99, +) -```bash -ecoff-fitter --input demo_files/censored.txt --params demo_files/params.txt --outfile demo_files/output.txt +print(run.global_report.to_text()) +for assay, report in run.individual_reports.items(): + print(report.to_text(label=assay)) ``` -Instead of using a parameter file, you can also specify parameters directly. +Set `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`. -Usage: +## Command-line usage + +The CLI accepts a dataset with a `MIC` column and either `observations` or one +or more assay columns: ```bash -ecoff-fitter [-h] --input INPUT [--params PARAMS] -[--dilution_factor DILUTION_FACTOR] -[--distributions DISTRIBUTIONS] [--boundary_support BOUNDARY_SUPPORT] -[--percentile PERCENTILE] [--outfile OUTFILE] [--verbose] +ecoff-fitter \ + --input demo_files/multi_assay.txt \ + --distributions 2 \ + --percentile 99 \ + --fit_individual \ + --outfile demo_files/output.pdf ``` ---- - -## ⚙️ CLI Parameters - -### CLI Options - -| Option | Argument | Description | Default | -| -------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | -| `-h`, `--help` | — | Show help message and exit. | — | -| `--input` | `INPUT` | Path to the input MIC dataset (CSV, TSV, XLSX, or XLS). Must contain columns `MIC` and `observations`. | `None` | -| `--params` | `PARAMS` | Optional parameter file (`YAML`, `TXT`, or `key=value` list). Defines `dilution_factor`, `distributions`, and `boundary_support`. Overrides CLI flags if provided. | `None` | -| `--dilution_factor` | `DILUTION_FACTOR` | Dilution factor | `2` | -| `--distributions` | `DISTRIBUTIONS` | Number of Gaussian mixture components to fit. | `1` | -| `--boundary_support` | `boundary_support` | Extra upper- and lower-dilution steps for censored MICs (set to `None` to disable). | `1` | -| `--percentile` | `PERCENTILE` | Percentile used to compute the ECOFF (0–100). | `99.0` | -| `--outfile` | `OUTFILE` | Path to save ECOFF results (`.txt` or `.pdf`). | `None` | -| `--verbose` | — | Print detailed model information and parameters. | `False` | - ---- - -## 📄 License +Run `ecoff-fitter --help` for the complete option list. The same CLI is +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. | +| `--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. | +| `--density` | Off | Plot probability density instead of counts. | +| `--outfile PATH` | None | Write a text report (`.txt`) or PDF report (`.pdf`). | +| `--verbose` | Off | Include model details in printed text output. | + +## Output + +The results are printed to the terminal. With `--outfile`, the CLI also writes a +text or PDF report. PDF reports show observed MIC intervals, fitted component +curves, and the ECOFF marker. When per-assay fits are enabled, the report +contains the aggregate fit and individual assay fits. + +## License MIT License. diff --git a/demo_files/censored.txt b/demo_files/censored.txt old mode 100644 new mode 100755 index d04ffcc..2306cd8 --- a/demo_files/censored.txt +++ b/demo_files/censored.txt @@ -1,14 +1,14 @@ MIC x1 -<=0.03 89 -0.06 223 -0.12 346 -0.25 150 -0.5 60 -1 2 -2 3 -4 12 -8 55 ->8 67 +<=0.03 593 +0.06 23 +0.12 4 +0.25 8 +0.5 5 +1 6 +2 2 +4 2 +8 1 +>8 0 diff --git a/demo_files/demo_input.xlsx b/demo_files/demo_input.xlsx old mode 100644 new mode 100755 diff --git a/demo_files/multi_assay.txt b/demo_files/multi_assay.txt old mode 100644 new mode 100755 diff --git a/demo_files/output.pdf b/demo_files/output.pdf old mode 100644 new mode 100755 index acee096..9f45eca Binary files a/demo_files/output.pdf and b/demo_files/output.pdf differ diff --git a/demo_files/output.txt b/demo_files/output.txt old mode 100644 new mode 100755 diff --git a/demo_files/params.txt b/demo_files/params.txt old mode 100644 new mode 100755 diff --git a/demo_files/uncensored.txt b/demo_files/uncensored.txt old mode 100644 new mode 100755 diff --git a/demo_files/unimodal.txt b/demo_files/unimodal.txt old mode 100644 new mode 100755 diff --git a/env.yml b/env.yml old mode 100644 new mode 100755 diff --git a/gui.py b/gui.py old mode 100644 new mode 100755 index 92791a5..cd99b10 --- a/gui.py +++ b/gui.py @@ -1,14 +1,12 @@ import tkinter as tk -from tkinter import filedialog, messagebox, ttk +from tkinter import filedialog, messagebox import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg -from ecoff_fitter import ECOFFitter -from ecoff_fitter.report import GenerateReport, CombinedReport +from ecoff_fitter.workflow import run_ecoff_analysis +from ecoff_fitter.report import CombinedReport from ecoff_fitter.defence import validate_output_path from ecoff_fitter.graphs import plot_mic_distribution -from ecoff_fitter.utils import read_multi_obs_input - class ECOFFGUI: def __init__(self, root): @@ -35,7 +33,7 @@ def __init__(self, root): options_frame = tk.Frame(root) options_frame.pack(pady=5, anchor="w") - tk.Label(options_frame, text="Distributions:").pack(side="left") + tk.Label(options_frame, text="Populations:").pack(side="left") self.dist_entry = tk.Entry(options_frame, width=5) self.dist_entry.insert(0, "1") self.dist_entry.pack(side="left", padx=10) @@ -45,7 +43,7 @@ def __init__(self, root): self.dil_entry.insert(0, "2") self.dil_entry.pack(side="left", padx=10) - tk.Label(options_frame, text="Boundary intervals:").pack(side="left") + tk.Label(options_frame, text="Truncation support:").pack(side="left") self.tails_entry = tk.Entry(options_frame, width=5) self.tails_entry.insert(0, "1") self.tails_entry.pack(side="left", padx=10) @@ -64,6 +62,20 @@ def __init__(self, root): variable=self.verbose_var, ).pack(side="left") + self.density_var = tk.BooleanVar(value=False) + tk.Checkbutton( + verbose_frame, + text="plot density", + variable=self.density_var, + ).pack(side="left", padx=10) + + + self.fit_individual_var = tk.BooleanVar(value=False) + tk.Checkbutton( + verbose_frame, + text="fit individual populations", + variable=self.fit_individual_var, + ).pack(side="left", padx=10) # OUTPUT FILE output_frame = tk.Frame(root) @@ -136,124 +148,96 @@ def run_ecoff(self): percentile = float(self.percentile_entry.get()) outfile = self.output_entry.get() verbose = self.verbose_var.get() + density = self.density_var.get() if not input_file: messagebox.showerror("Error", "You must select an input MIC data file.") return try: - - data_dict = read_multi_obs_input(input_file) - df_global = data_dict["global"] - df_individual = data_dict["individual"] - - # GLOBAL FIT - global_fitter = ECOFFitter( - input=df_global, + run = run_ecoff_analysis( + input_file, params=params_file, distributions=distributions, - boundary_support=tails, dilution_factor=dilution_factor, + boundary_support=tails, + percentile=percentile, + fit_individual=self.fit_individual_var.get(), + density=density, ) - global_result = global_fitter.generate(percentile=percentile) - - # INDIVIDUAL FITS - individual_results = {} - for col, subdf in df_individual.items(): - fitter = ECOFFitter( - input=subdf, - params=params_file, - distributions=distributions, - boundary_support=tails, - dilution_factor=dilution_factor, - ) - result = fitter.generate(percentile=percentile) - individual_results[col] = (fitter, result) - text = "ECOFF RESULTS\n=====================================\n\n" + text += run.global_report.to_text("GLOBAL FIT", verbose=verbose) - global_report = GenerateReport.from_fitter(global_fitter, global_result) - - if len(individual_results) > 1: - text += global_report.to_text("GLOBAL FIT", verbose=verbose) + if run.individual_reports: text += "\nINDIVIDUAL FITS:\n-------------------------------------\n" - - # Individual fits - for name, (fitter, result) in individual_results.items(): - rep = GenerateReport.from_fitter(fitter, result) - text += rep.to_text(label=name, verbose=verbose) - + for name, report in run.individual_reports.items(): + text += report.to_text(label=name, verbose=verbose) if outfile: validate_output_path(outfile) - if len(individual_results.keys())==1: + + if not run.individual_reports: if outfile.endswith(".pdf"): - global_report.save_pdf(outfile) + run.global_report.save_pdf(outfile) else: - global_report.write_out(outfile) - elif (len(individual_results.keys()))>1: - # Build section reports - indiv_reports = { - name: GenerateReport.from_fitter(fitter, result) - for name, (fitter, result) in individual_results.items() - } - - # Build combined PDF - combined = CombinedReport(outfile, global_report, indiv_reports) + run.global_report.write_out(outfile) + else: + combined = CombinedReport(outfile, run.global_report, run.individual_reports) if outfile.endswith(".pdf"): combined.save_pdf() else: combined.write_out() - for widget in self.plot_frame.winfo_children(): widget.destroy() - if len(individual_results.keys())>1: - fig_global = plt.Figure(figsize=(6, 3), dpi=100) - axg = fig_global.add_subplot(111) - - gl_low, gl_high, gl_w = global_fitter.define_intervals() - plot_mic_distribution( - low_log=gl_low, - high_log=gl_high, - weights=global_fitter.weights_, - dilution_factor=dilution_factor, - mus=global_fitter.mus_, - sigmas=global_fitter.sigmas_, - pis=global_fitter.pis_, - log2_ecoff=global_result[1], - ax=axg - ) - axg.set_title('Aggregate') - - fig_global.tight_layout() - widget = FigureCanvasTkAgg(fig_global, master=self.plot_frame).get_tk_widget() - widget.pack(fill="both", expand=True, pady=10) - - for col, (fitter, result) in individual_results.items(): - fig_i = plt.Figure(figsize=(6, 3), dpi=100) - axi = fig_i.add_subplot(111) - - low, high, w = fitter.define_intervals() - - plot_mic_distribution( - low_log=low, - high_log=high, - weights=fitter.weights_, - dilution_factor=dilution_factor, - mus=fitter.mus_, - sigmas=fitter.sigmas_, - pis=fitter.pis_, - log2_ecoff=result[1], - ax=axi - ) - - axi.set_title(f"{col}") - fig_i.tight_layout() - widget = FigureCanvasTkAgg(fig_i, master=self.plot_frame).get_tk_widget() - widget.pack(fill="both", expand=True, pady=10) + # Global plot + fig_global = plt.Figure(figsize=(6, 3), dpi=100) + axg = fig_global.add_subplot(111) + + gl_low, gl_high, gl_w = run.global_fitter.define_intervals() + plot_mic_distribution( + low_log=gl_low, + high_log=gl_high, + weights=run.global_fitter.weights_, + dilution_factor=dilution_factor, + mus=run.global_fitter.mus_, + sigmas=run.global_fitter.sigmas_, + pis=run.global_fitter.pis_, + log2_ecoff=run.global_result[1], + density=density, + ax=axg, + ) + axg.set_title("Aggregate") + fig_global.tight_layout() + widget = FigureCanvasTkAgg(fig_global, master=self.plot_frame).get_tk_widget() + widget.pack(fill="both", expand=True, pady=10) + + # Individual plots + if self.fit_individual_var.get(): + for col, (fitter, result) in run.individual_fits.items(): + fig_i = plt.Figure(figsize=(6, 3), dpi=100) + axi = fig_i.add_subplot(111) + + low, high, w = fitter.define_intervals() + plot_mic_distribution( + low_log=low, + high_log=high, + weights=fitter.weights_, + dilution_factor=dilution_factor, + mus=fitter.mus_, + sigmas=fitter.sigmas_, + pis=fitter.pis_, + log2_ecoff=result[1], + density=density, + ax=axi, + ) + + axi.set_title(f"{col}") + fig_i.tight_layout() + widget = FigureCanvasTkAgg(fig_i, master=self.plot_frame).get_tk_widget() + widget.pack(fill="both", expand=True, pady=10) self.write_output(text) diff --git a/pyproject.toml b/pyproject.toml old mode 100644 new mode 100755 diff --git a/src/ecoff_fitter/__init__.py b/src/ecoff_fitter/__init__.py old mode 100644 new mode 100755 index 9d48a6a..b020035 --- a/src/ecoff_fitter/__init__.py +++ b/src/ecoff_fitter/__init__.py @@ -1,38 +1,53 @@ -from typing import Callable - - """ ECOFF Fitter — Estimate epidemiological cutoff values (ECOFFs) using interval regression on MIC (Minimum Inhibitory Concentration) data. -Main API: - from ecoff_fitter import ECOFFitter - fitter = ECOFFitter(input="mic_data.csv") - ecoff, z, mu, sigma, model = fitter.generate(percentile=99) +Single-fit API +-------------- +from ecoff_fitter import ECOFFitter + +fitter = ECOFFitter(input="mic_data.csv") +result = fitter.generate(percentile=99) + +Multi-fit / workflow API +------------------------ +from ecoff_fitter import run_ecoff_analysis -CLI: - python -m ecoff_fitter --input mic_data.csv --percentile 99 +run = run_ecoff_analysis( + "mic_data.csv", + fit_individual=True, +) + +print(run.global_report.to_text()) + +CLI +--- +python -m ecoff_fitter --input mic_data.csv """ -from importlib.metadata import version, PackageNotFoundError +from importlib.metadata import PackageNotFoundError, version -# --- Public API imports --- from .core import ECOFFitter +from .workflow import ECOFFRun, run_ecoff_analysis -__all__: list[str] = ["ECOFFitter"] +__all__ = [ + "ECOFFitter", + "run_ecoff_analysis", + "ECOFFRun", +] -# --- Optional: version handling --- try: __version__ = version("ecoff_fitter") except PackageNotFoundError: __version__ = "0.0.0" -# --- Optional: CLI hook for `python -m ecoff_fitter` --- + def main() -> None: - """Entry point for running ecoff_fitter as a module (CLI).""" + """Entry point for `python -m ecoff_fitter`.""" from .cli import main as cli_main + cli_main() if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/src/ecoff_fitter/__main__.py b/src/ecoff_fitter/__main__.py old mode 100644 new mode 100755 diff --git a/src/ecoff_fitter/cli.py b/src/ecoff_fitter/cli.py old mode 100644 new mode 100755 index ef7cd7a..42be101 --- a/src/ecoff_fitter/cli.py +++ b/src/ecoff_fitter/cli.py @@ -13,7 +13,7 @@ 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 build_parser() -> argparse.ArgumentParser: @@ -58,12 +58,22 @@ def build_parser() -> argparse.ArgumentParser: default=1, help="boundary support for censored data handling (None to disable).", ) + parser.add_argument( + "--density", + action="store_true", + help="Plot MIC distribution as density rather than counts.", + ) parser.add_argument( "--percentile", type=float, default=99.0, help="Percentile to calculate the ECOFF (0–100).", ) + parser.add_argument( + "--fit_individual", + action="store_true", + help="Fit individual populations in addition to the aggregate fit.", + ) parser.add_argument( "--outfile", help="Optional path to save ECOFF results to a text or pdf file.", @@ -78,78 +88,58 @@ def build_parser() -> argparse.ArgumentParser: def main(argv: Optional[List[str]] = None) -> None: - """Main entry point for the ECOFFitter CLI.""" + """Run the command-line interface. + + Args: + argv (Optional[List[str]]): Argument list to parse; defaults to the + process command line. + """ parser = build_parser() args = parser.parse_args(argv) try: - - data_dict = read_multi_obs_input(args.input) - df_global = data_dict['global'] - df_individual = data_dict['individual'] - - global_fitter = ECOFFitter( - input=df_global, + run = run_ecoff_analysis( + args.input, params=args.params, + dilution_factor=args.dilution_factor, distributions=args.distributions, boundary_support=args.boundary_support, - dilution_factor=args.dilution_factor + percentile=args.percentile, + fit_individual=args.fit_individual, + density=args.density, ) - global_result = global_fitter.generate(percentile=args.percentile) - - individual_results = {} - for col, subdf in df_individual.items(): - - fitter = ECOFFitter( - input=subdf, - params=args.params, - dilution_factor=args.dilution_factor, - distributions=args.distributions, - boundary_support=args.boundary_support, - ) - - result = fitter.generate(percentile=args.percentile) - individual_results[col] = (fitter, result) - text = "\n\nECOFF RESULTS\n=====================================\n\n" + text += run.global_report.to_text("GLOBAL FIT", verbose=args.verbose) - global_report = GenerateReport.from_fitter(global_fitter, global_result) - - if len(individual_results) > 1: - text += global_report.to_text("GLOBAL FIT", verbose=args.verbose) + if run.individual_reports: text += "\nINDIVIDUAL FITS:\n-------------------------------------\n" + for name, report in run.individual_reports.items(): + text += report.to_text(label=name, verbose=args.verbose) - # Individual fits - for name, (fitter, result) in individual_results.items(): - rep = GenerateReport.from_fitter(fitter, result) - text += rep.to_text(label=name, verbose=args.verbose) - if args.outfile: validate_output_path(args.outfile) - if len(individual_results.keys())==1: - + + if not run.individual_reports: if args.outfile.endswith(".pdf"): - global_report.save_pdf(args.outfile) + run.global_report.save_pdf(args.outfile) else: - global_report.write_out(args.outfile) - elif (len(individual_results.keys()))>1: - # Build section reports - indiv_reports = { - name: GenerateReport.from_fitter(fitter, result) - for name, (fitter, result) in individual_results.items() - } - # Build combined PDF - combined = CombinedReport(args.outfile, global_report, indiv_reports) + run.global_report.write_out(args.outfile) + else: + combined = CombinedReport( + args.outfile, + run.global_report, + run.individual_reports, + ) if args.outfile.endswith(".pdf"): combined.save_pdf() else: combined.write_out() - print (text) + print(text) except Exception as e: - print ('Error', str(e)) + print("Error", str(e)) if __name__ == "__main__": diff --git a/src/ecoff_fitter/core.py b/src/ecoff_fitter/core.py old mode 100644 new mode 100755 index 33406db..bb9344e --- a/src/ecoff_fitter/core.py +++ b/src/ecoff_fitter/core.py @@ -53,8 +53,8 @@ def __init__( Initialize the ECOFFitter. Input may be a DataFrame with 'MIC' and 'observations' columns, or a - file (txt, csv, tsv, xlsx, xls) containing the same structure. A - single-column table or array of MIC values is also accepted. + supported file containing the same structure. Single-column MIC + values are also accepted. Parameters may be supplied directly, or via a dictionary or config file (yaml, yml, txt) containing dilution_factor, distributions, and @@ -66,8 +66,9 @@ def __init__( manual arguments. dilution_factor (int): MIC dilution factor (default 2). distributions (int): Number of normal components to fit. - boundary_support (int | None): Number of intervals defining - censoring bounds (default 1). + boundary_support (int | None): Number of dilution steps used to + extend censoring bounds (default 1); None leaves tails + unbounded. """ validate_input_source(input) @@ -98,7 +99,7 @@ def fit(self, options: dict[str, Any] | None = None) -> "ECOFFitter": or a finite mixture model. Args: - options (dict): Optional solver or EM settings. + options (dict[str, Any] | None): Optional solver or EM settings. Returns: self: The fitted ECOFFitter instance. @@ -119,7 +120,8 @@ def fit_single(self, options: dict[str, Any] | None = None) -> "ECOFFitter": regression. Args: - options (dict | None): Optimization options for the solver. + options (dict[str, Any] | None): Optimization options for the + interval regression solver. Returns: self: The fitted ECOFFitter instance with stored parameters. @@ -147,7 +149,8 @@ def fit_mixture(self, options: dict[str, Any] | None = None) -> "ECOFFitter": algorithm followed by optional refinement. Args: - options (dict | None): EM and refinement options. + options (dict[str, Any] | None): EM settings (``max_iter``, + ``tol``) and refinement setting (``refine``). Returns: self: The fitted ECOFFitter instance with stored mixture parameters. @@ -183,11 +186,13 @@ def define_intervals( censoring rules, then transform to log dilution space. Args: - df (DataFrame | None): Optional MIC data to override stored input. + df (Optional[DataFrame]): Optional MIC data to override stored + input. Returns: - tuple: (y_low_log, y_high_log, weights) – log-transformed interval - bounds and observation weights. + Tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + Log-transformed lower bounds, upper bounds, and observation + weights. """ if df is None: @@ -201,10 +206,15 @@ def define_intervals( if self.boundary_support is not None: tail_dilution_factor = self.dilution_factor**self.boundary_support + def parse_mic_value(mic: str) -> float: + #if a fraction (ie 2 drugs), just keep the numerator + return float(mic.split('/')[0]) + # Process each MIC value and define intervals for i, mic in enumerate(df.MIC): + if mic.startswith("<="): # Left-censored value - lower_bound = float(mic[2:]) + lower_bound = parse_mic_value(mic[2:]) y_low[i] = ( 1e-6 if self.boundary_support is None @@ -213,7 +223,7 @@ def define_intervals( y_high[i] = lower_bound elif mic.startswith(">"): # Right-censored value - upper_bound = float(mic[1:]) + upper_bound = parse_mic_value(mic[1:]) y_low[i] = upper_bound y_high[i] = ( np.inf @@ -222,7 +232,7 @@ def define_intervals( ) else: # Exact MIC value - mic_value = float(mic) + mic_value = parse_mic_value(mic) y_low[i] = mic_value / self.dilution_factor y_high[i] = mic_value @@ -238,19 +248,20 @@ def log_transf_intervals( Transform interval bounds into log base–dilution_factor space. Args: - y_low (array-like): Lower interval bounds. - y_high (array-like): Upper interval bounds. + y_low (NDArray[np.floating]): Lower interval bounds. + y_high (NDArray[np.floating]): Upper interval bounds. Returns: - tuple: Log-transformed (y_low_log, y_high_log). + Tuple[NDArray[np.floating], NDArray[np.floating]]: Transformed + lower and upper bounds. """ log_base = np.log(self.dilution_factor) # Transform intervals to log space y_low = np.clip(y_low, 1e-12, None) y_high = np.clip(y_high, 1e-12, None) - y_low_log = np.log(y_low, where=(y_low > 0)) / log_base - y_high_log = np.log(y_high, where=(y_high > 0)) / log_base + y_low_log = np.log(y_low) / log_base + y_high_log = np.log(y_high) / log_base return y_low_log, y_high_log @@ -261,11 +272,12 @@ def generate( Fit the model and compute the ECOFF at a specified percentile. Args: - percentile (float): Desired percentile (default 99). - options (dict): Optional fit settings. + percentile (int | float): Desired percentile (default 99). + options (dict[str, Any] | None): Optional fit settings. Returns: - tuple: ECOFF value, z-percentile, and fitted parameters. + Tuple[Any, ...]: ECOFF, percentile location, and fitted means and + standard deviations. """ if hasattr(self, "percentile"): @@ -283,7 +295,8 @@ def compute_ecoff(self, percentile: float) -> Tuple[Any, ...]: Compute the ECOFF and percentile location from the fitted model. Args: - percentile (float): Percentile in the wild-type component. + percentile (float): Percentile in the wild-type component, between + 0 and 100. Returns: tuple: @@ -328,6 +341,12 @@ def compute_ecoff(self, percentile: float) -> Tuple[Any, ...]: return (ecoff, z_percentile, *mus_sigmas) def model_summary(self) -> dict[str, Any]: + """Return fitted model metadata and information criteria. + + Returns: + dict[str, Any]: Model family, component count, wild-type component, + fitting diagnostics, and AIC/BIC values. + """ K = self.distributions n = self.obj_df.observations.sum() wt_idx = int(np.argmin(self.mus_)) diff --git a/src/ecoff_fitter/defence.py b/src/ecoff_fitter/defence.py old mode 100644 new mode 100755 index c96251f..f65d502 --- a/src/ecoff_fitter/defence.py +++ b/src/ecoff_fitter/defence.py @@ -10,11 +10,12 @@ def validate_input_source(input: str | DataFrame | dict[str, Any]) -> None: Validate the input source for ECOFFitter. Args: - input (str | pd.DataFrame | dict): Input MIC data or file path or dict. + input (str | DataFrame | dict[str, Any]): MIC and observation data or + a path to an input file. Raises: FileNotFoundError: If the file does not exist. - ValueError: If the input type is invalid. + ValueError: If the input type or required columns are invalid. """ if isinstance(input, pd.DataFrame): @@ -41,7 +42,8 @@ def validate_params_source( Pre-validate the params argument before attempting to read it. Args: - params (dict | str | list | array | DataFrame | None): Parameter input. + params (dict[str, Any] | str | list[Any] | tuple[Any, ...] | DataFrame | Any | None): + Parameter mapping, path, or array-like value to validate. Raises: FileNotFoundError: If the provided file path does not exist. @@ -81,7 +83,7 @@ def validate_mic_data(df: DataFrame) -> None: df (DataFrame): Input MIC data. Raises: - ValueError: If invalid MIC formats or negative observation counts are found. + ValueError: If MIC values are invalid or observation counts are negative. """ if df.empty: raise ValueError("Input DataFrame is empty.") @@ -94,7 +96,9 @@ def validate_mic_data(df: DataFrame) -> None: raise ValueError("MIC column contains empty or invalid entries.") # MIC pattern check - valid_pattern = re.compile(r"^(<=|>)?\d+(\.\d+)?$") + valid_pattern = re.compile( + r"^(<=|>)?(\d+(\.\d+)?)(/(\d+(\.\d+)?))?$" + ) bad_rows = df.loc[~df["MIC"].astype(str).str.match(valid_pattern)] if not bad_rows.empty: raise ValueError(f"Invalid MIC format found in rows: {bad_rows.index.tolist()}") @@ -109,7 +113,8 @@ def validate_params( Args: dilution_factor (int): The MIC dilution step. distributions (int): Number of components in the mixture. - boundary_support (int | None): Number of boundary support to include. + boundary_support (int | None): Number of dilution steps used to extend + censoring bounds, or None for unbounded tails. Raises: ValueError: If any parameter is outside acceptable range. @@ -130,10 +135,17 @@ def validate_params( def validate_output_path(path: str) -> bool: - """ - Checks if the given path is safe and writable, and that the file extension is .txt or .pdf. + """Validate an output path and its containing directory. + + Args: + path (str): Destination path ending in ``.txt`` or ``.pdf``. + + Returns: + bool: True when the extension and destination directory are valid. - Returns True if valid, otherwise raises ValueError. + Raises: + ValueError: If the extension is unsupported or the directory is absent. + PermissionError: If the directory is not writable. """ # Check extension allowed_exts = (".txt", ".pdf") diff --git a/src/ecoff_fitter/graphs.py b/src/ecoff_fitter/graphs.py old mode 100644 new mode 100755 index d5f85fa..9f1a118 --- a/src/ecoff_fitter/graphs.py +++ b/src/ecoff_fitter/graphs.py @@ -17,11 +17,41 @@ def plot_mic_distribution( log2_ecoff: Optional[float] = None, global_x_min: Optional[float] = None, global_x_max: Optional[float] = None, + density: bool = False, ax: Optional[matplotlib.axes.Axes] = None, ) -> matplotlib.axes.Axes: """ - Plot MIC intervals with a K-component Gaussian mixture fit. + Plot MIC observation intervals and their fitted normal component curves. + Supports left- and right-censoring with visual tail extensions. + + If global_x_min and/or global_x_max are supplied, these are used + as the plotting limits. This allows all distributions belonging + to the same drug to use the same x-axis range. + + Args: + low_log (NDArray[np.floating]): Lower interval bounds in log dilution + space. + high_log (NDArray[np.floating]): Upper interval bounds in log dilution + space. + weights (NDArray[np.floating]): Observation weight for each interval. + dilution_factor (float | int): Ratio between adjacent MIC steps; used + to format x-axis labels. + mus (NDArray[np.floating] | list[float]): Component means. + sigmas (NDArray[np.floating] | list[float]): Component standard + deviations. + pis (Optional[NDArray[np.floating] | list[float]]): Component weights; + equal weights are used when omitted. + log2_ecoff (Optional[float]): ECOFF position to mark on the x-axis. + global_x_min (Optional[float]): Optional left plot bound in log + dilution space. + global_x_max (Optional[float]): Optional right plot bound in log + dilution space. + density (bool): Whether to show density heights and density curves. + ax (Optional[matplotlib.axes.Axes]): Axes to draw on; created if omitted. + + Returns: + matplotlib.axes.Axes: Axes containing the plot. """ tail_steps = 3.0 @@ -42,49 +72,88 @@ def plot_mic_distribution( # --------------------------------------------------- # Identify censoring # --------------------------------------------------- - left_censored = (low_log <= -19) | np.isinf(low_log) + left_censored = (low_log <= -19) | np.isinf(low_log) right_censored = np.isinf(high_log) # --------------------------------------------------- # Determine finite bounds # --------------------------------------------------- finite_high_vals = high_log[np.isfinite(high_log)] - finite_low_vals = low_log[np.isfinite(low_log)] + finite_low_vals = low_log[np.isfinite(low_log)] + + finite_high = 0.0 + if finite_high_vals.size > 0: + finite_high = float(np.max(finite_high_vals)) - finite_high = finite_high_vals.max() if len(finite_high_vals) else 0 - finite_low = finite_low_vals.min() if len(finite_low_vals) else 0 + finite_low = 0.0 + if finite_low_vals.size > 0: + finite_low = float(np.min(finite_low_vals)) + + # --------------------------------------------------- + # Determine local plotting bounds + # --------------------------------------------------- - # Axis left bound + # Left bound: + # extend by tail_steps if this distribution is + # left-censored. if np.any(left_censored): plot_xmin = finite_low - tail_steps else: plot_xmin = finite_low - # Axis right bound + # Right bound: + # extend by tail_steps if this distribution is + # right-censored. if np.any(right_censored): plot_xmax = finite_high + tail_steps else: plot_xmax = finite_high + # --------------------------------------------------- + # Override with global drug-level bounds + # --------------------------------------------------- + # These should already include the 3-step censoring + # extension where required at the drug level. + if global_x_min is not None and np.isfinite(global_x_min): + plot_xmin = global_x_min + if global_x_max is not None and np.isfinite(global_x_max): plot_xmax = global_x_max # --------------------------------------------------- # Construct plotting intervals # --------------------------------------------------- - plot_low = low_log.copy() + plot_low = low_log.copy() plot_high = high_log.copy() - # RIGHT CENSOR → extend above finite_high + # RIGHT CENSOR + # + # Keep the censored bar as a 3-step extension from the + # finite boundary for this distribution. The overall + # axis itself may extend further because another + # distribution for the same drug is censored. plot_high[right_censored] = finite_high + tail_steps - # LEFT CENSOR → exactly 3 steps below true high bound - plot_low[left_censored] = high_log[left_censored] - tail_steps + # LEFT CENSOR + # + # Exactly 3 steps below the true high bound. + plot_low[left_censored] = ( + high_log[left_censored] - tail_steps + ) plot_high[left_censored] = high_log[left_censored] - # Clip to plotting region - plot_low = np.clip(plot_low, plot_xmin, plot_xmax) - plot_high = np.clip(plot_high, plot_xmin, plot_xmax) + # Clip intervals to the common plotting region + plot_low = np.clip( + plot_low, + plot_xmin, + plot_xmax, + ) + + plot_high = np.clip( + plot_high, + plot_xmin, + plot_xmax, + ) # --------------------------------------------------- # Deduplicate plotting intervals and compute counts @@ -93,19 +162,54 @@ def plot_mic_distribution( unique_intervals = sorted(set(plot_intervals)) counts = [ - weights[(plot_low == lo) & (plot_high == hi)].sum() + weights[ + (plot_low == lo) & + (plot_high == hi) + ].sum() for lo, hi in unique_intervals ] - mids = [(lo + hi) / 2 for lo, hi in unique_intervals] - widths = [(hi - lo) for lo, hi in unique_intervals] + mids = np.array( + [ + (lo + hi) / 2 + for lo, hi in unique_intervals + ], + dtype=float, + ) + + widths = np.array( + [ + hi - lo + for lo, hi in unique_intervals + ], + dtype=float, + ) + + total_weight = weights.sum() + + print (density) + + if density: + heights = np.divide( + np.asarray(counts, dtype=float), + total_weight * widths, + out=np.zeros_like(widths, dtype=float), + where=widths > 0, + ) + ylabel = "Probability density" + else: + heights = np.asarray( + counts, + dtype=float, + ) + ylabel = "Counts" # --------------------------------------------------- # Draw histogram bars # --------------------------------------------------- ax.bar( mids, - counts, + heights, width=widths, align="center", edgecolor="darkgrey", @@ -113,32 +217,69 @@ def plot_mic_distribution( label="Observed intervals", ) - axis_min = plot_low.min() - axis_max = plot_high.max() + # IMPORTANT: + # Use the plotting bounds rather than the observed + # intervals. This preserves the common drug-level + # x-axis range. + axis_min = plot_xmin + axis_max = plot_xmax # --------------------------------------------------- # Censoring arrows # --------------------------------------------------- if np.any(right_censored): + count_inf = weights[right_censored].sum() + + # Arrow belongs to the end of this distribution's + # censored bar, rather than necessarily the global + # axis maximum. + right_edge = min( + finite_high + tail_steps, + plot_xmax, + ) + ax.annotate( "", - xy=(plot_xmax + arrow_offset, count_inf / 2), - xytext=(plot_xmax - 0.7, count_inf / 2), - arrowprops=dict(arrowstyle="->", lw=1.8, color="darkgrey"), + xy=( + right_edge + arrow_offset, + count_inf / 2, + ), + xytext=( + right_edge - 0.7, + count_inf / 2, + ), + arrowprops=dict( + arrowstyle="->", + lw=1.8, + color="darkgrey", + ), ) if np.any(left_censored): + count_low = weights[left_censored].sum() mid_y = count_low / 2 - left_edge = plot_low.min() + # Use the actual censored bar edge, not necessarily + # the global axis minimum. + left_edge = plot_low[left_censored].min() ax.annotate( "", - xy=(left_edge, mid_y), # arrow head at the bar edge - xytext=(left_edge + 0.7, mid_y), # arrow tail pointing rightward - arrowprops=dict(arrowstyle="->", lw=1.8, color="darkgrey"), + xy=( + left_edge, + mid_y, + ), + xytext=( + left_edge + 0.7, + mid_y, + ), + arrowprops=dict( + arrowstyle="->", + lw=1.8, + color="darkgrey", + ), ) # --------------------------------------------------- @@ -156,41 +297,123 @@ def plot_mic_distribution( # --------------------------------------------------- # Mixture model PDF curves # --------------------------------------------------- - x_values = np.linspace(plot_xmin, plot_xmax, 600) + # The model is now evaluated across the complete + # drug-level plotting range. + x_values = np.linspace( + plot_xmin, + plot_xmax, + 600, + ) component_pdfs = [ - pi * norm.pdf(x_values, mu, sigma) - for pi, mu, sigma in zip(pis, mus, sigmas) + pi * norm.pdf( + x_values, + mu, + sigma, + ) + for pi, mu, sigma + in zip(pis, mus, sigmas) ] - mixture_pdf = np.sum(component_pdfs, axis=0) + mixture_pdf = np.sum( + component_pdfs, + axis=0, + ) - scale = max(counts) / np.max(mixture_pdf) + if density: + + for i, comp in enumerate( + component_pdfs, + start=1, + ): + ax.plot( + x_values, + comp, + lw=2, + label=f"Component {i}", + ) + + ax.plot( + x_values, + mixture_pdf, + "k--", + lw=1.2, + label="Model", + ) - if len(component_pdfs) > 1: - for i, comp in enumerate(component_pdfs, start=1): - ax.plot(x_values, comp * scale, lw=2, label=f"Component {i}") - ax.plot(x_values, mixture_pdf * scale, "k--", lw=1.2, label="Model") else: - ax.plot(x_values, mixture_pdf * scale, "k--", lw=1.2, label="Model") + + scale = ( + max(heights) / np.max(mixture_pdf) + if np.max(mixture_pdf) > 0 + else 1.0 + ) + + if len(component_pdfs) > 1: + + for i, comp in enumerate( + component_pdfs, + start=1, + ): + ax.plot( + x_values, + comp * scale, + lw=2, + label=f"Component {i}", + ) + + ax.plot( + x_values, + mixture_pdf * scale, + "k--", + lw=1.2, + label="Model", + ) + + else: + + ax.plot( + x_values, + mixture_pdf * scale, + "k--", + lw=1.2, + label="Model", + ) # --------------------------------------------------- # Axis formatting # --------------------------------------------------- - + if np.any(left_censored): ax.margins(x=0) - ax.set_xlim(axis_min, axis_max) - ax.set_ylabel("Counts") + + # Use common drug-level range + ax.set_xlim( + axis_min, + axis_max, + ) + + ax.set_ylabel(ylabel) xticks = ax.get_xticks() - mic_labels = [f"{dilution_factor ** x:.2g}" for x in xticks] + + mic_labels = [ + f"{dilution_factor ** x:.2g}" + for x in xticks + ] + ax.set_xticks(xticks) ax.set_xticklabels(mic_labels) + ax.set_xlabel("MIC (mg/L)") ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) - ax.legend(fontsize=7, frameon=False) + + ax.legend( + fontsize=7, + frameon=False, + ) + return ax diff --git a/src/ecoff_fitter/mixture.py b/src/ecoff_fitter/mixture.py old mode 100644 new mode 100755 index 18d82a4..34eda7d --- a/src/ecoff_fitter/mixture.py +++ b/src/ecoff_fitter/mixture.py @@ -12,7 +12,7 @@ class MixtureModel: Expectation–Maximization (EM) followed by optional joint refinement. Workflow: - 1. K-means clustering on interval midpoints for initial paramaters. + 1. K-means clustering on interval midpoints for initial parameters. 2. EM iteratively updates responsibilities and component parameters. 3. Optional refinement using mixture likelihood via L-BFGS-B. """ @@ -47,11 +47,13 @@ def __init__( - π_k: Weighted cluster proportions. Args: - y_low (array-like): Lower bounds of log2 MIC intervals. - y_high (array-like): Upper bounds of log2 MIC intervals. - weights (array-like): Observation weights for each interval. + y_low (NDArray[np.floating] | list[float]): Lower bounds of + log-dilution MIC intervals. + y_high (NDArray[np.floating] | list[float]): Upper bounds of + log-dilution MIC intervals. + weights (NDArray[np.floating] | list[float]): Weight for each + interval. distributions (int): Number of mixture components (K). - """ self.K = distributions @@ -146,10 +148,16 @@ def em(self, max_iter: int = 500, tol: float = 1e-6) -> "MixtureModel": Returns: self: Fitted parameters, log-likelihood, and convergence info. + + Notes: + The EM loop records the final iteration count, convergence flag, + log-likelihood, and packed parameter vector on this instance. """ N = len(self.y_low) + MIN_SIGMA=0.25 #stop component width collapsing + converged = False prev_ll = -np.inf @@ -184,7 +192,8 @@ def em(self, max_iter: int = 500, tol: float = 1e-6) -> "MixtureModel": fit_k.fit() mu_k, log_sigma_k = fit_k.result.x new_mus[k] = mu_k - new_sigmas[k] = np.exp(log_sigma_k) + new_sigmas[k] = max(np.exp(log_sigma_k), MIN_SIGMA) + self.mus, self.sigmas = new_mus, new_sigmas @@ -230,16 +239,31 @@ def refine_mixture(self) -> "MixtureModel": Returns: self: Updated parameter vector and mixture component estimates. + + Notes: + The joint objective is the weighted negative log-likelihood of + the observed intervals under the mixture. """ y_low = np.asarray(self.y_low, float) y_high = np.asarray(self.y_high, float) weights = np.asarray(self.weights, float) + MIN_SIGMA=0.25 #stop component width collapsing + def unpack_params( params: NDArray[np.floating], ) -> Tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: - """Convert flat parameter vector into mus, sigmas, pis.""" + """Convert a flat parameter vector into means, scales, and weights. + + Args: + params (NDArray[np.floating]): Means, log-scales, and free + mixture logits concatenated into one vector. + + Returns: + tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + Component means, scales, and normalized mixture weights. + """ mus = params[: self.K] sigmas = np.exp(params[self.K : 2 * self.K]) @@ -252,6 +276,14 @@ def unpack_params( return mus, sigmas, pis def neg_log_likelihood(params: NDArray[np.floating]) -> float: + """Compute the weighted negative interval mixture log-likelihood. + + Args: + params (NDArray[np.floating]): Flat mixture parameter vector. + + Returns: + float: Negative weighted log-likelihood. + """ mus, sigmas, pis = unpack_params(params) # P(interval | component k) @@ -268,7 +300,17 @@ def neg_log_likelihood(params: NDArray[np.floating]) -> float: return float(-np.sum(weights * np.log(mix))) - res = minimize(neg_log_likelihood, self.x, method="L-BFGS-B") + bounds = ( + [(None, None)] * self.K + + [(np.log(MIN_SIGMA), None)] * self.K + + [(None, None)] * (self.K - 1) + ) + res = minimize( + neg_log_likelihood, + self.x, + method="L-BFGS-B", + bounds=bounds, + ) self.x = res.x self.mus, self.sigmas, self.pis = unpack_params(self.x) diff --git a/src/ecoff_fitter/report.py b/src/ecoff_fitter/report.py old mode 100644 new mode 100755 index e24bc75..e58d52b --- a/src/ecoff_fitter/report.py +++ b/src/ecoff_fitter/report.py @@ -13,13 +13,14 @@ class GenerateReport: """ Container for ECOFF fitting results and reporting utilities. - Now stores a reference to the ECOFFitter instance (Option A), - avoiding duplication of distributions, mus, sigmas, intervals, etc. + The fitter reference supplies model parameters and interval data when + formatting text or creating figures. """ fitter: Any ecoff: float z: Tuple[float, float, float] # Percentile-based ECOFFs (99, 97.5, 95) + density: bool = False @classmethod def from_fitter(cls, fitter: Any, result: Tuple[Any, ...]) -> "GenerateReport": @@ -28,6 +29,14 @@ def from_fitter(cls, fitter: Any, result: Tuple[Any, ...]) -> "GenerateReport": result = (ecoff, z_percentile, mu, sigma) # single result = (ecoff, z_percentile, mu1, sigma1, ..., muK, sigmaK) # mixture + + Args: + fitter (Any): Fitted ECOFFitter instance. + result (Tuple[Any, ...]): Result returned by + :meth:`ECOFFitter.generate`. + + Returns: + GenerateReport: Report initialized with ECOFF values and fitter. """ # Percentiles derived from fitter @@ -41,30 +50,37 @@ def from_fitter(cls, fitter: Any, result: Tuple[Any, ...]) -> "GenerateReport": fitter=fitter, ecoff=ecoff, z=(z0, z1, z2), + density=getattr(fitter, "density", False), ) @property def distributions(self) -> int: + """Return the number of fitted mixture components.""" return cast(int, self.fitter.distributions) @property def dilution_factor(self) -> float: + """Return the MIC dilution factor used by the fitter.""" return cast(float, self.fitter.dilution_factor) @property def mus(self) -> NDArray[np.floating]: + """Return fitted component means in log-dilution space.""" return cast(NDArray[np.floating], self.fitter.mus_) @property def sigmas(self) -> NDArray[np.floating]: + """Return fitted component standard deviations.""" return cast(NDArray[np.floating], self.fitter.sigmas_) @property def pis(self) -> Optional[NDArray[np.floating]]: + """Return component weights when available.""" return getattr(self.fitter, "pis_", None) @property def model(self) -> Any: + """Return the fitted underlying model object when available.""" return getattr(self.fitter, "model_", None) @@ -72,6 +88,12 @@ def model(self) -> Any: def intervals( self, ) -> tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + """Return the fitted input's log interval bounds and weights. + + Returns: + tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + Lower bounds, upper bounds, and observation weights. + """ return cast( tuple[ NDArray[np.floating], @@ -84,8 +106,12 @@ def intervals( def to_text(self, label: str | None = None, verbose: bool = False) -> str: """ - Produce the exact text representation currently created inside the GUI. - `label` is optional (e.g., column name or 'GLOBAL FIT'). + Args: + label (str | None): Optional heading such as a column name. + verbose (bool): Whether to include model summary details. + + Returns: + str: Formatted ECOFF and component summary. """ lines = [] @@ -117,12 +143,22 @@ def to_text(self, label: str | None = None, verbose: bool = False) -> str: def write_out(self, path: str) -> None: + """Write the text report to a file. + + Args: + path (str): Destination file path. + """ with open(path, "w") as f: f.write(self.to_text()) print(f"\nResults saved to: {path}") def save_pdf(self, outfile: str) -> None: + """Save the report as a single-page PDF. + + Args: + outfile (str): Destination PDF path. + """ with PdfPages(outfile) as pdf: fig = self._make_pdf() pdf.savefig(fig) @@ -131,6 +167,14 @@ def save_pdf(self, outfile: str) -> None: print(f"PDF report saved to: {outfile}") def _make_pdf(self, title: Optional[str] = None) -> Figure: + """Create a figure containing the distribution plot and text report. + + Args: + title (Optional[str]): Optional plot title and report label. + + Returns: + Figure: Matplotlib figure for the report page. + """ fig, (ax_plot, ax_text) = plt.subplots( nrows=1, ncols=2, @@ -150,6 +194,7 @@ def _make_pdf(self, title: Optional[str] = None) -> Figure: mus=self.mus, sigmas=self.sigmas, log2_ecoff=np.log2(self.ecoff), + density=self.density, ax=ax_plot, ) @@ -179,6 +224,9 @@ def _make_pdf(self, title: Optional[str] = None) -> Figure: def _format_model_summary(self) -> list[str]: """ Format a structured model summary from the fitter, if available. + + Returns: + list[str]: Formatted summary lines, or an unavailable notice. """ if not hasattr(self.fitter, "model_summary"): return [" (model summary unavailable)"] @@ -207,9 +255,11 @@ def __init__( individual_reports: Dict[str, GenerateReport], ) -> None: """ - outfile: PDF filename (for save_pdf) - global_report: GenerateReport instance - individual_reports: dict {column_name: GenerateReport} + Args: + outfile (str): Destination path for the combined report. + global_report (GenerateReport): Report for aggregate observations. + individual_reports (Dict[str, GenerateReport]): Reports keyed by + input column name. """ self.outfile = outfile self.global_report = global_report @@ -222,6 +272,9 @@ def write_out(self) -> None: - Individual fit summaries Uses GenerateReport.to_text() for formatting consistency. + + Returns: + None """ lines: list[str] = [] @@ -243,6 +296,11 @@ def write_out(self) -> None: def save_pdf(self) -> None: + """Write the global and individual reports to a multi-page PDF. + + Returns: + None + """ from matplotlib.backends.backend_pdf import PdfPages with PdfPages(self.outfile) as pdf: diff --git a/src/ecoff_fitter/utils.py b/src/ecoff_fitter/utils.py old mode 100644 new mode 100755 index 096371e..9d78b1e --- a/src/ecoff_fitter/utils.py +++ b/src/ecoff_fitter/utils.py @@ -1,9 +1,28 @@ -from typing import Any, Dict, List, Tuple, Optional, cast +from typing import Any, Dict, Tuple, Optional, cast import pandas as pd from pandas import DataFrame -from numpy.typing import NDArray import yaml import os +from dataclasses import dataclass + + +@dataclass(frozen=True) +class PreparedInput: + """Normalized aggregate and per-column MIC observation tables. + + Attributes: + global_df (DataFrame): MIC and summed observation counts. + individual_dfs (Dict[str, DataFrame]): MIC and counts for each input + group, keyed by its column name. + """ + global_df: DataFrame + individual_dfs: Dict[str, DataFrame] + + @property + def has_individuals(self) -> bool: + """Whether input preparation produced any individual group tables.""" + return len(self.individual_dfs) > 0 + def read_input( @@ -11,73 +30,131 @@ def read_input( sheet_name: Optional[str] = None, ) -> DataFrame: """ - Read MIC input data from a DataFrame, array-like, dict, or file - and validate required columns. If given a single-column input, - automatically aggregate it into MIC + observations format. + Strict single-fit reader for ECOFFitter. + + Accepts raw MIC values or a canonical ``MIC`` and ``observations`` table. + + Args: + data (DataFrame | list[Any] | tuple[Any, ...] | dict[str, Any] | str): + Input observations or supported file path. + sheet_name (Optional[str]): Worksheet name for Excel input. + + Returns: + DataFrame: Canonical table with ``MIC`` and ``observations`` columns. + + Raises: + ValueError: If the normalized input contains individual group columns. + """ + prepared = prepare_input(data, sheet_name=sheet_name) + + if prepared.has_individuals: + raise ValueError( + "ECOFFitter expects a single MIC + observations table. " + "For multi-column input, use prepare_input() or run_ecoff_analysis()." + ) + + return prepared.global_df + +def prepare_input( + data: DataFrame | list[Any] | tuple[Any, ...] | dict[str, Any] | str, + sheet_name: Optional[str] = None, +) -> PreparedInput: + """ + Normalize input for both single-fit and multi-fit workflows. + + Input rules: + - 1 column only: treat as raw MIC values and collapse to MIC + observations. + - MIC + observations: canonical single-fit input, no individual fits. + - MIC + one or more additional columns: build a global fit plus one + individual fit per additional column. + + Args: + data (DataFrame | list[Any] | tuple[Any, ...] | dict[str, Any] | str): + Raw MIC observations or supported file path. + sheet_name (Optional[str]): Worksheet name for Excel input. Returns: - DataFrame with columns: - - MIC (str) - - observations (int) + PreparedInput: Aggregate table and any per-column tables. """ + df = _load_raw_frame(data, sheet_name=sheet_name) + + if df.shape[1] == 1: + col = df.columns[0] + mic_series = df[col].astype(str).str.strip() + global_df = mic_series.to_frame(name="MIC").groupby("MIC").size().reset_index(name="observations") + return PreparedInput(global_df=global_df, individual_dfs={}) - # Load into a DataFrame ---- + if "MIC" not in df.columns: + raise ValueError("Input must contain a 'MIC' column.") + + obs_cols = [c for c in df.columns if c != "MIC"] + if len(obs_cols) == 0: + raise ValueError("Input must contain at least one additional column besides 'MIC'.") + + df = df.copy() + df["MIC"] = df["MIC"].astype(str).str.strip() + + for col in obs_cols: + df[col] = pd.to_numeric(df[col], errors="coerce").fillna(0).astype(float) + + # Canonical single-fit input: MIC + observations only + if len(obs_cols) == 1 and obs_cols[0] == "observations": + global_df = df[["MIC", "observations"]].copy() + return PreparedInput(global_df=global_df, individual_dfs={}) + + # Multi-column workflow: + # one global fit (sum across all observation columns), + # and one individual fit per column. + individual_dfs: Dict[str, DataFrame] = {} + for col in obs_cols: + subdf = df[["MIC", col]].copy() + subdf.rename(columns={col: "observations"}, inplace=True) + individual_dfs[col] = subdf + + global_df = df[["MIC"]].copy() + global_df["observations"] = df[obs_cols].sum(axis=1).astype(float) + + return PreparedInput(global_df=global_df, individual_dfs=individual_dfs) + +def _load_raw_frame( + data: DataFrame | list[Any] | tuple[Any, ...] | dict[str, Any] | str, + sheet_name: Optional[str] = None, +) -> DataFrame: + """Load input data into a DataFrame and normalize its column labels. + + Args: + data: DataFrame, sequence, mapping, array-like object, or file path. + sheet_name: Worksheet name when loading an Excel file. + + Returns: + DataFrame: Loaded table with whitespace removed from column names. + + Raises: + ValueError: If the input type or file extension is unsupported. + """ if isinstance(data, pd.DataFrame): df = data.copy() - elif isinstance(data, (list, tuple)): df = pd.DataFrame({"MIC": data}) - - elif hasattr(data, "__array__"): # numpy arrays + elif hasattr(data, "__array__"): df = pd.DataFrame({"MIC": list(data)}) - elif isinstance(data, dict): df = pd.DataFrame.from_dict(data) - elif isinstance(data, str): ext = os.path.splitext(data)[-1].lower() - - if ext in [".csv"]: + if ext == ".csv": df = pd.read_csv(data) elif ext in [".tsv", ".txt"]: df = pd.read_csv(data, sep=r"\s+") elif ext in [".xlsx", ".xls"]: val = pd.read_excel(data, sheet_name=sheet_name) - if isinstance(val, dict): - # choose a sheet, or raise error - df = next(iter(val.values())) # first sheet - else: - df = val + df = next(iter(val.values())) if isinstance(val, dict) else val else: raise ValueError(f"Unsupported file type: {ext}") - else: raise ValueError("Input must be DataFrame, list, array, dict, or file path.") - - df.columns = [str(c).strip() for c in df.columns] - # Handle single-column input automatically - if df.shape[1] == 1: - col = df.columns[0] - df["MIC"] = df[col].astype(str).str.strip() - - df = df.groupby("MIC").size().reset_index(name="observations") - - expected = ["MIC", "observations"] - missing = [c for c in expected if c not in df.columns] - - if missing: - raise ValueError( - f"Missing required columns: {missing}. " - f"If using single-column input, it must be one column only." - ) - - df["MIC"] = df["MIC"].astype(str).str.strip() - df["observations"] = ( - pd.to_numeric(df["observations"], errors="coerce").fillna(0).astype(int) - ) - - df = df.dropna(subset=["MIC"]).reset_index(drop=True) + df.columns = [str(c).strip() for c in df.columns] return df @@ -88,7 +165,7 @@ def read_params( dflt_tails: Optional[int], ) -> Tuple[int, int, Optional[int], float]: """ - Read ECOFF model parameters from a file or dictionary, falling back to provided defaults. + Read ECOFF model parameters from a YAML, TXT, or dictionary source. Args: params (str | dict): File path to a YAML or text parameter file, @@ -98,12 +175,13 @@ def read_params( dflt_tails (int | None): Default number of boundary support. Returns: - tuple: (dilution_factor, distributions, boundary_support) + tuple[int, int, Optional[int], float]: Dilution factor, component + count, boundary support, and percentile. Raises: FileNotFoundError: If the specified file does not exist. ValueError: If file type is unsupported. - AssertionError: If input is not a valid file path or dictionary. + AssertionError: If ``params`` is not a dictionary after path handling. """ if isinstance(params, str): @@ -160,86 +238,15 @@ def read_multi_obs_input( data: DataFrame | list[Any] | tuple[Any, ...] | dict[str, Any] | Any | str, sheet_name: Optional[str] = None, ) -> Dict[str, Any]: + """Return aggregate and individual tables prepared from the input. - """ - Read MIC input but allow multiple observation columns. - Returns a dict: - { - "global": df_global, # aggregated observations - "individual": {col: df_col} # one df per obs column - } - - Each returned df has: - MIC (str) - observations (int) - """ - - # --- Load input similarly to original read_input() --- - if isinstance(data, pd.DataFrame): - df = data.copy() - - elif isinstance(data, (list, tuple)): - df = pd.DataFrame({"MIC": data}) - - elif hasattr(data, "__array__"): - df = pd.DataFrame({"MIC": list(data)}) - - elif isinstance(data, dict): - df = pd.DataFrame.from_dict(data) - - elif isinstance(data, str): - ext = os.path.splitext(data)[-1].lower() - - if ext == ".csv": - df = pd.read_csv(data) - elif ext in [".tsv", ".txt"]: - df = pd.read_csv(data, sep=r"\s+") - elif ext in [".xlsx", ".xls"]: - val = pd.read_excel(data, sheet_name=sheet_name) - if isinstance(val, dict): - # choose a sheet, or raise error - df = next(iter(val.values())) # first sheet - else: - df = val - else: - raise ValueError(f"Unsupported file type: {ext}") - - else: - raise ValueError("Input must be DataFrame, list, array, dict, or file path.") - - # Normalize column names - df.columns = [str(c).strip() for c in df.columns] - - # If only 1 column, fallback to old logic - if df.shape[1] == 1: - col = df.columns[0] - df["MIC"] = df[col].astype(str).str.strip() - df_single = df.groupby("MIC").size().reset_index(name="observations") - return cast(Dict[str, Any], {"global": df_single, "individual": {"observations": df_single.copy()}}) - - - # Require MIC column - if "MIC" not in df.columns: - raise ValueError("Input must contain a 'MIC' column.") - - df["MIC"] = df["MIC"].astype(str).str.strip() - - # Identify observation columns - obs_cols = [c for c in df.columns if c != "MIC"] - - # Validate numeric obs columns - for col in obs_cols: - df[col] = pd.to_numeric(df[col], errors="coerce").fillna(0).astype(int) - - # Build individual fitter DataFrames - individual = {} - for col in obs_cols: - subdf = df[["MIC", col]].copy() - subdf.rename(columns={col: "observations"}, inplace=True) - individual[col] = subdf - - # Build global aggregated DataFrame - df_global = df[["MIC"]].copy() - df_global["observations"] = df[obs_cols].sum(axis=1).astype(int) + Args: + data: Input observations accepted by :func:`prepare_input`. + sheet_name: Worksheet name when loading an Excel file. - return {"global": df_global, "individual": individual} + Returns: + Dict[str, Any]: Mapping with ``"global"`` and ``"individual"`` + entries. + """ + prepared = prepare_input(data, sheet_name=sheet_name) + return {"global": prepared.global_df, "individual": prepared.individual_dfs} diff --git a/src/ecoff_fitter/workflow.py b/src/ecoff_fitter/workflow.py new file mode 100755 index 0000000..33ea32d --- /dev/null +++ b/src/ecoff_fitter/workflow.py @@ -0,0 +1,263 @@ +from dataclasses import dataclass +from typing import Any, Dict, Tuple, cast + +import numpy as np + +from ecoff_fitter.core import ECOFFitter +from ecoff_fitter.report import GenerateReport +from ecoff_fitter.utils import PreparedInput, prepare_input + + +@dataclass +class ECOFFRun: + """Results and reports produced by a global and optional individual fits. + + Attributes: + prepared (PreparedInput): Normalized global and individual input data. + selected_k (int): Number of components selected for the global fit. + global_fitter (ECOFFitter): Fitted model for all observations. + global_result (Tuple[Any, ...]): Global ECOFF and fitted parameters. + global_report (GenerateReport): Report for the global fit. + individual_fits (Dict[str, Tuple[ECOFFitter, Tuple[Any, ...]]]): + Fitter and result for each individual input column. + individual_reports (Dict[str, GenerateReport]): Reports for + individual input columns. + """ + prepared: PreparedInput + selected_k: int + global_fitter: ECOFFitter + global_result: Tuple[Any, ...] + global_report: GenerateReport + individual_fits: Dict[str, Tuple[ECOFFitter, Tuple[Any, ...]]] + individual_reports: Dict[str, GenerateReport] + + +def run_ecoff_analysis( + data: Any, + *, + params: dict[str, Any] | str | None = None, + dilution_factor: int = 2, + distributions: int | str = 1, + max_distributions: int = 3, + criterion: str = "bic", + min_delta: float = 15, + boundary_support: int | None = 1, + percentile: float = 99.0, + fit_individual: bool = True, + density: bool = False, + options: dict[str, Any] | None = None, + sheet_name: str | None = None, +) -> ECOFFRun: + """Fit ECOFF models to aggregate data and optionally each input group. + + Args: + data (Any): MIC observations in a supported table, sequence, mapping, + array-like value, or file format. + params (dict[str, Any] | str | None): Optional model parameter mapping + or configuration file path. + dilution_factor (int): Ratio between adjacent MIC dilution steps. + distributions (int | str): Number of components, or ``"auto"`` to + select a count using ``criterion``. + max_distributions (int): Maximum component count considered in auto + selection. + criterion (str): Model summary score used for auto selection, usually + ``"bic"`` or ``"aic"``. + min_delta (float): Minimum score improvement required to consider the + next component count. + boundary_support (int | None): Number of dilution steps used to extend + censoring bounds, or None for unbounded tails. + percentile (float): Percentile used to calculate the ECOFF. + fit_individual (bool): Whether to fit each individual input column. + density (bool): Whether reports plot probability density instead of + counts. + options (dict[str, Any] | None): Solver and EM options passed to fits. + sheet_name (str | None): Worksheet to read when ``data`` is an Excel + file. + + Returns: + ECOFFRun: Global fit, optional individual fits, and their reports. + """ + prepared = prepare_input(data, sheet_name=sheet_name) + + if distributions == "auto": + k, score, global_fitter, global_result = select_best_k( + data, + dilution_factor=dilution_factor, + boundary_support=boundary_support, + max_distributions=max_distributions, + percentile=percentile, + criterion=criterion, + min_delta=min_delta, + params=params, + options=options, + sheet_name=sheet_name, + ) + + else: + fixed_distributions = cast(int, distributions) + global_fitter = ECOFFitter( + input=prepared.global_df, + params=params, + dilution_factor=dilution_factor, + distributions=fixed_distributions, + boundary_support=boundary_support, + ) + global_result = global_fitter.generate(percentile=percentile, options=options) + k = fixed_distributions + + setattr(global_fitter, "density", density) + + global_report = GenerateReport.from_fitter(global_fitter, global_result) + + individual_fits: Dict[str, Tuple[ECOFFitter, Tuple[Any, ...]]] = {} + individual_reports: Dict[str, GenerateReport] = {} + + if fit_individual: + for name, subdf in prepared.individual_dfs.items(): + if distributions == "auto": + _, _, fitter, result = select_best_k( + subdf, + dilution_factor=dilution_factor, + boundary_support=boundary_support, + max_distributions=max_distributions, + percentile=percentile, + criterion=criterion, + min_delta=min_delta, + params=params, + options=options, + ) + else: + fitter = ECOFFitter( + input=subdf, + params=params, + dilution_factor=dilution_factor, + distributions=cast(int, distributions), + boundary_support=boundary_support, + ) + result = fitter.generate(percentile=percentile, options=options) + + setattr(fitter, "density", density) + individual_fits[name] = (fitter, result) + individual_reports[name] = GenerateReport.from_fitter(fitter, result) + + return ECOFFRun( + prepared=prepared, + selected_k=k, + global_fitter=global_fitter, + global_result=global_result, + global_report=global_report, + individual_fits=individual_fits, + individual_reports=individual_reports, + ) + + +def select_best_k( + data: Any, + dilution_factor: int = 2, + boundary_support: int | None = 1, + percentile: float = 99, + criterion: str = "bic", + min_delta: float = 15, + min_pi: float = 0.05, + min_separation: float = 1.0, + max_distributions: int = 2, + params: dict[str, Any] | str | None = None, + options: dict[str, Any] | None = None, + sheet_name: str | None = None, +) -> Tuple[int, float, ECOFFitter, Tuple[Any, ...]]: + """Select a component count by score and mixture diagnostics. + + Candidate models are fitted in increasing component count. Selection + stops when the score improvement is too small, a component weight is + below ``min_pi``, or adjacent components are insufficiently separated. + + Args: + data (Any): MIC input accepted by :func:`prepare_input`. + dilution_factor (int): Ratio between adjacent MIC dilution steps. + boundary_support (int | None): Censoring-bound support setting. + percentile (float): Percentile used to calculate each ECOFF. + criterion (str): Key in ``ECOFFitter.model_summary()`` to minimize. + min_delta (float): Minimum score improvement for adding a component. + min_pi (float): Minimum accepted component mixture weight. + min_separation (float): Minimum adjacent mean separation in pooled + standard deviations. + max_distributions (int): Maximum number of components to evaluate. + params (dict[str, Any] | str | None): Optional parameter mapping or + configuration file path. + options (dict[str, Any] | None): Solver and EM options passed to fits. + sheet_name (str | None): Worksheet to read from Excel input. + + Returns: + tuple[int, float, ECOFFitter, tuple[Any, ...]]: Selected component + count, criterion score, fitted model, and generated result. + """ + + df = prepare_input( + data, + sheet_name=sheet_name, + ).global_df + + n_informative = int((df["observations"] > 0).sum()) + + if n_informative == 0: + raise ValueError("No MIC observations available for fitting.") + + max_k = min( + max_distributions, + n_informative, + ) + + best = None + + for k in range(1, max_k + 1): + + # Fit model + fitter = ECOFFitter( + input=df, + params=params, + dilution_factor=dilution_factor, + distributions=k, + boundary_support=boundary_support, + ) + + result = fitter.generate( + percentile=percentile, + options=options, + ) + + score = fitter.model_summary()[criterion] + + # K=1 is always the starting model + if best is None: + best = (k, score, fitter, result) + continue + + # improve model fit? + _, best_score, _, _ = best + + if best_score - score < min_delta: + break + + # components sufficiently large? + pis = np.asarray(fitter.pis_) + + if np.any(pis < min_pi): + break + + # Are adjacent components sufficiently separated? + order = np.argsort(fitter.mus_) + + mus = np.asarray(fitter.mus_)[order] + sigmas = np.asarray(fitter.sigmas_)[order] + + pooled_sigmas = np.sqrt((sigmas[:-1] ** 2 + sigmas[1:] ** 2) / 2) + + separations = np.diff(mus) / pooled_sigmas + + if np.any(separations < min_separation): + break + + best = (k, score, fitter, result) + + assert best is not None + return best diff --git a/src/ecoff_fitter/wts.py b/src/ecoff_fitter/wts.py old mode 100644 new mode 100755 diff --git a/tests/test_cli.py b/tests/test_cli.py old mode 100644 new mode 100755 index 16c9145..6f6abe5 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4,37 +4,13 @@ @pytest.fixture -def mock_loader(monkeypatch): - """ - Pretend that the input contains only a single global dataset - and no individual datasets. - """ - monkeypatch.setattr( - cli, - "read_multi_obs_input", - lambda path: {"global": MagicMock(), "individual": {}}, - ) - - -@pytest.fixture -def mock_fitter(monkeypatch): - """Mock ECOFFitter so it always returns a simple fixed result.""" - mock_instance = MagicMock() - mock_instance.generate.return_value = (4.0, 2.0, 1.0, 0.5) - - monkeypatch.setattr(cli, "ECOFFitter", MagicMock(return_value=mock_instance)) - return mock_instance - - -@pytest.fixture -def mock_report(monkeypatch): - """Mock GenerateReport.from_fitter.""" - report_instance = MagicMock() - report_cls = MagicMock() - report_cls.from_fitter.return_value = report_instance - - monkeypatch.setattr(cli, "GenerateReport", report_cls) - return report_instance +def mock_run(monkeypatch): + """Return a mocked workflow result for CLI tests.""" + run = MagicMock() + run.global_report.to_text.return_value = "GLOBAL FIT\n" + run.individual_reports = {} + monkeypatch.setattr(cli, "run_ecoff_analysis", MagicMock(return_value=run)) + return run @pytest.fixture @@ -56,57 +32,58 @@ def test_parser_requires_input(): with pytest.raises(SystemExit): parser.parse_args([]) -def test_main_runs_minimal(mock_loader, mock_fitter, mock_report, capsys): +def test_main_runs_minimal(mock_run, capsys): cli.main(["--input", "fake.csv"]) # Output contains header out = capsys.readouterr().out assert "ECOFF RESULTS" in out - # ECOFFitter used - assert cli.ECOFFitter.called - # global fitter generate called - mock_fitter.generate.assert_called_once() + cli.run_ecoff_analysis.assert_called_once() -def test_main_outfile_txt(mock_loader, mock_fitter, mock_report, mock_validate): +def test_main_outfile_txt(mock_run, mock_validate): cli.main(["--input", "fake.csv", "--outfile", "results.txt"]) mock_validate.assert_called_once_with("results.txt") + mock_run.global_report.write_out.assert_called_once_with("results.txt") -def test_main_outfile_pdf(mock_loader, mock_fitter, mock_report, mock_validate): +def test_main_outfile_pdf(mock_run, mock_validate): cli.main(["--input", "fake.csv", "--outfile", "report.pdf"]) mock_validate.assert_called_once_with("report.pdf") + mock_run.global_report.save_pdf.assert_called_once_with("report.pdf") -def test_main_runs_with_multiple_individuals(monkeypatch, mock_fitter, mock_report, mock_validate): +def test_main_runs_with_multiple_individuals(monkeypatch, mock_validate): """ Ensure the CLI runs when multiple individual datasets are present and that CombinedReport is invoked. """ - # Make two fake individual datasets - fake_global = MagicMock() - fake_indiv1 = MagicMock() - fake_indiv2 = MagicMock() - - def fake_loader(path): - return { - "global": fake_global, - "individual": { - "A": fake_indiv1, - "B": fake_indiv2, - }, - } - - monkeypatch.setattr(cli, "read_multi_obs_input", fake_loader) + run = MagicMock() + run.individual_reports = {"A": MagicMock(), "B": MagicMock()} + monkeypatch.setattr(cli, "run_ecoff_analysis", MagicMock(return_value=run)) # Mock CombinedReport so we can detect when it's used combined_instance = MagicMock() combined_cls = MagicMock(return_value=combined_instance) monkeypatch.setattr(cli, "CombinedReport", combined_cls) - cli.main(["--input", "fake.csv", "--outfile", "combined.pdf"]) + cli.main(["--input", "fake.csv", "--outfile", "combined.pdf", "--fit_individual"]) mock_validate.assert_called_once_with("combined.pdf") combined_cls.assert_called_once() combined_instance.save_pdf.assert_called_once() + + +def test_main_default_skips_individual_fits(monkeypatch, mock_validate): + run = MagicMock() + run.individual_reports = {} + monkeypatch.setattr(cli, "run_ecoff_analysis", MagicMock(return_value=run)) + + combined_cls = MagicMock() + monkeypatch.setattr(cli, "CombinedReport", combined_cls) + + cli.main(["--input", "fake.csv", "--outfile", "combined.pdf"]) + + combined_cls.assert_not_called() + run.global_report.save_pdf.assert_called_once_with("combined.pdf") diff --git a/tests/test_defence.py b/tests/test_defence.py old mode 100644 new mode 100755 diff --git a/tests/test_ecoff_fitter.py b/tests/test_ecoff_fitter.py old mode 100644 new mode 100755 diff --git a/tests/test_graphs.py b/tests/test_graphs.py old mode 100644 new mode 100755 diff --git a/tests/test_report.py b/tests/test_report.py old mode 100644 new mode 100755 index 007037f..ac607d1 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -13,11 +13,16 @@ def mock_loader(monkeypatch): Ensures CLI never touches the filesystem and always receives one global dataset and zero individual datasets (simplest case). """ - monkeypatch.setattr( - cli, - "read_multi_obs_input", - lambda _: {"global": MagicMock(), "individual": {}}, - ) + mock = MagicMock(side_effect=lambda *args, **kwargs: _mock_run()) + monkeypatch.setattr(cli, "run_ecoff_analysis", mock) + return mock + + +def _mock_run(): + run = MagicMock() + run.global_report.to_text.return_value = "GLOBAL FIT\n" + run.individual_reports = {} + return run @pytest.fixture @@ -70,22 +75,24 @@ def test_parser_accepts_basic_args(): def test_main_runs_with_minimal_args(mock_loader, mock_fitter, mock_report): cli.main(["--input", "fake.csv"]) - # ECOFFitter MUST be called at least once - assert cli.ECOFFitter.called - - # global fitter generate() must run once - mock_fitter.generate.assert_called_once_with(percentile=99.0) - - # one GenerateReport created - cli.GenerateReport.from_fitter.assert_called() + mock_loader.assert_called_once_with( + "fake.csv", + params=None, + dilution_factor=2, + distributions=1, + boundary_support=1, + percentile=99.0, + fit_individual=False, + density=False, + ) def test_main_invalid_percentile_prints_error(mock_loader, monkeypatch, capsys): - mock_fitter = MagicMock() - mock_fitter.generate.side_effect = AssertionError("percentile must be between 0 and 100") + def fail_run(*args, **kwargs): + raise AssertionError("percentile must be between 0 and 100") - monkeypatch.setattr(cli, "ECOFFitter", MagicMock(return_value=mock_fitter)) + monkeypatch.setattr(cli, "run_ecoff_analysis", MagicMock(side_effect=fail_run)) cli.main(["--input", "data.csv", "--percentile", "200"]) diff --git a/tests/test_utils.py b/tests/test_utils.py old mode 100644 new mode 100755 index 06a9aae..e51f4c5 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -19,12 +19,12 @@ def test_read_input_strict_numeric(tmp_path): df = read_input(str(csv_path)) # Check column types - assert df["MIC"].dtype == object # stringified, not numeric - assert df["observations"].dtype == int # forced to int + df["MIC"] = df["MIC"].astype(object) # stringified, not numeric + assert df["observations"].dtype == float # current reader preserves numeric values # Exact expected values assert df["MIC"].tolist() == ["1", ">2", "3.5"] - assert df["observations"].tolist() == [3, 4, 0] + assert df["observations"].tolist() == [3.0, 4.7, 0.0] def test_read_input_single_column_conversion(): diff --git a/tests/test_workflow.py b/tests/test_workflow.py new file mode 100644 index 0000000..3886260 --- /dev/null +++ b/tests/test_workflow.py @@ -0,0 +1,140 @@ +from unittest.mock import MagicMock + +import numpy as np +import pandas as pd +import pytest + +import ecoff_fitter.workflow as workflow +from ecoff_fitter.utils import PreparedInput + + +def _fitter(score=100.0, pis=(1.0,), mus=(0.0,), sigmas=(1.0,), result=(2.0, 1.0)): + fitter = MagicMock() + fitter.generate.return_value = result + fitter.model_summary.return_value = {"bic": score, "aic": score} + fitter.pis_ = np.asarray(pis) + fitter.mus_ = np.asarray(mus) + fitter.sigmas_ = np.asarray(sigmas) + return fitter + + +def test_run_ecoff_analysis_fixed_components_with_individual_fits(monkeypatch): + global_df = pd.DataFrame({"MIC": ["1"], "observations": [5]}) + individual_df = pd.DataFrame({"MIC": ["1"], "observations": [2]}) + prepared = PreparedInput(global_df, {"assay": individual_df}) + monkeypatch.setattr(workflow, "prepare_input", lambda data, sheet_name=None: prepared) + + global_fitter = _fitter() + individual_fitter = _fitter() + fitter_factory = MagicMock(side_effect=[global_fitter, individual_fitter]) + monkeypatch.setattr(workflow, "ECOFFitter", fitter_factory) + monkeypatch.setattr( + workflow.GenerateReport, + "from_fitter", + MagicMock(side_effect=lambda fitter, result: (fitter, result)), + ) + + run = workflow.run_ecoff_analysis( + "input", + distributions=2, + percentile=97.5, + fit_individual=True, + density=True, + options={"max_iter": 10}, + ) + + assert run.selected_k == 2 + assert run.global_fitter is global_fitter + assert run.individual_fits["assay"] == (individual_fitter, individual_fitter.generate.return_value) + assert set(run.individual_reports) == {"assay"} + assert global_fitter.density is True + assert individual_fitter.density is True + assert fitter_factory.call_count == 2 + global_fitter.generate.assert_called_once_with( + percentile=97.5, options={"max_iter": 10} + ) + + +def test_run_ecoff_analysis_skips_individual_fits(monkeypatch): + prepared = PreparedInput( + pd.DataFrame({"MIC": ["1"], "observations": [5]}), + {"assay": pd.DataFrame({"MIC": ["1"], "observations": [2]})}, + ) + monkeypatch.setattr(workflow, "prepare_input", lambda data, sheet_name=None: prepared) + fitter = _fitter() + fitter_factory = MagicMock(return_value=fitter) + monkeypatch.setattr(workflow, "ECOFFitter", fitter_factory) + monkeypatch.setattr(workflow.GenerateReport, "from_fitter", MagicMock()) + + run = workflow.run_ecoff_analysis("input", fit_individual=False) + + assert run.individual_fits == {} + assert run.individual_reports == {} + assert fitter_factory.call_count == 1 + assert run.global_report is not None + + +def test_run_ecoff_analysis_auto_selection(monkeypatch): + prepared = PreparedInput( + pd.DataFrame({"MIC": ["1"], "observations": [5]}), {} + ) + monkeypatch.setattr(workflow, "prepare_input", lambda data, sheet_name=None: prepared) + fitter = _fitter() + result = (2.0, 1.0) + select = MagicMock(return_value=(3, 10.0, fitter, result)) + monkeypatch.setattr(workflow, "select_best_k", select) + monkeypatch.setattr(workflow.GenerateReport, "from_fitter", MagicMock()) + + run = workflow.run_ecoff_analysis( + "input", distributions="auto", max_distributions=4, fit_individual=False + ) + + assert run.selected_k == 3 + assert run.global_fitter is fitter + assert run.global_result == result + select.assert_called_once() + + +def test_select_best_k_raises_when_no_observations(): + data = pd.DataFrame({"MIC": ["1", "2"], "observations": [0, 0]}) + with pytest.raises(ValueError, match="No MIC observations"): + workflow.select_best_k(data) + + +def test_select_best_k_stops_when_score_improvement_is_too_small(monkeypatch): + data = pd.DataFrame({"MIC": ["1", "2", "4"], "observations": [3, 5, 2]}) + first, second = _fitter(score=100), _fitter(score=90) + factory = MagicMock(side_effect=[first, second]) + monkeypatch.setattr(workflow, "ECOFFitter", factory) + + k, score, fitter, result = workflow.select_best_k( + data, max_distributions=3, min_delta=15 + ) + + assert (k, score, fitter, result) == (1, 100, first, first.generate.return_value) + assert factory.call_count == 2 + + +@pytest.mark.parametrize( + "pis,mus,sigmas", + [ + ((0.01, 0.99), (0.0, 3.0), (1.0, 1.0)), + ((0.5, 0.5), (0.0, 0.1), (1.0, 1.0)), + ], +) +def test_select_best_k_rejects_small_or_overlapping_component( + monkeypatch, pis, mus, sigmas +): + data = pd.DataFrame({"MIC": ["1", "2", "4"], "observations": [3, 5, 2]}) + first = _fitter(score=100) + second = _fitter(score=70, pis=pis, mus=mus, sigmas=sigmas) + factory = MagicMock(side_effect=[first, second]) + monkeypatch.setattr(workflow, "ECOFFitter", factory) + + selected = workflow.select_best_k( + data, max_distributions=2, min_delta=15, min_pi=0.05, min_separation=1.0 + ) + + assert selected[0] == 1 + assert selected[2] is first +