From c9470f618a39a3869e50ab3323f9dd66188a2b2c Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Thu, 2 Apr 2026 15:28:56 +0100 Subject: [PATCH 1/4] WIP: density + optional individual fits --- demo_files/censored.txt | 20 ++--- demo_files/output.pdf | Bin 44088 -> 30172 bytes gui.py | 149 ++++++++++++++++++++----------------- src/ecoff_fitter/cli.py | 60 ++++++++------- src/ecoff_fitter/core.py | 2 +- src/ecoff_fitter/graphs.py | 42 ++++++++--- src/ecoff_fitter/report.py | 3 + tests/test_cli.py | 29 +++++++- 8 files changed, 190 insertions(+), 115 deletions(-) diff --git a/demo_files/censored.txt b/demo_files/censored.txt index d04ffcc..2306cd8 100644 --- 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/output.pdf b/demo_files/output.pdf index acee096c9370f4a78921eefc352842e18b0adb54..9f45eca7270ec1fa9bf6109964306d5d122b6080 100644 GIT binary patch delta 7535 zcmZu!2{@G9`!-54mbTZDPkIYcX!fmaWyzYdmWaU^H1?saV<}Rh92BDLSxZADX(Ne9 zs1VxA64j?jw*QRg>lgm-b#=|@exLW;=Q-!TpXa#I$=@@CxDt(Er5#9+(OrG))ui=% zIkg+-*9PwD7G&JDsaU?Yq*w6Pii5#lyVIKPdrwSG>N-DRS{^nrbxJv7#V_<(tOzH! z(eym|%(Dc|?UNsRhuB`3>OQ7-de!-nQq1}BVfHjEjO z)_XLs?{O@Y_ct`F*9PVdY_ISG1?&iY_Cx$f%g_|e)LN+G74(t6{m{b}Up0a{L zyw_w=JYL?rO(yM1@%sbq6Fu^Y`AS(8C1btUB?Ed`R|7|6<-XeqgzU@ce1<7=&?)QGF ze$72Pk%wF&0(Jb}Ex8%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j+*|nynB4 zIC}H^r!jCo{{KAu_p@+*bc*Vada!@FWe6OOPKy0+J)qH%8Yzf+fB%H}AcFk=uMKP0 zZ5W1uyMLjxmoAZbk|=#Z19S?|Kgg0X23mLS4|MAfmvn;0(siY&7pXg)kCe{DI%)zbJAtvrK4l#6Zn}0-Bu4-=G72fJ^WWiM^g$EbqMM`s-+iyk_VF#-8 zz@vs|q6<_ZE= 1: - text += global_report.to_text("GLOBAL FIT", verbose=verbose) - text += "\nINDIVIDUAL FITS:\n-------------------------------------\n" + text += global_report.to_text("GLOBAL FIT", verbose=verbose) - # Individual fits - for name, (fitter, result) in individual_results.items(): - rep = GenerateReport.from_fitter(fitter, result) - text += rep.to_text(label=name, verbose=verbose) + if individual_results: + text += "\nINDIVIDUAL FITS:\n-------------------------------------\n" + for name, (fitter, result) in individual_results.items(): + rep = GenerateReport.from_fitter(fitter, result) + text += rep.to_text(label=name, verbose=verbose) if outfile: validate_output_path(outfile) - if len(individual_results.keys())==1: + + if not self.fit_individual_var.get(): if outfile.endswith(".pdf"): global_report.save_pdf(outfile) else: global_report.write_out(outfile) - elif (len(individual_results.keys()))>1: - # Build section reports + else: 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) if outfile.endswith(".pdf"): combined.save_pdf() @@ -210,50 +225,50 @@ def run_ecoff(self): 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) + 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], + density=density, # or False + 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) + + if self.fit_individual_var.get(): + 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], + density=density, # or False + 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/src/ecoff_fitter/cli.py b/src/ecoff_fitter/cli.py index ef7cd7a..93a1a55 100644 --- a/src/ecoff_fitter/cli.py +++ b/src/ecoff_fitter/cli.py @@ -15,7 +15,6 @@ from unittest.mock import MagicMock, patch - def build_parser() -> argparse.ArgumentParser: """Create and configure the command-line argument parser.""" parser = argparse.ArgumentParser( @@ -58,12 +57,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.", @@ -85,71 +94,70 @@ def main(argv: Optional[List[str]] = None) -> None: try: data_dict = read_multi_obs_input(args.input) - df_global = data_dict['global'] - df_individual = data_dict['individual'] + df_global = data_dict["global"] + df_individual = data_dict["individual"] global_fitter = ECOFFitter( input=df_global, params=args.params, distributions=args.distributions, boundary_support=args.boundary_support, - dilution_factor=args.dilution_factor + dilution_factor=args.dilution_factor, ) 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) + if args.fit_individual: + 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" global_report = GenerateReport.from_fitter(global_fitter, global_result) - if len(individual_results) > 1: - text += global_report.to_text("GLOBAL FIT", verbose=args.verbose) + text += global_report.to_text("GLOBAL FIT", verbose=args.verbose) + + if individual_results: 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=args.verbose) - + 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 args.fit_individual: if args.outfile.endswith(".pdf"): global_report.save_pdf(args.outfile) else: global_report.write_out(args.outfile) - elif (len(individual_results.keys()))>1: - # Build section reports + else: 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) 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 index 33406db..6bafa8d 100644 --- a/src/ecoff_fitter/core.py +++ b/src/ecoff_fitter/core.py @@ -265,7 +265,7 @@ def generate( options (dict): Optional fit settings. Returns: - tuple: ECOFF value, z-percentile, and fitted parameters. + tuple: ECOFF value, z-percentile, mus, and sigmas. """ if hasattr(self, "percentile"): diff --git a/src/ecoff_fitter/graphs.py b/src/ecoff_fitter/graphs.py index d5f85fa..6723f40 100644 --- a/src/ecoff_fitter/graphs.py +++ b/src/ecoff_fitter/graphs.py @@ -17,6 +17,7 @@ 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: """ @@ -86,6 +87,9 @@ def plot_mic_distribution( 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 + # --------------------------------------------------- # --------------------------------------------------- # Deduplicate plotting intervals and compute counts # --------------------------------------------------- @@ -97,15 +101,29 @@ def plot_mic_distribution( 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() + + 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", @@ -165,14 +183,18 @@ def plot_mic_distribution( mixture_pdf = np.sum(component_pdfs, axis=0) - scale = max(counts) / np.max(mixture_pdf) - - if len(component_pdfs) > 1: + if density: 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") + ax.plot(x_values, comp, lw=2, label=f"Component {i}") + ax.plot(x_values, mixture_pdf, "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 @@ -181,7 +203,7 @@ def plot_mic_distribution( if np.any(left_censored): ax.margins(x=0) ax.set_xlim(axis_min, axis_max) - ax.set_ylabel("Counts") + ax.set_ylabel(ylabel) xticks = ax.get_xticks() mic_labels = [f"{dilution_factor ** x:.2g}" for x in xticks] diff --git a/src/ecoff_fitter/report.py b/src/ecoff_fitter/report.py index e24bc75..e800af7 100644 --- a/src/ecoff_fitter/report.py +++ b/src/ecoff_fitter/report.py @@ -20,6 +20,7 @@ class GenerateReport: 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": @@ -41,6 +42,7 @@ def from_fitter(cls, fitter: Any, result: Tuple[Any, ...]) -> "GenerateReport": fitter=fitter, ecoff=ecoff, z=(z0, z1, z2), + density=getattr(fitter, "density", False), ) @property @@ -150,6 +152,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, ) diff --git a/tests/test_cli.py b/tests/test_cli.py index 16c9145..c3f60ee 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -30,6 +30,10 @@ def mock_fitter(monkeypatch): def mock_report(monkeypatch): """Mock GenerateReport.from_fitter.""" report_instance = MagicMock() + report_instance.to_text.return_value = "GLOBAL FIT\n" + report_instance.write_out = MagicMock() + report_instance.save_pdf = MagicMock() + report_cls = MagicMock() report_cls.from_fitter.return_value = report_instance @@ -104,9 +108,32 @@ def fake_loader(path): 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_fitter, mock_report, mock_validate): + fake_global = MagicMock() + + def fake_loader(path): + return { + "global": fake_global, + "individual": { + "A": MagicMock(), + "B": MagicMock(), + }, + } + + monkeypatch.setattr(cli, "read_multi_obs_input", fake_loader) + + combined_cls = MagicMock() + monkeypatch.setattr(cli, "CombinedReport", combined_cls) + + cli.main(["--input", "fake.csv", "--outfile", "combined.pdf"]) + + combined_cls.assert_not_called() + mock_report.save_pdf.assert_called_once_with("combined.pdf") \ No newline at end of file From b4af69f52d4637401ebb06d1500dfea5c4ba2ccc Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Thu, 2 Apr 2026 15:48:41 +0100 Subject: [PATCH 2/4] minor --- tests/test_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_utils.py b/tests/test_utils.py index 06a9aae..23b6f67 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -19,7 +19,7 @@ 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 + df["MIC"] = df["MIC"].astype(object) # stringified, not numeric assert df["observations"].dtype == int # forced to int # Exact expected values From 069e7e52e6978914dff77e76774025215f324c70 Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Sun, 18 Oct 2026 18:00:40 +0100 Subject: [PATCH 3/4] intreg tests docs types --- .github/workflows/ci.yml | 0 .github/workflows/gui-build.yml | 0 .github/workflows/mypy.yml | 0 .github/workflows/pypi.yaml | 0 .gitignore | 0 LICENSE | 0 README.md | 204 ++++++++++------------ demo_files/censored.txt | 0 demo_files/demo_input.xlsx | Bin demo_files/multi_assay.txt | 0 demo_files/output.pdf | Bin demo_files/output.txt | 0 demo_files/params.txt | 0 demo_files/uncensored.txt | 0 demo_files/unimodal.txt | 0 env.yml | 0 gui.py | 91 ++++------ pyproject.toml | 0 src/ecoff_fitter/__init__.py | 47 +++-- src/ecoff_fitter/__main__.py | 0 src/ecoff_fitter/cli.py | 68 +++----- src/ecoff_fitter/core.py | 63 ++++--- src/ecoff_fitter/defence.py | 30 +++- src/ecoff_fitter/graphs.py | 297 +++++++++++++++++++++++++++----- src/ecoff_fitter/mixture.py | 58 ++++++- src/ecoff_fitter/report.py | 69 +++++++- src/ecoff_fitter/utils.py | 267 ++++++++++++++-------------- src/ecoff_fitter/workflow.py | 261 ++++++++++++++++++++++++++++ src/ecoff_fitter/wts.py | 0 tests/test_cli.py | 94 +++------- tests/test_defence.py | 0 tests/test_ecoff_fitter.py | 0 tests/test_graphs.py | 0 tests/test_report.py | 39 +++-- tests/test_utils.py | 4 +- tests/test_workflow.py | 140 +++++++++++++++ 36 files changed, 1187 insertions(+), 545 deletions(-) mode change 100644 => 100755 .github/workflows/ci.yml mode change 100644 => 100755 .github/workflows/gui-build.yml mode change 100644 => 100755 .github/workflows/mypy.yml mode change 100644 => 100755 .github/workflows/pypi.yaml mode change 100644 => 100755 .gitignore mode change 100644 => 100755 LICENSE mode change 100644 => 100755 README.md mode change 100644 => 100755 demo_files/censored.txt mode change 100644 => 100755 demo_files/demo_input.xlsx mode change 100644 => 100755 demo_files/multi_assay.txt mode change 100644 => 100755 demo_files/output.pdf mode change 100644 => 100755 demo_files/output.txt mode change 100644 => 100755 demo_files/params.txt mode change 100644 => 100755 demo_files/uncensored.txt mode change 100644 => 100755 demo_files/unimodal.txt mode change 100644 => 100755 env.yml mode change 100644 => 100755 gui.py mode change 100644 => 100755 pyproject.toml mode change 100644 => 100755 src/ecoff_fitter/__init__.py mode change 100644 => 100755 src/ecoff_fitter/__main__.py mode change 100644 => 100755 src/ecoff_fitter/cli.py mode change 100644 => 100755 src/ecoff_fitter/core.py mode change 100644 => 100755 src/ecoff_fitter/defence.py mode change 100644 => 100755 src/ecoff_fitter/graphs.py mode change 100644 => 100755 src/ecoff_fitter/mixture.py mode change 100644 => 100755 src/ecoff_fitter/report.py mode change 100644 => 100755 src/ecoff_fitter/utils.py create mode 100755 src/ecoff_fitter/workflow.py mode change 100644 => 100755 src/ecoff_fitter/wts.py mode change 100644 => 100755 tests/test_cli.py mode change 100644 => 100755 tests/test_defence.py mode change 100644 => 100755 tests/test_ecoff_fitter.py mode change 100644 => 100755 tests/test_graphs.py mode change 100644 => 100755 tests/test_report.py mode change 100644 => 100755 tests/test_utils.py create mode 100644 tests/test_workflow.py 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 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 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 e8aa912..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): @@ -157,97 +155,68 @@ def run_ecoff(self): 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 = {} - - if self.fit_individual_var.get(): - 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) - - text += global_report.to_text("GLOBAL FIT", verbose=verbose) - - if individual_results: + if run.individual_reports: text += "\nINDIVIDUAL FITS:\n-------------------------------------\n" - 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 not self.fit_individual_var.get(): + 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) + run.global_report.write_out(outfile) else: - indiv_reports = { - name: GenerateReport.from_fitter(fitter, result) - for name, (fitter, result) in individual_results.items() - } - - combined = CombinedReport(outfile, global_report, indiv_reports) + 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() + # Global plot 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() + gl_low, gl_high, gl_w = run.global_fitter.define_intervals() plot_mic_distribution( low_log=gl_low, high_log=gl_high, - weights=global_fitter.weights_, + weights=run.global_fitter.weights_, dilution_factor=dilution_factor, - mus=global_fitter.mus_, - sigmas=global_fitter.sigmas_, - pis=global_fitter.pis_, - log2_ecoff=global_result[1], - density=density, # or False - ax=axg + 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 individual_results.items(): + for col, (fitter, result) in run.individual_fits.items(): fig_i = plt.Figure(figsize=(6, 3), dpi=100) axi = fig_i.add_subplot(111) @@ -261,8 +230,8 @@ def run_ecoff(self): sigmas=fitter.sigmas_, pis=fitter.pis_, log2_ecoff=result[1], - density=density, # or False - ax=axi + density=density, + ax=axi, ) axi.set_title(f"{col}") 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 93a1a55..42be101 --- a/src/ecoff_fitter/cli.py +++ b/src/ecoff_fitter/cli.py @@ -13,6 +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: @@ -87,68 +88,49 @@ 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 = {} - - if args.fit_individual: - 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) - - text += global_report.to_text("GLOBAL FIT", verbose=args.verbose) - - if individual_results: + 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=args.verbose) + for name, report in run.individual_reports.items(): + text += report.to_text(label=name, verbose=args.verbose) if args.outfile: validate_output_path(args.outfile) - if not args.fit_individual: + 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) + run.global_report.write_out(args.outfile) else: - indiv_reports = { - name: GenerateReport.from_fitter(fitter, result) - for name, (fitter, result) in individual_results.items() - } - combined = CombinedReport(args.outfile, global_report, indiv_reports) + combined = CombinedReport( + args.outfile, + run.global_report, + run.individual_reports, + ) if args.outfile.endswith(".pdf"): combined.save_pdf() else: diff --git a/src/ecoff_fitter/core.py b/src/ecoff_fitter/core.py old mode 100644 new mode 100755 index 6bafa8d..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, mus, and sigmas. + 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 6723f40..897e0d9 --- a/src/ecoff_fitter/graphs.py +++ b/src/ecoff_fitter/graphs.py @@ -21,8 +21,37 @@ def plot_mic_distribution( 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 @@ -43,53 +72,93 @@ 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 = 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_high = ( + finite_high_vals.max() + if len(finite_high_vals) + else 0 + ) - # Axis left bound + finite_low = ( + finite_low_vals.min() + if len(finite_low_vals) + else 0 + ) + + # --------------------------------------------------- + # Determine local plotting bounds + # --------------------------------------------------- + + # 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 - # --------------------------------------------------- # --------------------------------------------------- # Deduplicate plotting intervals and compute counts # --------------------------------------------------- @@ -97,15 +166,33 @@ 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 = 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) + 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), @@ -115,7 +202,10 @@ def plot_mic_distribution( ) ylabel = "Probability density" else: - heights = np.asarray(counts, dtype=float) + heights = np.asarray( + counts, + dtype=float, + ) ylabel = "Counts" # --------------------------------------------------- @@ -131,32 +221,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", + ), ) # --------------------------------------------------- @@ -174,45 +301,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, + ) 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") + + 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", + ) + else: - scale = max(heights) / np.max(mixture_pdf) if np.max(mixture_pdf) > 0 else 1.0 + + 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") + + 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") + + 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) + + # 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 e800af7..e58d52b --- a/src/ecoff_fitter/report.py +++ b/src/ecoff_fitter/report.py @@ -13,8 +13,8 @@ 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 @@ -29,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 @@ -47,26 +55,32 @@ def from_fitter(cls, fitter: Any, result: Tuple[Any, ...]) -> "GenerateReport": @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) @@ -74,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], @@ -86,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 = [] @@ -119,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) @@ -133,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, @@ -182,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)"] @@ -210,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 @@ -225,6 +272,9 @@ def write_out(self) -> None: - Individual fit summaries Uses GenerateReport.to_text() for formatting consistency. + + Returns: + None """ lines: list[str] = [] @@ -246,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..7b69754 --- /dev/null +++ b/src/ecoff_fitter/workflow.py @@ -0,0 +1,261 @@ +from dataclasses import dataclass +from typing import Any, Dict, Tuple + +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: + global_fitter = ECOFFitter( + input=prepared.global_df, + params=params, + dilution_factor=dilution_factor, + distributions=distributions, + boundary_support=boundary_support, + ) + global_result = global_fitter.generate(percentile=percentile, options=options) + k = distributions + + 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=distributions, + boundary_support=boundary_support, + ) + result = fitter.generate(percentile=percentile, options=options) + + 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) + + 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 c3f60ee..6f6abe5 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4,41 +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_instance.to_text.return_value = "GLOBAL FIT\n" - report_instance.write_out = MagicMock() - report_instance.save_pdf = 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 @@ -60,48 +32,35 @@ 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() @@ -116,19 +75,10 @@ def fake_loader(path): combined_instance.save_pdf.assert_called_once() -def test_main_default_skips_individual_fits(monkeypatch, mock_fitter, mock_report, mock_validate): - fake_global = MagicMock() - - def fake_loader(path): - return { - "global": fake_global, - "individual": { - "A": MagicMock(), - "B": MagicMock(), - }, - } - - monkeypatch.setattr(cli, "read_multi_obs_input", fake_loader) +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) @@ -136,4 +86,4 @@ def fake_loader(path): cli.main(["--input", "fake.csv", "--outfile", "combined.pdf"]) combined_cls.assert_not_called() - mock_report.save_pdf.assert_called_once_with("combined.pdf") \ No newline at end of file + 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 23b6f67..e51f4c5 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -20,11 +20,11 @@ def test_read_input_strict_numeric(tmp_path): # Check column types df["MIC"] = df["MIC"].astype(object) # stringified, not numeric - assert df["observations"].dtype == int # forced to int + 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 + From a1236a4d8a5c98f57348798a4e1c6534460ab8e2 Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Sun, 18 Oct 2026 18:04:43 +0100 Subject: [PATCH 4/4] mypy --- src/ecoff_fitter/graphs.py | 16 ++++++---------- src/ecoff_fitter/workflow.py | 14 ++++++++------ 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/ecoff_fitter/graphs.py b/src/ecoff_fitter/graphs.py index 897e0d9..9f1a118 100755 --- a/src/ecoff_fitter/graphs.py +++ b/src/ecoff_fitter/graphs.py @@ -81,17 +81,13 @@ def plot_mic_distribution( finite_high_vals = high_log[np.isfinite(high_log)] finite_low_vals = low_log[np.isfinite(low_log)] - finite_high = ( - finite_high_vals.max() - if len(finite_high_vals) - else 0 - ) + finite_high = 0.0 + if finite_high_vals.size > 0: + finite_high = float(np.max(finite_high_vals)) - 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 diff --git a/src/ecoff_fitter/workflow.py b/src/ecoff_fitter/workflow.py index 7b69754..33ea32d 100755 --- a/src/ecoff_fitter/workflow.py +++ b/src/ecoff_fitter/workflow.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from typing import Any, Dict, Tuple +from typing import Any, Dict, Tuple, cast import numpy as np @@ -94,17 +94,18 @@ def run_ecoff_analysis( ) else: + fixed_distributions = cast(int, distributions) global_fitter = ECOFFitter( input=prepared.global_df, params=params, dilution_factor=dilution_factor, - distributions=distributions, + distributions=fixed_distributions, boundary_support=boundary_support, ) global_result = global_fitter.generate(percentile=percentile, options=options) - k = distributions + k = fixed_distributions - global_fitter.density = density + setattr(global_fitter, "density", density) global_report = GenerateReport.from_fitter(global_fitter, global_result) @@ -130,12 +131,12 @@ def run_ecoff_analysis( input=subdf, params=params, dilution_factor=dilution_factor, - distributions=distributions, + distributions=cast(int, distributions), boundary_support=boundary_support, ) result = fitter.generate(percentile=percentile, options=options) - fitter.density = density + setattr(fitter, "density", density) individual_fits[name] = (fitter, result) individual_reports[name] = GenerateReport.from_fitter(fitter, result) @@ -258,4 +259,5 @@ def select_best_k( best = (k, score, fitter, result) + assert best is not None return best