From b22ff7ee77c17d1395fa4b5e0891aacfa6916a40 Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Sun, 18 Oct 2026 21:04:27 +0100 Subject: [PATCH 1/4] initial --- README.md | 33 ++- src/ecoff_fitter/__init__.py | 4 +- src/ecoff_fitter/cli.py | 68 ++++- src/ecoff_fitter/defence.py | 21 ++ src/ecoff_fitter/ecoffinder_core.py | 406 ++++++++++++++++++++++++++++ src/ecoff_fitter/range_search.py | 184 +++++++++++++ src/ecoff_fitter/utils.py | 74 ++++- src/ecoff_fitter/workflow.py | 93 +++++-- 8 files changed, 826 insertions(+), 57 deletions(-) create mode 100644 src/ecoff_fitter/ecoffinder_core.py create mode 100644 src/ecoff_fitter/range_search.py diff --git a/README.md b/README.md index cd9da3b..9c283b9 100755 --- a/README.md +++ b/README.md @@ -108,6 +108,29 @@ for assay, report in run.individual_reports.items(): print(report.to_text(label=assay)) ``` +Use the ECOFFinder workbook-style range search through the same workflow by +setting `method="ecoffinder"`. The selected wild-type range is found with +least squares; `intervals=True` then refits that range using ECOFFitter's +interval regression: + +```python +run = run_ecoff_analysis( + "demo_files/multi_assay.txt", + method="ecoffinder", + detection_level=10, + intervals=True, + fit_individual=True, +) + +print(run.global_report.to_text(verbose=True)) +``` + +ECOFFinder fits one wild-type distribution and does not support +`distributions="auto"`. It accepts parameter mappings or YAML/TXT files with +`dilution_factor`, `boundary_support`, `percentile`, `detection_level`, +`cumulative`, `first_best`, and `intervals`. File values override matching +arguments. A `distributions` entry is accepted only when set to `1`. + 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 @@ -122,7 +145,8 @@ or more assay columns: ```bash ecoff-fitter \ --input demo_files/multi_assay.txt \ - --distributions 2 \ + --method ecoffinder \ + --intervals \ --percentile 99 \ --fit_individual \ --outfile demo_files/output.pdf @@ -134,13 +158,18 @@ 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. | +| `--method METHOD` | `ecoffitter` | Fitting method: `ecoffitter` or `ecoffinder`. | +| `--params PARAMS` | None | YAML or TXT parameter file; supported keys depend on the selected method, and file values override matching options. | | `--dilution_factor N` | `2` | Ratio between adjacent MIC dilution steps. | | `--distributions K` | `1` | Number of normal components to fit. The CLI accepts an integer; automatic selection is available in the Python workflow API. | | `--boundary_support N` | `1` | Number of dilution steps used to extend censoring bounds. Use `None` in a parameter file for unbounded tails. | | `--percentile P` | `99.0` | Percentile used to calculate the ECOFF; must be between 0 and 100. | | `--fit_individual` | Off | Fit each assay column as well as the aggregate observations. | | `--density` | Off | Plot probability density instead of counts. | +| `--detection_level P` | `10.0` | Minimum eligible ECOFFinder mode size as a percentage of observations. | +| `--cumulative` / `--no-cumulative` | On | Use cumulative counts in ECOFFinder range fitting, or per-dilution frequencies. | +| `--first_best` | Off | Stop ECOFFinder range search after its score begins increasing from its best value. | +| `--intervals` | Off | Refit ECOFFinder's selected range using interval regression. | | `--outfile PATH` | None | Write a text report (`.txt`) or PDF report (`.pdf`). | | `--verbose` | Off | Include model details in printed text output. | diff --git a/src/ecoff_fitter/__init__.py b/src/ecoff_fitter/__init__.py index b020035..21aab26 100755 --- a/src/ecoff_fitter/__init__.py +++ b/src/ecoff_fitter/__init__.py @@ -28,10 +28,12 @@ from importlib.metadata import PackageNotFoundError, version from .core import ECOFFitter +from .ecoffinder_core import ECOFFinder from .workflow import ECOFFRun, run_ecoff_analysis __all__ = [ "ECOFFitter", + "ECOFFinder", "run_ecoff_analysis", "ECOFFRun", ] @@ -50,4 +52,4 @@ def main() -> None: if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/src/ecoff_fitter/cli.py b/src/ecoff_fitter/cli.py index 42be101..be255b2 100755 --- a/src/ecoff_fitter/cli.py +++ b/src/ecoff_fitter/cli.py @@ -32,12 +32,19 @@ def build_parser() -> argparse.ArgumentParser: "with columns 'MIC' and assay name." ), ) + parser.add_argument( + "--method", + choices=("ecoffitter", "ecoffinder"), + default="ecoffitter", + help="Fitting method to use (default: ECOFFitter).", + ) parser.add_argument( "--params", help=( - "Optional path to a parameter file (YAML, TXT, or key=value list) " - "defining dilution_factor, distributions, and boundary_support. " - "Overrides manual CLI options if provided." + "Optional YAML or TXT parameter file. ECOFFitter accepts " + "dilution_factor, distributions, boundary_support, and percentile; " + "ECOFFinder also accepts detection_level, cumulative, first_best, " + "and intervals. File values override matching options." ), ) parser.add_argument( @@ -50,7 +57,7 @@ def build_parser() -> argparse.ArgumentParser: "--distributions", type=int, default=1, - help="Number of normal components to fit.", + help="Number of normal components to fit with ECOFFitter; ECOFFinder uses one WT range.", ) parser.add_argument( "--boundary_support", @@ -63,6 +70,31 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="Plot MIC distribution as density rather than counts.", ) + parser.add_argument( + "--detection_level", + type=float, + default=10.0, + help="Minimum ECOFFinder mode size as a percentage of observations.", + ) + parser.add_argument( + "--cumulative", + action=argparse.BooleanOptionalAction, + default=True, + help=( + "Fit cumulative frequencies with ECOFFinder; use --no-cumulative " + "for per-dilution frequencies." + ), + ) + parser.add_argument( + "--first_best", + action="store_true", + help="Stop ECOFFinder range search after its score starts increasing.", + ) + parser.add_argument( + "--intervals", + action="store_true", + help="Refit ECOFFinder's selected range with interval regression.", + ) parser.add_argument( "--percentile", type=float, @@ -98,16 +130,24 @@ def main(argv: Optional[List[str]] = None) -> None: args = parser.parse_args(argv) try: - run = run_ecoff_analysis( - args.input, - params=args.params, - dilution_factor=args.dilution_factor, - distributions=args.distributions, - boundary_support=args.boundary_support, - percentile=args.percentile, - fit_individual=args.fit_individual, - density=args.density, - ) + workflow_args = { + "params": args.params, + "dilution_factor": args.dilution_factor, + "distributions": args.distributions, + "boundary_support": args.boundary_support, + "percentile": args.percentile, + "fit_individual": args.fit_individual, + "density": args.density, + } + if args.method == "ecoffinder": + workflow_args.update( + method=args.method, + detection_level=args.detection_level, + cumulative=args.cumulative, + first_best=args.first_best, + intervals=args.intervals, + ) + run = run_ecoff_analysis(args.input, **workflow_args) text = "\n\nECOFF RESULTS\n=====================================\n\n" text += run.global_report.to_text("GLOBAL FIT", verbose=args.verbose) diff --git a/src/ecoff_fitter/defence.py b/src/ecoff_fitter/defence.py index f65d502..5092abe 100755 --- a/src/ecoff_fitter/defence.py +++ b/src/ecoff_fitter/defence.py @@ -134,6 +134,27 @@ def validate_params( raise ValueError("boundary_support must be a non-negative integer or None.") +def validate_ecoffinder_params( + detection_level: float, + cumulative: bool, + first_best: bool, + intervals: bool, + percentile: float, +) -> None: + """Validate ECOFFinder-specific settings and the requested percentile.""" + if not isinstance(detection_level, (int, float)) or not 0 <= detection_level <= 100: + raise ValueError("detection_level must be between 0 and 100.") + for name, value in ( + ("cumulative", cumulative), + ("first_best", first_best), + ("intervals", intervals), + ): + if not isinstance(value, bool): + raise ValueError(f"{name} must be a boolean.") + if not isinstance(percentile, (int, float)) or not 0 < percentile < 100: + raise ValueError("percentile must be between 0 and 100.") + + def validate_output_path(path: str) -> bool: """Validate an output path and its containing directory. diff --git a/src/ecoff_fitter/ecoffinder_core.py b/src/ecoff_fitter/ecoffinder_core.py new file mode 100644 index 0000000..b134924 --- /dev/null +++ b/src/ecoff_fitter/ecoffinder_core.py @@ -0,0 +1,406 @@ +from typing import Any + +import numpy as np +import pandas as pd +from numpy.typing import NDArray +from scipy.stats import norm + +from ecoff_fitter.defence import ( + validate_ecoffinder_params, + validate_input_source, + validate_mic_data, + validate_params, + validate_params_source, +) +from ecoff_fitter.range_search import ECOFFinderRangeSearch +from ecoff_fitter.utils import prepare_input, read_ecoffinder_params + + +class ECOFFinder: + """Select a wild-type MIC range with the ECOFFinder workbook method. + + Candidate ranges are evaluated using cumulative least squares on the log2 + MIC scale. If ``intervals=True``, the selected range is then fitted with + interval regression using :class:`ECOFFitter`. + + The range-search implementation is an approximation pending validation + against reference outputs from the Excel workbook. + """ + + def __init__( + self, + input: Any, + dilution_factor: int = 2, + detection_level: float = 10.0, + cumulative: bool = True, + first_best: bool = False, + intervals: bool = False, + boundary_support: int | None = 1, + params: dict[str, Any] | str | None = None, + percentile: float = 99.9, + ) -> None: + """Initialize ECOFFinder with MIC frequencies. + + Args: + input: Input accepted by :func:`prepare_input`. + dilution_factor (int): Ratio between adjacent MIC dilution steps. + detection_level (float): Minimum mode frequency as a percentage + of the total count. + cumulative (bool): Fit cumulative counts when True; otherwise fit + per-dilution frequencies. + first_best (bool): Stop range search after the count-difference + criterion begins increasing from its best value. + intervals (bool): If True, use the selected ECOFFinder range to + fit an interval-regression model with ECOFFitter. + boundary_support (int | None): Number of dilution steps used by + the interval fit to extend censored bounds; None leaves the + tails unbounded. + params (dict[str, Any] | str | None): Optional mapping or YAML/TXT + file with common or ECOFFinder-specific settings. Values in + the parameter source override the corresponding arguments. + percentile (float): ECOFF percentile used by ``generate()`` when + no percentile is passed there. + + Raises: + ValueError: If the dilution factor, detection level, or MIC table + is invalid. + """ + validate_params_source(params) + + if params is not None: + ( + dilution_factor, + distributions, + detection_level, + cumulative, + first_best, + intervals, + boundary_support, + percentile, + ) = read_ecoffinder_params( + params, + dilution_factor, + detection_level, + cumulative, + first_best, + intervals, + boundary_support, + percentile, + ) + if distributions != 1: + raise ValueError("ECOFFinder supports one WT distribution only.") + + validate_params(dilution_factor, 1, boundary_support) + validate_ecoffinder_params( + detection_level, + cumulative, + first_best, + intervals, + percentile, + ) + + prepared = prepare_input(input) + if prepared.has_individuals: + raise ValueError( + "ECOFFinder expects one MIC distribution. Pass a single " + "MIC/observations table or one assay column." + ) + + self.obj_df = prepared.global_df.copy() + validate_input_source(self.obj_df) + validate_mic_data(self.obj_df) + self.dilution_factor = dilution_factor + self.detection_level = detection_level + self.cumulative = cumulative + self.first_best = first_best + self.intervals = intervals + self.boundary_support = boundary_support + self.percentile = float(percentile) + self.distributions = 1 + self.density = False + + self.pmic_: NDArray[np.float64] + self.observed_: NDArray[np.float64] + self.observed_cumulative_: NDArray[np.float64] + self.inclusion_range_: tuple[int, int] + self.mu_: float + self.sigma_: float + self.n_est_: float + self.sumsq_: float + self.ecoff_: float + self.z_percentile_: float + self.converged_: bool + self.result_: Any + self.interval_fitter_: Any + + def prepare_data(self) -> "ECOFFinder": + """Convert the input table to sorted pMIC and frequency arrays. + + Exact MIC rows are placed on the log2 scale. Censored values are + represented by their reported boundary for this workbook-style + frequency fit; this draft does not yet reproduce the workbook's + special handling of censored tail bins. + + Returns: + self: The instance with prepared pMIC and frequency arrays. + """ + df = self.obj_df.copy() + mic = df["MIC"].astype(str).str.strip() + + # The workbook frequency algorithm expects numeric MIC categories. + # Represent censored categories at their stated threshold for now. + mic = mic.str.replace("<=", "", regex=False) + mic = mic.str.replace(">", "", regex=False) + mic = mic.str.split("/").str[0] + mic_values = pd.to_numeric(mic, errors="raise").to_numpy(dtype=float) + + if np.any(mic_values <= 0): + raise ValueError("MIC values must be greater than zero.") + + pmic = np.log(mic_values) / np.log(self.dilution_factor) + frequencies = df["observations"].to_numpy(dtype=float) + order = np.argsort(pmic) + + self.pmic_ = pmic[order] + self.observed_ = frequencies[order] + self.observed_cumulative_ = np.cumsum(self.observed_) + return self + + def search_ranges(self) -> "ECOFFinder": + """Search candidate ranges and retain the best count-matching fit. + + Candidate iteration and least-squares scoring are handled by + :class:`ECOFFinderRangeSearch`. + + Returns: + self: The instance populated with the selected range and fit. + """ + range_search = ECOFFinderRangeSearch( + pmic=self.pmic_, + frequencies=self.observed_, + detection_level=self.detection_level, + cumulative=self.cumulative, + first_best=self.first_best, + ) + search_result = range_search.fit() + best = search_result["best"] + candidates = search_result["candidates"] + self.mode_idx_ = search_result["mode"] + self.inclusion_range_ = (best["start"], best["end"]) + self.selection_mu_ = best["mu"] + self.selection_sigma_ = best["sigma"] + self.selection_n_est_ = best["n_est"] + self.selection_sumsq_ = best["sumsq"] + self.mu_ = self.selection_mu_ + self.sigma_ = self.selection_sigma_ + self.n_est_ = self.selection_n_est_ + self.sumsq_ = best["sumsq"] + self.converged_ = best["success"] + self.result_ = best["result"] + self.range_fits_ = candidates + self.mus_ = np.array([self.mu_], dtype=float) + self.sigmas_ = np.array([self.sigma_], dtype=float) + self.pis_ = np.array([1.0], dtype=float) + return self + + def _selected_df(self) -> pd.DataFrame: + """Return original MIC rows within the selected inclusive range.""" + if not hasattr(self, "inclusion_range_"): + raise RuntimeError("Call search_ranges() before selecting MIC rows.") + + start, end = self.inclusion_range_ + selected_pmic = self.pmic_[start : end + 1] + selected_min = self.dilution_factor ** selected_pmic[0] + selected_max = self.dilution_factor ** selected_pmic[-1] + mic_values = self.obj_df["MIC"].astype(str).str.strip() + numeric_mic = mic_values.str.replace("<=", "", regex=False) + numeric_mic = numeric_mic.str.replace(">", "", regex=False) + numeric_mic = numeric_mic.str.split("/").str[0] + numeric_mic = pd.to_numeric(numeric_mic, errors="raise") + selected = (numeric_mic >= selected_min) & (numeric_mic <= selected_max) + selected_df = self.obj_df.loc[selected, ["MIC", "observations"]].copy() + + if selected_df.empty: + raise ValueError("The selected wild-type range contains no MIC rows.") + return selected_df + + def define_intervals(self) -> tuple[ + NDArray[np.floating], NDArray[np.floating], NDArray[np.floating] + ]: + """Return selected MIC rows as log-scale censoring intervals. + + Uses ECOFFitter's existing interval conversion so report plots retain + the input's left-, right-, and interval-censoring semantics. + + Returns: + tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + Lower bounds, upper bounds, and observation weights. + """ + from ecoff_fitter.core import ECOFFitter + + fitter = ECOFFitter( + input=self._selected_df(), + dilution_factor=self.dilution_factor, + distributions=1, + boundary_support=self.boundary_support, + ) + return fitter.define_intervals() + + def fit_intervals( + self, options: dict[str, Any] | None = None + ) -> "ECOFFinder": + """Fit the selected wild-type range with ECOFFitter interval regression. + + The range is selected by the ECOFFinder least-squares search. Rows + outside that selected range are excluded from the interval fit. + + Returns: + self: The instance with interval-regression estimates. + """ + from ecoff_fitter.core import ECOFFitter + + selected_df = self._selected_df() + + fitter = ECOFFitter( + input=selected_df, + dilution_factor=self.dilution_factor, + distributions=1, + boundary_support=self.boundary_support, + ) + fitter.fit(options=options) + + self.interval_fitter_ = fitter + self.mu_ = float(fitter.mus_[0]) + self.sigma_ = float(fitter.sigmas_[0]) + self.mus_ = fitter.mus_.copy() + self.sigmas_ = fitter.sigmas_.copy() + self.pis_ = fitter.pis_.copy() + self.n_est_ = float(np.sum(selected_df["observations"])) + self.loglike_ = fitter.loglike_ + self.converged_ = fitter.converged_ + self.result_ = fitter.model_ + return self + + def fit(self, options: dict[str, Any] | None = None) -> "ECOFFinder": + """Prepare input, select the WT range, and fit the selected data. + + Candidate ranges are always selected with the ECOFFinder cumulative + least-squares procedure. When ``intervals`` is True, ECOFFitter then + refits the MIC rows in the selected range using interval likelihood. + + Returns: + self: The fitted ECOFFinder instance. + """ + self.prepare_data() + self.search_ranges() + if self.intervals: + return self.fit_intervals(options=options) + return self + + def compute_ecoff(self, percentile: float | None = None) -> tuple[float, float]: + """Calculate the ECOFF at a percentile of the fitted WT distribution. + + Args: + percentile (float): Percentile between 0 and 100. + + Returns: + tuple[float, float]: ECOFF on the MIC scale and its log2 location. + """ + if percentile is None: + percentile = self.percentile + if not 0 < percentile < 100: + raise ValueError("percentile must be between 0 and 100.") + if not hasattr(self, "mu_"): + raise RuntimeError("Call fit() before compute_ecoff().") + + z_percentile = self.mu_ + norm.ppf(percentile / 100) * self.sigma_ + ecoff = float(self.dilution_factor**z_percentile) + self.ecoff_ = ecoff + self.z_percentile_ = float(z_percentile) + return ecoff, float(z_percentile) + + def generate( + self, + percentile: float | None = None, + options: dict[str, Any] | None = None, + ) -> tuple[Any, ...]: + """Fit the distribution and return ECOFF and model parameters. + + Args: + percentile (float | None): Percentile used to calculate the ECOFF; + defaults to the configured value. + options (dict[str, Any] | None): Optional ECOFFitter solver + settings; used when ``intervals=True``. + + Returns: + tuple[Any, ...]: ECOFF, log2 ECOFF, mean, standard deviation, + estimated WT count, and selected inclusive range. + """ + self.fit(options=options) + ecoff, z_percentile = self.compute_ecoff(percentile) + result = ( + ecoff, + z_percentile, + self.mu_, + self.sigma_, + self.n_est_, + self.inclusion_range_, + ) + self.generated_result_: tuple[Any, ...] = result + return result + + def make_report(self) -> Any: + """Create a :class:`GenerateReport` for the fitted ECOFFinder model. + + If ``generate()`` has already been called, its ECOFF result is used. + Otherwise the model is fitted if needed and a default 99.9th + percentile report result is created. + + Returns: + GenerateReport: Report using the existing ECOFFitter report tools. + """ + from ecoff_fitter.report import GenerateReport + + if not hasattr(self, "mu_"): + self.fit() + if not hasattr(self, "generated_result_"): + ecoff, z_percentile = self.compute_ecoff(self.percentile) + self.generated_result_ = ( + ecoff, + z_percentile, + self.mu_, + self.sigma_, + ) + return GenerateReport.from_fitter(self, self.generated_result_) + + def model_summary(self) -> dict[str, Any]: + """Return selected range, fitted parameters, and optimization status.""" + if not hasattr(self, "mu_"): + raise RuntimeError("Call fit() before model_summary().") + return { + "model_family": ( + "interval-censored normal" + if self.intervals + else "normal cumulative least squares" + ), + "model_type": "ECOFFinder range search", + "range_selection_method": "cumulative least squares", + "final_fit_method": ( + "interval regression" if self.intervals else "cumulative least squares" + ), + "dilution_factor": self.dilution_factor, + "detection_level": self.detection_level, + "cumulative": self.cumulative, + "inclusion_range": self.inclusion_range_, + "mean_log2_mic": self.mu_, + "sd_log2_mic": self.sigma_, + "estimated_wt_count": self.n_est_, + "range_selection_mean_log2_mic": self.selection_mu_, + "range_selection_sd_log2_mic": self.selection_sigma_, + "range_selection_estimated_count": self.selection_n_est_, + "sum_squared_error": self.selection_sumsq_, + "fit_method": ( + "interval regression" if self.intervals else "cumulative least squares" + ), + "converged": self.converged_, + } diff --git a/src/ecoff_fitter/range_search.py b/src/ecoff_fitter/range_search.py new file mode 100644 index 0000000..cee97ae --- /dev/null +++ b/src/ecoff_fitter/range_search.py @@ -0,0 +1,184 @@ +from typing import Any + +import numpy as np +from numpy.typing import NDArray +from scipy.optimize import least_squares +from scipy.stats import norm + + +class ECOFFinderRangeSearch: + """Find the WT inclusion range using the ECOFFinder least-squares method. + + This class owns mode detection, candidate range iteration, least-squares + fitting, and selection by the observed-versus-estimated count difference. + The current candidate-range iteration is an approximation pending + validation against reference workbook outputs. + """ + + def __init__( + self, + pmic: NDArray[np.float64], + frequencies: NDArray[np.float64], + detection_level: float = 10.0, + cumulative: bool = True, + first_best: bool = False, + ) -> None: + """Initialize the range search with sorted MIC frequencies. + + Args: + pmic (NDArray[np.float64]): Sorted log-dilution MIC values. + frequencies (NDArray[np.float64]): Frequency at each MIC value. + detection_level (float): Minimum eligible peak size as a + percentage of total observations. + cumulative (bool): Whether the least-squares fit uses cumulative + counts rather than per-dilution counts. + first_best (bool): Whether to stop when the count-difference + criterion starts increasing after its best value. + + Raises: + ValueError: If input arrays are not one-dimensional and equal in + length, or if no observations are present. + """ + self.pmic = np.asarray(pmic, dtype=float) + self.frequencies = np.asarray(frequencies, dtype=float) + if self.pmic.ndim != 1 or self.frequencies.ndim != 1: + raise ValueError("pMIC and frequencies must be one-dimensional.") + if self.pmic.shape != self.frequencies.shape: + raise ValueError("pMIC and frequencies must have the same length.") + if self.pmic.size == 0: + raise ValueError("At least one MIC value is required.") + + self.detection_level = detection_level + self.cumulative = cumulative + self.first_best = first_best + self.cumulative_frequencies = np.cumsum(self.frequencies) + + def _find_mode(self) -> int: + """Find the leftmost local mode meeting the detection threshold.""" + total = float(np.sum(self.frequencies)) + if total <= 0: + raise ValueError("No MIC observations available for fitting.") + + threshold = total * self.detection_level / 100 + local_modes = [] + for i, count in enumerate(self.frequencies): + left = self.frequencies[i - 1] if i > 0 else -np.inf + right = ( + self.frequencies[i + 1] if i + 1 < len(self.frequencies) else -np.inf + ) + if count >= left and count >= right and count >= threshold: + local_modes.append(i) + + if not local_modes: + raise ValueError("No MIC mode meets the configured detection level.") + return local_modes[0] + + def _initial_range(self, mode: int) -> tuple[int, int]: + """Set the initial range from the first count through above the mode.""" + nonzero = np.flatnonzero(self.frequencies > 0) + start = int(nonzero[0]) + end = min(mode + 1, len(self.pmic) - 1) + return start, max(start, end) + + def _initial_parameters(self, start: int, end: int) -> NDArray[np.float64]: + """Calculate starting values for mean, log-SD, and fitted count.""" + x = self.pmic[start : end + 1] + counts = self.frequencies[start : end + 1] + total = max(float(np.sum(counts)), 1.0) + weights = np.maximum(counts, 1e-12) + mu = float(np.average(x, weights=weights)) + sigma = float(np.sqrt(np.average((x - mu) ** 2, weights=weights))) + sigma = max(sigma, 0.1) + return np.array([mu, np.log(sigma), total], dtype=float) + + def _predicted_counts( + self, params: NDArray[np.float64], start: int, end: int + ) -> NDArray[np.float64]: + """Calculate cumulative or per-bin normal predictions.""" + mu, log_sigma, n_est = params + sigma = float(np.exp(log_sigma)) + x = self.pmic[start : end + 1] + + if self.cumulative: + predicted = n_est * norm.cdf(x, loc=mu, scale=sigma) + else: + lower = x - 0.5 + upper = x + 0.5 + predicted = n_est * ( + norm.cdf(upper, loc=mu, scale=sigma) + - norm.cdf(lower, loc=mu, scale=sigma) + ) + return np.asarray(predicted, dtype=float) + + def _fit_range( + self, + start: int, + end: int, + initial: NDArray[np.float64] | None = None, + ) -> dict[str, Any]: + """Fit the normal model to one candidate inclusion range.""" + if initial is None: + initial = self._initial_parameters(start, end) + + observed = ( + self.cumulative_frequencies[start : end + 1] + if self.cumulative + else self.frequencies[start : end + 1] + ) + + def residuals(params: NDArray[np.float64]) -> NDArray[np.float64]: + return observed - self._predicted_counts(params, start, end) + + result = least_squares( + residuals, + initial, + bounds=( + np.array([-9.0, np.log(0.1), 1.0]), + np.array([9.0, np.log(9.0), 1_000_000.0]), + ), + ) + mu, log_sigma, n_est = result.x + residual = residuals(result.x) + return { + "start": start, + "end": end, + "mu": float(mu), + "sigma": float(np.exp(log_sigma)), + "n_est": float(n_est), + "sumsq": float(np.sum(residual**2)), + "observed_count": float(np.sum(self.frequencies[start : end + 1])), + "success": bool(result.success), + "result": result, + } + + def fit(self) -> dict[str, Any]: + """Iterate candidate ranges and return the best count-matching fit. + + Returns: + dict[str, Any]: Selected fit and all candidate range fits. + """ + mode = self._find_mode() + start, initial_end = self._initial_range(mode) + last_nonzero = len(self.frequencies) - 1 + zero_rows = np.flatnonzero(self.frequencies[initial_end + 1 :] == 0) + if zero_rows.size: + last_nonzero = initial_end + int(zero_rows[0]) + + candidates = [] + params = None + best_difference = np.inf + for end in range(initial_end, max(initial_end, last_nonzero) + 1): + fit = self._fit_range(start, end, params) + params = np.array( + [fit["mu"], np.log(fit["sigma"]), fit["n_est"]], dtype=float + ) + difference = abs(fit["observed_count"] - fit["n_est"]) + fit["count_difference"] = difference + candidates.append(fit) + + if self.first_best and difference > best_difference: + break + best_difference = min(best_difference, difference) + + best = min(candidates, key=lambda fit: fit["count_difference"]) + return {"best": best, "candidates": candidates, "mode": mode} diff --git a/src/ecoff_fitter/utils.py b/src/ecoff_fitter/utils.py index 9d78b1e..7193fb6 100755 --- a/src/ecoff_fitter/utils.py +++ b/src/ecoff_fitter/utils.py @@ -181,9 +181,52 @@ def read_params( Raises: FileNotFoundError: If the specified file does not exist. ValueError: If file type is unsupported. - AssertionError: If ``params`` is not a dictionary after path handling. + ValueError: If ``params`` is not a mapping after path handling. """ + params = _load_params_mapping(params) + + # --- Apply defaults for any missing keys --- + dilution_factor = params.get("dilution_factor", dflt_dilution) + distributions = params.get("distributions", dflt_dists) + boundary_support = params.get("boundary_support", dflt_tails) + percentile = params.get("percentile", 99) + + return dilution_factor, distributions, boundary_support, percentile + + +def read_ecoffinder_params( + params: str | dict[str, Any], + dflt_dilution: int, + dflt_detection: float, + dflt_cumulative: bool, + dflt_first_best: bool, + dflt_intervals: bool, + dflt_tails: int | None, + dflt_percentile: float, +) -> tuple[int, Any, float, bool, bool, bool, int | None, float]: + """Read common and ECOFFinder-specific settings from a config source. + + Supported keys are ``dilution_factor``, ``distributions``, + ``detection_level``, ``cumulative``, ``first_best``, ``intervals``, + ``boundary_support``, and ``percentile``. ``distributions`` is included + so callers can reject mixture settings that ECOFFinder cannot use. + """ + values = _load_params_mapping(params) + return ( + values.get("dilution_factor", dflt_dilution), + values.get("distributions", 1), + values.get("detection_level", dflt_detection), + values.get("cumulative", dflt_cumulative), + values.get("first_best", dflt_first_best), + values.get("intervals", dflt_intervals), + values.get("boundary_support", dflt_tails), + values.get("percentile", dflt_percentile), + ) + + +def _load_params_mapping(params: str | dict[str, Any]) -> dict[str, Any]: + """Load a parameter mapping and coerce known values in TXT files.""" if isinstance(params, str): if not os.path.exists(params): raise FileNotFoundError(f"Parameter file not found: {params}") @@ -203,35 +246,38 @@ def read_params( if not line or line.startswith("#"): continue key, val = [x.strip() for x in line.split("=", 1)] - if key == "dilution_factor": + if key in {"dilution_factor", "distributions"}: parsed[key] = int(val) elif key == "boundary_support": if val.lower() == "none": parsed[key] = None else: parsed[key] = int(val) - elif key == "distributions": - parsed[key] = int(val) elif key == "percentile": parsed[key] = float(val) + elif key == "detection_level": + parsed[key] = float(val) + elif key in {"cumulative", "first_best", "intervals"}: + parsed[key] = _parse_bool(val) else: parsed[key] = val params = parsed else: raise ValueError(f"Unsupported file type: {ext}") - else: - assert isinstance( - params, dict - ), "params must either be a file path or a dictionary" + if not isinstance(params, dict): + raise ValueError("params must be a parameter file path or a dictionary.") + return params - # --- Apply defaults for any missing keys --- - dilution_factor = params.get("dilution_factor", dflt_dilution) - distributions = params.get("distributions", dflt_dists) - boundary_support = params.get("boundary_support", dflt_tails) - percentile = params.get("percentile", 99) - return dilution_factor, distributions, boundary_support, percentile +def _parse_bool(value: str) -> bool: + """Parse a boolean value used in a text parameter file.""" + normalized = value.strip().lower() + if normalized in {"true", "yes", "1"}: + return True + if normalized in {"false", "no", "0"}: + return False + raise ValueError(f"Expected a boolean value, got {value!r}.") def read_multi_obs_input( diff --git a/src/ecoff_fitter/workflow.py b/src/ecoff_fitter/workflow.py index 33ea32d..4c665c8 100755 --- a/src/ecoff_fitter/workflow.py +++ b/src/ecoff_fitter/workflow.py @@ -4,9 +4,12 @@ import numpy as np from ecoff_fitter.core import ECOFFitter +from ecoff_fitter.ecoffinder_core import ECOFFinder from ecoff_fitter.report import GenerateReport from ecoff_fitter.utils import PreparedInput, prepare_input +Fitter = ECOFFitter | ECOFFinder + @dataclass class ECOFFRun: @@ -15,20 +18,20 @@ class ECOFFRun: 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_fitter (Fitter): 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, ...]]]): + individual_fits (Dict[str, Tuple[Fitter, 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_fitter: Fitter global_result: Tuple[Any, ...] global_report: GenerateReport - individual_fits: Dict[str, Tuple[ECOFFitter, Tuple[Any, ...]]] + individual_fits: Dict[str, Tuple[Fitter, Tuple[Any, ...]]] individual_reports: Dict[str, GenerateReport] @@ -47,6 +50,11 @@ def run_ecoff_analysis( density: bool = False, options: dict[str, Any] | None = None, sheet_name: str | None = None, + method: str = "ecoffitter", + detection_level: float = 10.0, + cumulative: bool = True, + first_best: bool = False, + intervals: bool = False, ) -> ECOFFRun: """Fit ECOFF models to aggregate data and optionally each input group. @@ -73,13 +81,61 @@ def run_ecoff_analysis( 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. + method (str): Fitting method, either ``"ecoffitter"`` or + ``"ecoffinder"``. + detection_level (float): Minimum mode size as a percentage of all + observations when using ECOFFinder. + cumulative (bool): Whether ECOFFinder fits cumulative frequencies. + first_best (bool): Whether ECOFFinder stops after its score begins to + increase from its best value. + intervals (bool): Whether ECOFFinder refits its selected range using + interval regression. Returns: ECOFFRun: Global fit, optional individual fits, and their reports. """ prepared = prepare_input(data, sheet_name=sheet_name) - if distributions == "auto": + if method not in {"ecoffitter", "ecoffinder"}: + raise ValueError("method must be 'ecoffitter' or 'ecoffinder'.") + + if method == "ecoffinder": + if distributions != 1: + raise ValueError( + "ECOFFinder fits one wild-type distribution; " + "distributions must be 1." + ) + + def fit_one(input_df: Any) -> tuple[Fitter, Tuple[Any, ...]]: + if method == "ecoffinder": + fitter = ECOFFinder( + input=input_df, + dilution_factor=dilution_factor, + detection_level=detection_level, + cumulative=cumulative, + first_best=first_best, + intervals=intervals, + boundary_support=boundary_support, + params=params, + percentile=percentile, + ) + result = fitter.generate(options=options) + else: + fitter = ECOFFitter( + input=input_df, + params=params, + dilution_factor=dilution_factor, + distributions=cast(int, distributions), + boundary_support=boundary_support, + ) + result = fitter.generate(percentile=percentile, options=options) + setattr(fitter, "density", density) + return fitter, result + + if method == "ecoffinder": + global_fitter, global_result = fit_one(prepared.global_df) + k = 1 + elif distributions == "auto": k, score, global_fitter, global_result = select_best_k( data, dilution_factor=dilution_factor, @@ -95,26 +151,19 @@ def run_ecoff_analysis( else: fixed_distributions = cast(int, distributions) - global_fitter = ECOFFitter( - input=prepared.global_df, - params=params, - dilution_factor=dilution_factor, - distributions=fixed_distributions, - boundary_support=boundary_support, - ) - global_result = global_fitter.generate(percentile=percentile, options=options) + global_fitter, global_result = fit_one(prepared.global_df) k = fixed_distributions - setattr(global_fitter, "density", density) - global_report = GenerateReport.from_fitter(global_fitter, global_result) - individual_fits: Dict[str, Tuple[ECOFFitter, Tuple[Any, ...]]] = {} + individual_fits: Dict[str, Tuple[Fitter, Tuple[Any, ...]]] = {} individual_reports: Dict[str, GenerateReport] = {} if fit_individual: for name, subdf in prepared.individual_dfs.items(): - if distributions == "auto": + if method == "ecoffinder": + fitter, result = fit_one(subdf) + elif distributions == "auto": _, _, fitter, result = select_best_k( subdf, dilution_factor=dilution_factor, @@ -127,16 +176,8 @@ def run_ecoff_analysis( options=options, ) else: - fitter = ECOFFitter( - input=subdf, - params=params, - dilution_factor=dilution_factor, - distributions=cast(int, distributions), - boundary_support=boundary_support, - ) - result = fitter.generate(percentile=percentile, options=options) + fitter, result = fit_one(subdf) - setattr(fitter, "density", density) individual_fits[name] = (fitter, result) individual_reports[name] = GenerateReport.from_fitter(fitter, result) From 9562410b7d55fb2b92be929648752b881f3c1243 Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Tue, 27 Oct 2026 16:48:18 +0200 Subject: [PATCH 2/4] refactor --- README.md | 69 ++-- src/ecoff_fitter/__init__.py | 42 +- src/ecoff_fitter/cli.py | 102 +++-- src/ecoff_fitter/core.py | 590 ++++++++++++--------------- src/ecoff_fitter/defence.py | 73 ++-- src/ecoff_fitter/ecoffinder_core.py | 406 ------------------- src/ecoff_fitter/graphs.py | 6 +- src/ecoff_fitter/intervals.py | 375 +++++++++++++++++ src/ecoff_fitter/least_squares.py | 354 ++++++++++++++++ src/ecoff_fitter/mixture.py | 34 +- src/ecoff_fitter/range_search.py | 609 +++++++++++++++++++++------- src/ecoff_fitter/report.py | 123 ++++-- src/ecoff_fitter/utils.py | 90 ++-- src/ecoff_fitter/workflow.py | 307 ++++---------- tests/test_ecoff_fitter.py | 36 +- tests/test_range_search.py | 45 ++ tests/test_report.py | 16 +- tests/test_workflow.py | 40 +- 18 files changed, 1956 insertions(+), 1361 deletions(-) mode change 100755 => 100644 src/ecoff_fitter/core.py delete mode 100644 src/ecoff_fitter/ecoffinder_core.py create mode 100644 src/ecoff_fitter/intervals.py create mode 100644 src/ecoff_fitter/least_squares.py create mode 100644 tests/test_range_search.py diff --git a/README.md b/README.md index 9c283b9..b2f275f 100755 --- a/README.md +++ b/README.md @@ -84,9 +84,9 @@ censored observations. Fit one dataset directly: ```python -from ecoff_fitter import ECOFFitter +from ecoff_fitter import IntervalRegressionFitter -fitter = ECOFFitter(input="demo_files/censored.txt", distributions=1) +fitter = IntervalRegressionFitter(input="demo_files/censored.txt", distributions=1) result = fitter.generate(percentile=99) print(result) ``` @@ -99,6 +99,7 @@ from ecoff_fitter import run_ecoff_analysis run = run_ecoff_analysis( "demo_files/multi_assay.txt", distributions=2, + range_search="mixture", fit_individual=True, percentile=99, ) @@ -108,31 +109,41 @@ for assay, report in run.individual_reports.items(): print(report.to_text(label=assay)) ``` -Use the ECOFFinder workbook-style range search through the same workflow by -setting `method="ecoffinder"`. The selected wild-type range is found with -least squares; `intervals=True` then refits that range using ECOFFitter's -interval regression: +Choose the fitting method and WT selector independently. The two count-based +selectors can use either least squares or interval regression; mixture +selection is available with interval regression only: ```python run = run_ecoff_analysis( "demo_files/multi_assay.txt", - method="ecoffinder", - detection_level=10, - intervals=True, + fitter="interval_regression", + range_search="first-local-peak", fit_individual=True, ) print(run.global_report.to_text(verbose=True)) ``` -ECOFFinder fits one wild-type distribution and does not support -`distributions="auto"`. It accepts parameter mappings or YAML/TXT files with -`dilution_factor`, `boundary_support`, `percentile`, `detection_level`, -`cumulative`, `first_best`, and `intervals`. File values override matching -arguments. A `distributions` entry is accepted only when set to `1`. +`range_search` accepts `"largest-bin"`, `"first-local-peak"`, or `"mixture"`. +The first-local-peak selector uses the fixed 19-bin log2 MIC grid and requires +`dilution_factor=2`. The largest-bin selector uses the highest-frequency active +bin; `park_from_mic` can exclude higher bins before selection. Count-based +selectors fit one wild-type range. Mixture selection uses the interval-regression +mixture model and supports fixed or automatically selected component counts. -Set `distributions="auto"` in `run_ecoff_analysis` to select a component -count by the AIC or BIC criterion. `max_distributions` sets the largest count +For example, select the largest active bin and fit it with interval regression: + +```python +run = run_ecoff_analysis( + data, + fitter="interval_regression", + range_search="largest-bin", + park_from_mic=32, +) +``` + +Set `range_search="mixture"` and `distributions="auto"` in +`run_ecoff_analysis` to select a component count by the AIC or BIC criterion. `max_distributions` sets the largest count to consider; `criterion`, `min_delta`, `min_pi`, and `min_separation` control the selection checks. The selected aggregate count is available as `run.selected_k`. @@ -145,8 +156,9 @@ or more assay columns: ```bash ecoff-fitter \ --input demo_files/multi_assay.txt \ - --method ecoffinder \ - --intervals \ + --fitter interval_regression \ + --range_search largest-bin \ + --park_from_mic 32 \ --percentile 99 \ --fit_individual \ --outfile demo_files/output.pdf @@ -158,18 +170,19 @@ available as `python -m ecoff_fitter`. | Option | Default | Description | | --- | --- | --- | | `--input INPUT` | Required | Input MIC dataset. | -| `--method METHOD` | `ecoffitter` | Fitting method: `ecoffitter` or `ecoffinder`. | -| `--params PARAMS` | None | YAML or TXT parameter file; supported keys depend on the selected method, and file values override matching options. | +| `--fitter METHOD` | `interval_regression` | `least_squares` or `interval_regression`. | +| `--range_search METHOD` | None | `largest-bin`, `first-local-peak`, or `mixture`. | +| `--params PARAMS` | None | YAML or TXT parameter file; file values override matching options. | | `--dilution_factor N` | `2` | Ratio between adjacent MIC dilution steps. | -| `--distributions K` | `1` | Number of normal components to fit. The CLI accepts an integer; automatic selection is available in the Python workflow API. | -| `--boundary_support N` | `1` | Number of dilution steps used to extend censoring bounds. Use `None` in a parameter file for unbounded tails. | -| `--percentile P` | `99.0` | Percentile used to calculate the ECOFF; must be between 0 and 100. | -| `--fit_individual` | Off | Fit each assay column as well as the aggregate observations. | +| `--distributions K` | `1` | Number of normal components to fit. | +| `--boundary_support N` | `1` | Number of dilution steps used to extend censoring bounds. | +| `--percentile P` | `99.0` | Percentile used to calculate the ECOFF. | +| `--fit_individual` | Off | Fit each assay column as well as aggregate observations. | | `--density` | Off | Plot probability density instead of counts. | -| `--detection_level P` | `10.0` | Minimum eligible ECOFFinder mode size as a percentage of observations. | -| `--cumulative` / `--no-cumulative` | On | Use cumulative counts in ECOFFinder range fitting, or per-dilution frequencies. | -| `--first_best` | Off | Stop ECOFFinder range search after its score begins increasing from its best value. | -| `--intervals` | Off | Refit ECOFFinder's selected range using interval regression. | +| `--detection_level P` | `10.0` | Minimum eligible local-peak size as a percentage of observations. | +| `--park_from_mic MIC` | None | Exclude this MIC and higher bins before largest-bin selection. | +| `--cumulative` / `--no-cumulative` | On | Use cumulative counts or per-bin frequencies in least-squares range fitting. | +| `--first_best` | Off | Stop range search after its score starts increasing. | | `--outfile PATH` | None | Write a text report (`.txt`) or PDF report (`.pdf`). | | `--verbose` | Off | Include model details in printed text output. | diff --git a/src/ecoff_fitter/__init__.py b/src/ecoff_fitter/__init__.py index 21aab26..f144dd2 100755 --- a/src/ecoff_fitter/__init__.py +++ b/src/ecoff_fitter/__init__.py @@ -1,39 +1,26 @@ -""" -ECOFF Fitter — Estimate epidemiological cutoff values (ECOFFs) -using interval regression on MIC (Minimum Inhibitory Concentration) data. +"""ECOFF analysis tools for MIC data. -Single-fit API --------------- -from ecoff_fitter import ECOFFitter +Direct interval-regression fitting: -fitter = ECOFFitter(input="mic_data.csv") -result = fitter.generate(percentile=99) + from ecoff_fitter import IntervalRegressionFitter -Multi-fit / workflow API ------------------------- -from ecoff_fitter import run_ecoff_analysis + fitter = IntervalRegressionFitter(input="mic_data.csv") + result = fitter.generate(percentile=99) -run = run_ecoff_analysis( - "mic_data.csv", - fit_individual=True, -) +Multi-assay workflow: -print(run.global_report.to_text()) + from ecoff_fitter import run_ecoff_analysis -CLI ---- -python -m ecoff_fitter --input mic_data.csv + run = run_ecoff_analysis("mic_data.csv", fitter="interval_regression") """ from importlib.metadata import PackageNotFoundError, version -from .core import ECOFFitter -from .ecoffinder_core import ECOFFinder +from .intervals import IntervalRegressionFitter from .workflow import ECOFFRun, run_ecoff_analysis __all__ = [ - "ECOFFitter", - "ECOFFinder", + "IntervalRegressionFitter", "run_ecoff_analysis", "ECOFFRun", ] @@ -45,7 +32,14 @@ def main() -> None: - """Entry point for `python -m ecoff_fitter`.""" + """Run the command-line entry point. + + + Returns: + None. + + Args: + None.""" from .cli import main as cli_main cli_main() diff --git a/src/ecoff_fitter/cli.py b/src/ecoff_fitter/cli.py index be255b2..fdea03e 100755 --- a/src/ecoff_fitter/cli.py +++ b/src/ecoff_fitter/cli.py @@ -1,26 +1,50 @@ #!/usr/bin/env python3 """ -Command-line interface for ECOFFitter. +Command-line interface for ECOFF analysis. Usage example: python -m ecoff_fitter.cli --input data/mic_data.csv --distributions 2 --percentile 99 """ import argparse -from typing import Any, List, Optional -from ecoff_fitter import ECOFFitter +from typing import List, Optional from ecoff_fitter.report import GenerateReport, CombinedReport from ecoff_fitter.defence import validate_output_path -from ecoff_fitter.utils import read_multi_obs_input -from unittest.mock import MagicMock, patch from ecoff_fitter.workflow import run_ecoff_analysis +def _parse_optional_int(value: str) -> int | None: + """Parse a non-negative integer or the word ``none``. + + Args: + value (str): Text supplied for an optional integer argument. + + Returns: + int | None: Parsed integer, or None when disabled. + """ + if value.strip().lower() == "none": + return None + try: + parsed = int(value) + except ValueError as error: + raise argparse.ArgumentTypeError("must be an integer or 'none'") from error + if parsed < 0: + raise argparse.ArgumentTypeError("must be a non-negative integer or 'none'") + return parsed + + def build_parser() -> argparse.ArgumentParser: - """Create and configure the command-line argument parser.""" + """Create and configure the command-line argument parser. + + + Returns: + argparse.ArgumentParser: Configured command-line parser. + + Args: + None.""" parser = argparse.ArgumentParser( prog="ecoff_fitter", - description="Estimate epidemiological cutoff values (ECOFFs) using interval regression on MIC data.", + description="Estimate epidemiological cutoff values (ECOFFs) from MIC data.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) @@ -33,18 +57,21 @@ def build_parser() -> argparse.ArgumentParser: ), ) parser.add_argument( - "--method", - choices=("ecoffitter", "ecoffinder"), - default="ecoffitter", - help="Fitting method to use (default: ECOFFitter).", + "--fitter", + choices=("least_squares", "interval_regression"), + help="Model fitting method: least squares or interval regression.", + ) + parser.add_argument( + "--range_search", + choices=("largest-bin", "first-local-peak", "mixture"), + help="Wild-type selector: largest bin, first local peak, or mixture model.", ) parser.add_argument( "--params", help=( - "Optional YAML or TXT parameter file. ECOFFitter accepts " - "dilution_factor, distributions, boundary_support, and percentile; " - "ECOFFinder also accepts detection_level, cumulative, first_best, " - "and intervals. File values override matching options." + "Optional YAML or TXT parameter file for dilution, component count, " + "censoring support, percentile, and range-search settings. File " + "values override matching options." ), ) parser.add_argument( @@ -57,13 +84,13 @@ def build_parser() -> argparse.ArgumentParser: "--distributions", type=int, default=1, - help="Number of normal components to fit with ECOFFitter; ECOFFinder uses one WT range.", + help="Number of normal components for interval regression or mixture selection.", ) parser.add_argument( "--boundary_support", - type=int, + type=_parse_optional_int, default=1, - help="boundary support for censored data handling (None to disable).", + help="Number of dilution steps used as support for censored observations.", ) parser.add_argument( "--density", @@ -74,26 +101,27 @@ def build_parser() -> argparse.ArgumentParser: "--detection_level", type=float, default=10.0, - help="Minimum ECOFFinder mode size as a percentage of observations.", + help="Minimum eligible local-peak size as a percentage of observations.", + ) + parser.add_argument( + "--park_from_mic", + type=float, + help=( + "Exclude this MIC and higher bins before largest-bin selection." + ), ) parser.add_argument( "--cumulative", action=argparse.BooleanOptionalAction, default=True, help=( - "Fit cumulative frequencies with ECOFFinder; use --no-cumulative " - "for per-dilution frequencies." + "Fit cumulative frequencies; use --no-cumulative for per-bin frequencies." ), ) parser.add_argument( "--first_best", action="store_true", - help="Stop ECOFFinder range search after its score starts increasing.", - ) - parser.add_argument( - "--intervals", - action="store_true", - help="Refit ECOFFinder's selected range with interval regression.", + help="Stop range search after its score starts increasing.", ) parser.add_argument( "--percentile", @@ -125,9 +153,13 @@ def main(argv: Optional[List[str]] = None) -> None: Args: argv (Optional[List[str]]): Argument list to parse; defaults to the process command line. - """ + + Returns: + None.""" parser = build_parser() args = parser.parse_args(argv) + if args.range_search == "mixture" and args.distributions < 2: + parser.error("--range_search mixture requires --distributions of at least 2") try: workflow_args = { @@ -138,15 +170,13 @@ def main(argv: Optional[List[str]] = None) -> None: "percentile": args.percentile, "fit_individual": args.fit_individual, "density": args.density, + "fitter": args.fitter or "interval_regression", + "range_search": args.range_search, + "detection_level": args.detection_level, + "cumulative": args.cumulative, + "first_best": args.first_best, + "park_from_mic": args.park_from_mic, } - if args.method == "ecoffinder": - workflow_args.update( - method=args.method, - detection_level=args.detection_level, - cumulative=args.cumulative, - first_best=args.first_best, - intervals=args.intervals, - ) run = run_ecoff_analysis(args.input, **workflow_args) text = "\n\nECOFF RESULTS\n=====================================\n\n" diff --git a/src/ecoff_fitter/core.py b/src/ecoff_fitter/core.py old mode 100755 new mode 100644 index bb9344e..56aeedb --- a/src/ecoff_fitter/core.py +++ b/src/ecoff_fitter/core.py @@ -1,373 +1,309 @@ -import numpy as np -from typing import Any, Optional, Tuple -import pandas as pd -from numpy.typing import NDArray -from scipy.stats import norm -from intreg.intreg import IntReg -from ecoff_fitter.utils import read_input, read_params -from ecoff_fitter.defence import ( - validate_input_source, - validate_params_source, - validate_mic_data, - validate_params, -) -from ecoff_fitter.mixture import MixtureModel - - -class ECOFFitter: - """ - Estimate epidemiological cutoff values (ECOFFs) using interval regression - on MIC (Minimum Inhibitory Concentration) data. +"""Coordinate WT range selection and distribution fitting.""" - If a single distribution is specified, a single censored-normal interval - regression model is fitted and the ECOFF is taken from the specified percentile. - - If more than one distribution is specified, a finite mixture of interval- - censored normals is fitted and the ECOFF is taken from the lowest-mean - (wild-type) component at the given percentile. - """ +from typing import Any, Tuple - model_: IntReg | MixtureModel | None - x: NDArray[np.floating] - mus_: NDArray[np.floating] - sigmas_: NDArray[np.floating] - pis_: NDArray[np.floating] - loglike_: float - converged_: bool - n_iter_: int | None - ecoff_: float - z_percentile_: float - y_low_: NDArray[np.floating] - y_high_: NDArray[np.floating] - weights_: NDArray[np.floating] - - def __init__( - self, - input: pd.DataFrame | str, - params: dict[str, Any] | str | None = None, - dilution_factor: int = 2, - distributions: int = 1, - boundary_support: int | None = 1, - ) -> None: - """ - Initialize the ECOFFitter. +import numpy as np - Input may be a DataFrame with 'MIC' and 'observations' columns, or a - supported file containing the same structure. Single-column MIC - values are also accepted. +from ecoff_fitter.intervals import IntervalRegressionFitter +from ecoff_fitter.range_search import CountRangeSelector, _RangeSearchFitResult +from ecoff_fitter.utils import prepare_input - Parameters may be supplied directly, or via a dictionary or config - file (yaml, yml, txt) containing dilution_factor, distributions, and - boundary_support. +Fitter = IntervalRegressionFitter | _RangeSearchFitResult - Args: - input: Input MIC data or file path. - params (dict | str | None): Optional parameter source overriding - manual arguments. - dilution_factor (int): MIC dilution factor (default 2). - distributions (int): Number of normal components to fit. - boundary_support (int | None): Number of dilution steps used to - extend censoring bounds (default 1); None leaves tails - unbounded. - """ - - validate_input_source(input) - validate_params_source(params) - - # read input dataframe or file - self.obj_df = read_input(input) - # check input values - validate_mic_data(self.obj_df) - - if params is not None: - # overide explicit arguments with input dict/file - dilution_factor, distributions, boundary_support, percentile = read_params( - params, dilution_factor, distributions, boundary_support - ) - self.percentile = percentile - # check parameter values - validate_params(dilution_factor, distributions, boundary_support) +class CoordinateFit: + """Route MIC data through the selected WT selector and fitter. - self.dilution_factor = dilution_factor - self.distributions = distributions - self.boundary_support = boundary_support + Use :meth:`fit` as the single entry point. Count-based selectors return a + range selection that is passed to the chosen fitter. Mixture selection + uses interval regression directly. + """ - def fit(self, options: dict[str, Any] | None = None) -> "ECOFFitter": - """ - Define MIC intervals and fit either a single censored-normal model - or a finite mixture model. + @staticmethod + def _fit_fixed( + input: Any, + *, + fitter: str, + range_search: str | None, + distributions: int, + params: dict[str, Any] | str | None = None, + dilution_factor: int = 2, + boundary_support: int | None = 1, + percentile: float = 99.0, + detection_level: float = 10.0, + cumulative: bool = True, + first_best: bool = False, + park_from_mic: float | None = None, + options: dict[str, Any] | None = None, + ) -> tuple[Fitter, tuple[Any, ...]]: + """Route one input through its selected range search and fitter. Args: - options (dict[str, Any] | None): Optional solver or EM settings. + input (Any): MIC data accepted by the input preparation helpers. + fitter (str): ``"least_squares"`` or ``"interval_regression"``. + range_search (str | None): ``"largest-bin"``, + ``"first-local-peak"``, ``"mixture"``, or None for direct fitting. + distributions (int): Number of interval-regression components. + params (dict[str, Any] | str | None): Optional parameter source. + dilution_factor (int): Ratio between adjacent MIC dilution steps. + boundary_support (int | None): Censoring-bound support setting. + percentile (float): Percentile used to calculate the ECOFF. + detection_level (float): Minimum eligible local-peak size. + cumulative (bool): Whether range fitting uses cumulative counts. + first_best (bool): Whether to stop when the range score increases. + park_from_mic (float | None): Upper MIC threshold for active bins. + options (dict[str, Any] | None): Solver or EM options. Returns: - self: The fitted ECOFFitter instance. - """ - # Define and log-transform intervals - self.y_low_, self.y_high_, self.weights_ = self.define_intervals() - - if self.distributions == 1: - return self.fit_single(options) - + tuple[Any, tuple[Any, ...]]: Fitted model and generated result.""" + selectors = {"largest-bin", "first-local-peak", "mixture"} + if fitter not in {"least_squares", "interval_regression"}: + raise ValueError("fitter must be 'least_squares' or 'interval_regression'.") + if range_search not in selectors | {None}: + raise ValueError("range_search must be 'largest-bin', 'first-local-peak', or 'mixture'.") + if fitter == "least_squares" and range_search not in {"largest-bin", "first-local-peak"}: + raise ValueError("Least-squares fitting requires a count-based range selector.") + if range_search == "mixture" and fitter != "interval_regression": + raise ValueError("Mixture range selection requires interval_regression.") + if range_search is None and fitter != "interval_regression": + raise ValueError("Direct fitting requires interval_regression.") + if range_search == "mixture" and distributions < 2: + raise ValueError("Mixture selection requires at least two components.") + if range_search is None and distributions != 1: + raise ValueError("Multiple components require range_search='mixture'.") + if range_search in {"largest-bin", "first-local-peak"} and distributions != 1: + raise ValueError("Count-based range selectors fit one wild-type distribution.") + if range_search in {"mixture", None}: + model = IntervalRegressionFitter( + input=input, params=params, dilution_factor=dilution_factor, + distributions=distributions, boundary_support=boundary_support, + ) + result = model.generate(percentile=percentile, options=options) else: - # multiple gaussians - return self.fit_mixture(options) - - def fit_single(self, options: dict[str, Any] | None = None) -> "ECOFFitter": - """ - Fit a single-component censored normal distribution using interval - regression. - - Args: - options (dict[str, Any] | None): Optimization options for the - interval regression solver. + selection = CountRangeSelector( + input=input, + range_search=range_search, + params=params, + dilution_factor=dilution_factor, + detection_level=detection_level, + cumulative=cumulative, + first_best=first_best, + boundary_support=boundary_support, + park_from_mic=park_from_mic, + percentile=percentile, + ).select() + interval_fitter = None + if fitter == "interval_regression": + interval_fitter = IntervalRegressionFitter( + input=selection.selected_df, + dilution_factor=selection.dilution_factor, + distributions=1, + boundary_support=selection.boundary_support, + ) + interval_fitter.fit(options=options) + model = _RangeSearchFitResult( + selection, + fitter=fitter, + interval_fitter=interval_fitter, + ) + result = model.generate() + return model, result - Returns: - self: The fitted ECOFFitter instance with stored parameters. - """ - - # single guassian - model = IntReg(self.y_low_, self.y_high_, weights=self.weights_) - model.fit(method="L-BFGS-B", options=options) - result = model.result - - self.model_ = model - self.x = result.x - self.mus_ = np.array([result.x[0]]) - self.sigmas_ = np.array([np.exp(result.x[1])]) - self.pis_ = np.array([1.0]) - self.loglike_ = -result.fun - self.converged_ = result.success - self.n_iter_ = result.nit if hasattr(result, "nit") else None - - return self - - def fit_mixture(self, options: dict[str, Any] | None = None) -> "ECOFFitter": - """ - Fit a K-component finite mixture of censored normals using the EM - algorithm followed by optional refinement. - Args: - options (dict[str, Any] | None): EM settings (``max_iter``, - ``tol``) and refinement setting (``refine``). + @staticmethod + 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, IntervalRegressionFitter, Tuple[Any, ...]]: + """Select a component count by score and mixture diagnostics. - Returns: - self: The fitted ECOFFitter instance with stored mixture parameters. - """ - - options = options or {} - max_iter = options.get("max_iter", 500) - tol = options.get("tol", 1e-6) - - # Ensure weights array - weights = np.asarray(self.weights_, dtype=float) - - # Run EM algorithm - model = MixtureModel(self.y_low_, self.y_high_, weights, self.distributions) - model.fit(max_iter=max_iter, tol=tol, refine=options.get("refine", True)) - - self.model_ = model - self.x = model.x - self.mus_ = model.mus - self.sigmas_ = model.sigmas - self.pis_ = model.pis - self.loglike_ = model.loglike - self.converged_ = model.converged - self.n_iter_ = model.n_iter - - return self - - def define_intervals( - self, df: Optional[pd.DataFrame] = None - ) -> Tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: - """ - Construct MIC interval bounds and apply left-, right-, and interval- - censoring rules, then transform to log dilution space. + 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: - df (Optional[DataFrame]): Optional MIC data to override stored - input. + 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 ``IntervalRegressionFitter.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[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: - Log-transformed lower bounds, upper bounds, and observation - weights. - """ - - if df is None: - df = self.obj_df - - y_low = np.zeros(len(df)) - y_high = np.zeros(len(df)) - weights = df.observations.to_numpy() - - # Calculate tail dilution factor if not censored - 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 = parse_mic_value(mic[2:]) - y_low[i] = ( - 1e-6 - if self.boundary_support is None - else lower_bound / tail_dilution_factor - ) - y_high[i] = lower_bound - - elif mic.startswith(">"): # Right-censored value - upper_bound = parse_mic_value(mic[1:]) - y_low[i] = upper_bound - y_high[i] = ( - np.inf - if self.boundary_support is None - else upper_bound * tail_dilution_factor - ) + tuple[int, float, IntervalRegressionFitter, tuple[Any, ...]]: Selected component + count, criterion score, fitted model, and generated result.""" - else: # Exact MIC value - mic_value = parse_mic_value(mic) - y_low[i] = mic_value / self.dilution_factor - y_high[i] = mic_value + df = prepare_input( + data, + sheet_name=sheet_name, + ).global_df - # Apply log transformation to intervals - y_low_log, y_high_log = self.log_transf_intervals(y_low, y_high) + n_informative = int((df["observations"] > 0).sum()) - return y_low_log, y_high_log, weights + if n_informative == 0: + raise ValueError("No MIC observations available for fitting.") - def log_transf_intervals( - self, y_low: NDArray[np.floating], y_high: NDArray[np.floating] - ) -> Tuple[NDArray[np.floating], NDArray[np.floating]]: - """ - Transform interval bounds into log base–dilution_factor space. + max_k = min( + max_distributions, + n_informative, + ) - Args: - y_low (NDArray[np.floating]): Lower interval bounds. - y_high (NDArray[np.floating]): Upper interval bounds. + best = None - Returns: - 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) / log_base - y_high_log = np.log(y_high) / log_base - - return y_low_log, y_high_log + for k in range(1, max_k + 1): - def generate( - self, percentile: int | float = 99, options: dict[str, Any] | None = None - ) -> Tuple[Any, ...]: - """ - Fit the model and compute the ECOFF at a specified percentile. - - Args: - percentile (int | float): Desired percentile (default 99). - options (dict[str, Any] | None): Optional fit settings. + # Fit model + fitter = IntervalRegressionFitter( + input=df, + params=params, + dilution_factor=dilution_factor, + distributions=k, + boundary_support=boundary_support, + ) - Returns: - Tuple[Any, ...]: ECOFF, percentile location, and fitted means and - standard deviations. - """ + result = fitter.generate( + percentile=percentile, + options=options, + ) - if hasattr(self, "percentile"): - percentile = self.percentile + score = fitter.model_summary()[criterion] - self.fit(options=options) # updates self.model_, self.mus_, etc. - results = self.compute_ecoff(percentile) - self.ecoff_ = results[0] - self.z_percentile_ = results[1] + # K=1 is always the starting model + if best is None: + best = (k, score, fitter, result) + continue - return results + # improve model fit? + _, best_score, _, _ = best - def compute_ecoff(self, percentile: float) -> Tuple[Any, ...]: - """ - Compute the ECOFF and percentile location from the fitted model. + if best_score - score < min_delta: + break - Args: - percentile (float): Percentile in the wild-type component, between - 0 and 100. + # components sufficiently large? + pis = np.asarray(fitter.pis_) - Returns: - tuple: - For 1 component: - (ecoff, z_percentile, mu, sigma) - For K components: - (ecoff, z_percentile, mu1, sigma1, ..., muK, sigmaK) - """ + if np.any(pis < min_pi): + break - assert 0 < percentile < 100, "percentile must be between 0 and 100" + # Are adjacent components sufficiently separated? + order = np.argsort(fitter.mus_) - z = norm.ppf(percentile / 100) + mus = np.asarray(fitter.mus_)[order] + sigmas = np.asarray(fitter.sigmas_)[order] - # SINGLE COMPONENT - if self.distributions == 1: - mu = self.mus_[0] - sigma = self.sigmas_[0] - z_percentile = mu + z * sigma - ecoff = self.dilution_factor**z_percentile - return ecoff, z_percentile, mu, sigma + pooled_sigmas = np.sqrt((sigmas[:-1] ** 2 + sigmas[1:] ** 2) / 2) - # MULTI-COMPONENT - K = self.distributions + separations = np.diff(mus) / pooled_sigmas - mus = self.mus_ - sigmas = self.sigmas_ + if np.any(separations < min_separation): + break - # WT = component with lowest mean - wt_idx = np.argmin(mus) - mu_wt = mus[wt_idx] - sigma_wt = sigmas[wt_idx] + best = (k, score, fitter, result) - # compute ECOFF on WT - z_percentile = mu_wt + z * sigma_wt - ecoff = self.dilution_factor**z_percentile + assert best is not None + return best - # flatten - mus_sigmas = [] - for k in range(K): - mus_sigmas.extend([mus[k], sigmas[k]]) - return (ecoff, z_percentile, *mus_sigmas) + def fit( + self, + input: Any, + *, + fitter: str, + range_search: str | None, + distributions: int | str, + max_distributions: int = 3, + criterion: str = "bic", + min_delta: float = 15, + params: dict[str, Any] | str | None = None, + dilution_factor: int = 2, + boundary_support: int | None = 1, + percentile: float = 99.0, + detection_level: float = 10.0, + cumulative: bool = True, + first_best: bool = False, + park_from_mic: float | None = None, + options: dict[str, Any] | None = None, + ) -> tuple[int, Fitter, tuple[Any, ...]]: + """Fit one MIC table using the selected range-search and fitting methods. - def model_summary(self) -> dict[str, Any]: - """Return fitted model metadata and information criteria. + Args: + input (Any): MIC data accepted by the input preparation helpers. + fitter (str): ``"least_squares"`` or ``"interval_regression"``. + range_search (str | None): Count-based selector, ``"mixture"``, or + None for a direct single-component interval fit. + distributions (int | str): Component count or ``"auto"`` for automatic + mixture selection. + max_distributions (int): Maximum components evaluated when automatic. + criterion (str): Model-summary score minimized during automatic selection. + min_delta (float): Minimum score improvement for another component. + params (dict[str, Any] | str | None): Optional parameter source. + dilution_factor (int): Ratio between adjacent MIC dilution steps. + boundary_support (int | None): Censoring-bound support setting. + percentile (float): Percentile used to calculate the ECOFF. + detection_level (float): Minimum eligible local-peak size. + cumulative (bool): Whether count-based range fitting uses cumulative counts. + first_best (bool): Whether count-based search stops as its score increases. + park_from_mic (float | None): Upper MIC threshold for active bins. + options (dict[str, Any] | None): Solver or EM options. 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_)) - - summary = { - "model_family": "interval-censored log-normal", - "model_type": "mixture" if K > 1 else "single", - "components": K, - "wild_type_component": wt_idx + 1, - "dilution_factor": self.dilution_factor, - "boundary_support": self.boundary_support, - "n_observations": n, - "log_likelihood": self.loglike_, - "converged": self.converged_, - "n_iter": self.n_iter_, - "pis": self.pis_, - } - - # Information criteria (if identifiable) - k_params = 2 * K + (K - 1) - summary["aic"] = 2 * k_params - 2 * self.loglike_ - summary["bic"] = np.log(n) * k_params - 2 * self.loglike_ - - return summary + tuple[int, Any, tuple[Any, ...]]: Selected component count, fitted model, + and generated result.""" + if distributions == "auto": + if fitter != "interval_regression" or range_search != "mixture": + raise ValueError( + "Automatic component selection requires interval_regression " + "with range_search='mixture'." + ) + selected_k, _, model, result = self._select_best_k( + input, + dilution_factor=dilution_factor, + boundary_support=boundary_support, + percentile=percentile, + criterion=criterion, + min_delta=min_delta, + max_distributions=max_distributions, + params=params, + options=options, + ) + return selected_k, model, result + + selected_k = ( + 1 + if range_search in {"largest-bin", "first-local-peak"} + else int(distributions) + ) + model, result = self._fit_fixed( + input, + fitter=fitter, + range_search=range_search, + distributions=selected_k, + params=params, + dilution_factor=dilution_factor, + boundary_support=boundary_support, + percentile=percentile, + detection_level=detection_level, + cumulative=cumulative, + first_best=first_best, + park_from_mic=park_from_mic, + options=options, + ) + return selected_k, model, result diff --git a/src/ecoff_fitter/defence.py b/src/ecoff_fitter/defence.py index 5092abe..ab59e49 100755 --- a/src/ecoff_fitter/defence.py +++ b/src/ecoff_fitter/defence.py @@ -6,17 +6,18 @@ def validate_input_source(input: str | DataFrame | dict[str, Any]) -> None: - """ - Validate the input source for ECOFFitter. + """Validate the MIC input source. Args: input (str | DataFrame | dict[str, Any]): MIC and observation data or a path to an input file. + Returns: + None: Returns when the input source is structurally valid. + Raises: FileNotFoundError: If the file does not exist. - ValueError: If the input type or required columns are invalid. - """ + ValueError: If the input type or required columns are invalid.""" if isinstance(input, pd.DataFrame): if not {"MIC", "observations"}.issubset(input.columns): @@ -38,17 +39,18 @@ def validate_input_source(input: str | DataFrame | dict[str, Any]) -> None: def validate_params_source( params: dict[str, Any] | str | list[Any] | tuple[Any, ...] | DataFrame | Any | None, ) -> None: - """ - Pre-validate the params argument before attempting to read it. + """Pre-validate the params argument before attempting to read it. Args: params (dict[str, Any] | str | list[Any] | tuple[Any, ...] | DataFrame | Any | None): Parameter mapping, path, or array-like value to validate. + Returns: + None: Returns when the parameter source type is supported. + Raises: FileNotFoundError: If the provided file path does not exist. - ValueError: If params is not a supported type. - """ + ValueError: If params is not a supported type.""" if params is None: return @@ -76,15 +78,16 @@ def validate_params_source( def validate_mic_data(df: DataFrame) -> None: - """ - Validate MIC and observations columns. + """Validate MIC and observations columns. Args: df (DataFrame): Input MIC data. + Returns: + None: Returns when all MIC rows are valid. + Raises: - ValueError: If MIC values are invalid or observation counts are negative. - """ + ValueError: If MIC values are invalid or observation counts are negative.""" if df.empty: raise ValueError("Input DataFrame is empty.") @@ -107,8 +110,7 @@ def validate_mic_data(df: DataFrame) -> None: def validate_params( dilution_factor: int, distributions: int, boundary_support: int | None ) -> None: - """ - Validate ECOFFitter configuration values. + """Validate fitting configuration values. Args: dilution_factor (int): The MIC dilution step. @@ -116,9 +118,11 @@ def validate_params( boundary_support (int | None): Number of dilution steps used to extend censoring bounds, or None for unbounded tails. + Returns: + None: Returns when all fitting parameters are valid. + Raises: - ValueError: If any parameter is outside acceptable range. - """ + ValueError: If any parameter is outside acceptable range.""" if not isinstance(dilution_factor, int) or dilution_factor <= 1: raise ValueError("dilution_factor must be an integer > 1.") @@ -134,25 +138,43 @@ def validate_params( raise ValueError("boundary_support must be a non-negative integer or None.") -def validate_ecoffinder_params( +def validate_range_search_params( detection_level: float, cumulative: bool, first_best: bool, - intervals: bool, percentile: float, + range_search: str, + park_from_mic: float | None = None, ) -> None: - """Validate ECOFFinder-specific settings and the requested percentile.""" + """Validate count-based range-search settings and the ECOFF percentile. + + Args: + detection_level (float): Minimum eligible peak size as a percent. + cumulative (bool): Whether to fit cumulative counts. + first_best (bool): Whether to stop after the score starts increasing. + percentile (float): ECOFF percentile between zero and one hundred. + range_search (str): ``"largest-bin"`` or ``"first-local-peak"``. + park_from_mic (float | None): Upper MIC threshold for active bins. + + Returns: + None: Raises ValueError when a setting is invalid.""" if not isinstance(detection_level, (int, float)) or not 0 <= detection_level <= 100: raise ValueError("detection_level must be between 0 and 100.") - for name, value in ( - ("cumulative", cumulative), - ("first_best", first_best), - ("intervals", intervals), - ): + for name, value in (("cumulative", cumulative), ("first_best", first_best)): if not isinstance(value, bool): raise ValueError(f"{name} must be a boolean.") if not isinstance(percentile, (int, float)) or not 0 < percentile < 100: raise ValueError("percentile must be between 0 and 100.") + if range_search not in {"largest-bin", "first-local-peak"}: + raise ValueError("range_search must be 'largest-bin' or 'first-local-peak'.") + if park_from_mic is not None and ( + isinstance(park_from_mic, bool) + or not isinstance(park_from_mic, (int, float)) + or park_from_mic <= 0 + ): + raise ValueError("park_from_mic must be a positive MIC value or None.") + if park_from_mic is not None and range_search != "largest-bin": + raise ValueError("park_from_mic is only available with the largest-bin selector.") def validate_output_path(path: str) -> bool: @@ -166,8 +188,7 @@ def validate_output_path(path: str) -> bool: Raises: ValueError: If the extension is unsupported or the directory is absent. - PermissionError: If the directory is not writable. - """ + PermissionError: If the directory is not writable.""" # Check extension allowed_exts = (".txt", ".pdf") if not path.lower().endswith(allowed_exts): diff --git a/src/ecoff_fitter/ecoffinder_core.py b/src/ecoff_fitter/ecoffinder_core.py deleted file mode 100644 index b134924..0000000 --- a/src/ecoff_fitter/ecoffinder_core.py +++ /dev/null @@ -1,406 +0,0 @@ -from typing import Any - -import numpy as np -import pandas as pd -from numpy.typing import NDArray -from scipy.stats import norm - -from ecoff_fitter.defence import ( - validate_ecoffinder_params, - validate_input_source, - validate_mic_data, - validate_params, - validate_params_source, -) -from ecoff_fitter.range_search import ECOFFinderRangeSearch -from ecoff_fitter.utils import prepare_input, read_ecoffinder_params - - -class ECOFFinder: - """Select a wild-type MIC range with the ECOFFinder workbook method. - - Candidate ranges are evaluated using cumulative least squares on the log2 - MIC scale. If ``intervals=True``, the selected range is then fitted with - interval regression using :class:`ECOFFitter`. - - The range-search implementation is an approximation pending validation - against reference outputs from the Excel workbook. - """ - - def __init__( - self, - input: Any, - dilution_factor: int = 2, - detection_level: float = 10.0, - cumulative: bool = True, - first_best: bool = False, - intervals: bool = False, - boundary_support: int | None = 1, - params: dict[str, Any] | str | None = None, - percentile: float = 99.9, - ) -> None: - """Initialize ECOFFinder with MIC frequencies. - - Args: - input: Input accepted by :func:`prepare_input`. - dilution_factor (int): Ratio between adjacent MIC dilution steps. - detection_level (float): Minimum mode frequency as a percentage - of the total count. - cumulative (bool): Fit cumulative counts when True; otherwise fit - per-dilution frequencies. - first_best (bool): Stop range search after the count-difference - criterion begins increasing from its best value. - intervals (bool): If True, use the selected ECOFFinder range to - fit an interval-regression model with ECOFFitter. - boundary_support (int | None): Number of dilution steps used by - the interval fit to extend censored bounds; None leaves the - tails unbounded. - params (dict[str, Any] | str | None): Optional mapping or YAML/TXT - file with common or ECOFFinder-specific settings. Values in - the parameter source override the corresponding arguments. - percentile (float): ECOFF percentile used by ``generate()`` when - no percentile is passed there. - - Raises: - ValueError: If the dilution factor, detection level, or MIC table - is invalid. - """ - validate_params_source(params) - - if params is not None: - ( - dilution_factor, - distributions, - detection_level, - cumulative, - first_best, - intervals, - boundary_support, - percentile, - ) = read_ecoffinder_params( - params, - dilution_factor, - detection_level, - cumulative, - first_best, - intervals, - boundary_support, - percentile, - ) - if distributions != 1: - raise ValueError("ECOFFinder supports one WT distribution only.") - - validate_params(dilution_factor, 1, boundary_support) - validate_ecoffinder_params( - detection_level, - cumulative, - first_best, - intervals, - percentile, - ) - - prepared = prepare_input(input) - if prepared.has_individuals: - raise ValueError( - "ECOFFinder expects one MIC distribution. Pass a single " - "MIC/observations table or one assay column." - ) - - self.obj_df = prepared.global_df.copy() - validate_input_source(self.obj_df) - validate_mic_data(self.obj_df) - self.dilution_factor = dilution_factor - self.detection_level = detection_level - self.cumulative = cumulative - self.first_best = first_best - self.intervals = intervals - self.boundary_support = boundary_support - self.percentile = float(percentile) - self.distributions = 1 - self.density = False - - self.pmic_: NDArray[np.float64] - self.observed_: NDArray[np.float64] - self.observed_cumulative_: NDArray[np.float64] - self.inclusion_range_: tuple[int, int] - self.mu_: float - self.sigma_: float - self.n_est_: float - self.sumsq_: float - self.ecoff_: float - self.z_percentile_: float - self.converged_: bool - self.result_: Any - self.interval_fitter_: Any - - def prepare_data(self) -> "ECOFFinder": - """Convert the input table to sorted pMIC and frequency arrays. - - Exact MIC rows are placed on the log2 scale. Censored values are - represented by their reported boundary for this workbook-style - frequency fit; this draft does not yet reproduce the workbook's - special handling of censored tail bins. - - Returns: - self: The instance with prepared pMIC and frequency arrays. - """ - df = self.obj_df.copy() - mic = df["MIC"].astype(str).str.strip() - - # The workbook frequency algorithm expects numeric MIC categories. - # Represent censored categories at their stated threshold for now. - mic = mic.str.replace("<=", "", regex=False) - mic = mic.str.replace(">", "", regex=False) - mic = mic.str.split("/").str[0] - mic_values = pd.to_numeric(mic, errors="raise").to_numpy(dtype=float) - - if np.any(mic_values <= 0): - raise ValueError("MIC values must be greater than zero.") - - pmic = np.log(mic_values) / np.log(self.dilution_factor) - frequencies = df["observations"].to_numpy(dtype=float) - order = np.argsort(pmic) - - self.pmic_ = pmic[order] - self.observed_ = frequencies[order] - self.observed_cumulative_ = np.cumsum(self.observed_) - return self - - def search_ranges(self) -> "ECOFFinder": - """Search candidate ranges and retain the best count-matching fit. - - Candidate iteration and least-squares scoring are handled by - :class:`ECOFFinderRangeSearch`. - - Returns: - self: The instance populated with the selected range and fit. - """ - range_search = ECOFFinderRangeSearch( - pmic=self.pmic_, - frequencies=self.observed_, - detection_level=self.detection_level, - cumulative=self.cumulative, - first_best=self.first_best, - ) - search_result = range_search.fit() - best = search_result["best"] - candidates = search_result["candidates"] - self.mode_idx_ = search_result["mode"] - self.inclusion_range_ = (best["start"], best["end"]) - self.selection_mu_ = best["mu"] - self.selection_sigma_ = best["sigma"] - self.selection_n_est_ = best["n_est"] - self.selection_sumsq_ = best["sumsq"] - self.mu_ = self.selection_mu_ - self.sigma_ = self.selection_sigma_ - self.n_est_ = self.selection_n_est_ - self.sumsq_ = best["sumsq"] - self.converged_ = best["success"] - self.result_ = best["result"] - self.range_fits_ = candidates - self.mus_ = np.array([self.mu_], dtype=float) - self.sigmas_ = np.array([self.sigma_], dtype=float) - self.pis_ = np.array([1.0], dtype=float) - return self - - def _selected_df(self) -> pd.DataFrame: - """Return original MIC rows within the selected inclusive range.""" - if not hasattr(self, "inclusion_range_"): - raise RuntimeError("Call search_ranges() before selecting MIC rows.") - - start, end = self.inclusion_range_ - selected_pmic = self.pmic_[start : end + 1] - selected_min = self.dilution_factor ** selected_pmic[0] - selected_max = self.dilution_factor ** selected_pmic[-1] - mic_values = self.obj_df["MIC"].astype(str).str.strip() - numeric_mic = mic_values.str.replace("<=", "", regex=False) - numeric_mic = numeric_mic.str.replace(">", "", regex=False) - numeric_mic = numeric_mic.str.split("/").str[0] - numeric_mic = pd.to_numeric(numeric_mic, errors="raise") - selected = (numeric_mic >= selected_min) & (numeric_mic <= selected_max) - selected_df = self.obj_df.loc[selected, ["MIC", "observations"]].copy() - - if selected_df.empty: - raise ValueError("The selected wild-type range contains no MIC rows.") - return selected_df - - def define_intervals(self) -> tuple[ - NDArray[np.floating], NDArray[np.floating], NDArray[np.floating] - ]: - """Return selected MIC rows as log-scale censoring intervals. - - Uses ECOFFitter's existing interval conversion so report plots retain - the input's left-, right-, and interval-censoring semantics. - - Returns: - tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: - Lower bounds, upper bounds, and observation weights. - """ - from ecoff_fitter.core import ECOFFitter - - fitter = ECOFFitter( - input=self._selected_df(), - dilution_factor=self.dilution_factor, - distributions=1, - boundary_support=self.boundary_support, - ) - return fitter.define_intervals() - - def fit_intervals( - self, options: dict[str, Any] | None = None - ) -> "ECOFFinder": - """Fit the selected wild-type range with ECOFFitter interval regression. - - The range is selected by the ECOFFinder least-squares search. Rows - outside that selected range are excluded from the interval fit. - - Returns: - self: The instance with interval-regression estimates. - """ - from ecoff_fitter.core import ECOFFitter - - selected_df = self._selected_df() - - fitter = ECOFFitter( - input=selected_df, - dilution_factor=self.dilution_factor, - distributions=1, - boundary_support=self.boundary_support, - ) - fitter.fit(options=options) - - self.interval_fitter_ = fitter - self.mu_ = float(fitter.mus_[0]) - self.sigma_ = float(fitter.sigmas_[0]) - self.mus_ = fitter.mus_.copy() - self.sigmas_ = fitter.sigmas_.copy() - self.pis_ = fitter.pis_.copy() - self.n_est_ = float(np.sum(selected_df["observations"])) - self.loglike_ = fitter.loglike_ - self.converged_ = fitter.converged_ - self.result_ = fitter.model_ - return self - - def fit(self, options: dict[str, Any] | None = None) -> "ECOFFinder": - """Prepare input, select the WT range, and fit the selected data. - - Candidate ranges are always selected with the ECOFFinder cumulative - least-squares procedure. When ``intervals`` is True, ECOFFitter then - refits the MIC rows in the selected range using interval likelihood. - - Returns: - self: The fitted ECOFFinder instance. - """ - self.prepare_data() - self.search_ranges() - if self.intervals: - return self.fit_intervals(options=options) - return self - - def compute_ecoff(self, percentile: float | None = None) -> tuple[float, float]: - """Calculate the ECOFF at a percentile of the fitted WT distribution. - - Args: - percentile (float): Percentile between 0 and 100. - - Returns: - tuple[float, float]: ECOFF on the MIC scale and its log2 location. - """ - if percentile is None: - percentile = self.percentile - if not 0 < percentile < 100: - raise ValueError("percentile must be between 0 and 100.") - if not hasattr(self, "mu_"): - raise RuntimeError("Call fit() before compute_ecoff().") - - z_percentile = self.mu_ + norm.ppf(percentile / 100) * self.sigma_ - ecoff = float(self.dilution_factor**z_percentile) - self.ecoff_ = ecoff - self.z_percentile_ = float(z_percentile) - return ecoff, float(z_percentile) - - def generate( - self, - percentile: float | None = None, - options: dict[str, Any] | None = None, - ) -> tuple[Any, ...]: - """Fit the distribution and return ECOFF and model parameters. - - Args: - percentile (float | None): Percentile used to calculate the ECOFF; - defaults to the configured value. - options (dict[str, Any] | None): Optional ECOFFitter solver - settings; used when ``intervals=True``. - - Returns: - tuple[Any, ...]: ECOFF, log2 ECOFF, mean, standard deviation, - estimated WT count, and selected inclusive range. - """ - self.fit(options=options) - ecoff, z_percentile = self.compute_ecoff(percentile) - result = ( - ecoff, - z_percentile, - self.mu_, - self.sigma_, - self.n_est_, - self.inclusion_range_, - ) - self.generated_result_: tuple[Any, ...] = result - return result - - def make_report(self) -> Any: - """Create a :class:`GenerateReport` for the fitted ECOFFinder model. - - If ``generate()`` has already been called, its ECOFF result is used. - Otherwise the model is fitted if needed and a default 99.9th - percentile report result is created. - - Returns: - GenerateReport: Report using the existing ECOFFitter report tools. - """ - from ecoff_fitter.report import GenerateReport - - if not hasattr(self, "mu_"): - self.fit() - if not hasattr(self, "generated_result_"): - ecoff, z_percentile = self.compute_ecoff(self.percentile) - self.generated_result_ = ( - ecoff, - z_percentile, - self.mu_, - self.sigma_, - ) - return GenerateReport.from_fitter(self, self.generated_result_) - - def model_summary(self) -> dict[str, Any]: - """Return selected range, fitted parameters, and optimization status.""" - if not hasattr(self, "mu_"): - raise RuntimeError("Call fit() before model_summary().") - return { - "model_family": ( - "interval-censored normal" - if self.intervals - else "normal cumulative least squares" - ), - "model_type": "ECOFFinder range search", - "range_selection_method": "cumulative least squares", - "final_fit_method": ( - "interval regression" if self.intervals else "cumulative least squares" - ), - "dilution_factor": self.dilution_factor, - "detection_level": self.detection_level, - "cumulative": self.cumulative, - "inclusion_range": self.inclusion_range_, - "mean_log2_mic": self.mu_, - "sd_log2_mic": self.sigma_, - "estimated_wt_count": self.n_est_, - "range_selection_mean_log2_mic": self.selection_mu_, - "range_selection_sd_log2_mic": self.selection_sigma_, - "range_selection_estimated_count": self.selection_n_est_, - "sum_squared_error": self.selection_sumsq_, - "fit_method": ( - "interval regression" if self.intervals else "cumulative least squares" - ), - "converged": self.converged_, - } diff --git a/src/ecoff_fitter/graphs.py b/src/ecoff_fitter/graphs.py index 9f1a118..c390edb 100755 --- a/src/ecoff_fitter/graphs.py +++ b/src/ecoff_fitter/graphs.py @@ -20,8 +20,7 @@ def plot_mic_distribution( density: bool = False, ax: Optional[matplotlib.axes.Axes] = None, ) -> matplotlib.axes.Axes: - """ - Plot MIC observation intervals and their fitted normal component curves. + """Plot MIC observation intervals and their fitted normal component curves. Supports left- and right-censoring with visual tail extensions. @@ -51,8 +50,7 @@ def plot_mic_distribution( ax (Optional[matplotlib.axes.Axes]): Axes to draw on; created if omitted. Returns: - matplotlib.axes.Axes: Axes containing the plot. - """ + matplotlib.axes.Axes: Axes containing the plot.""" tail_steps = 3.0 arrow_offset = 0 diff --git a/src/ecoff_fitter/intervals.py b/src/ecoff_fitter/intervals.py new file mode 100644 index 0000000..ab5b401 --- /dev/null +++ b/src/ecoff_fitter/intervals.py @@ -0,0 +1,375 @@ +import numpy as np +from typing import Any, Optional, Tuple +import pandas as pd +from numpy.typing import NDArray +from scipy.stats import norm +from intreg.intreg import IntReg +from ecoff_fitter.utils import read_input, read_params +from ecoff_fitter.defence import ( + validate_input_source, + validate_params_source, + validate_mic_data, + validate_params, +) +from ecoff_fitter.mixture import MixtureModel + + +class IntervalRegressionFitter: + """ + Estimate epidemiological cutoff values (ECOFFs) using interval regression + on MIC (Minimum Inhibitory Concentration) data. + + If a single distribution is specified, a single censored-normal interval + regression model is fitted and the ECOFF is taken from the specified percentile. + + If more than one distribution is specified, a finite mixture of interval- + censored normals is fitted and the ECOFF is taken from the lowest-mean + (wild-type) component at the given percentile. + """ + + model_: IntReg | MixtureModel | None + x: NDArray[np.floating] + mus_: NDArray[np.floating] + sigmas_: NDArray[np.floating] + pis_: NDArray[np.floating] + loglike_: float + converged_: bool + n_iter_: int | None + ecoff_: float + z_percentile_: float + y_low_: NDArray[np.floating] + y_high_: NDArray[np.floating] + weights_: NDArray[np.floating] + + def __init__( + self, + input: pd.DataFrame | str, + params: dict[str, Any] | str | None = None, + dilution_factor: int = 2, + distributions: int = 1, + boundary_support: int | None = 1, + ) -> None: + """Initialize the interval-regression fitter. + + Input may be a DataFrame with 'MIC' and 'observations' columns, or a + 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 + boundary_support. + + Args: + input: Input MIC data or file path. + params (dict | str | None): Optional parameter source overriding + manual arguments. + dilution_factor (int): MIC dilution factor (default 2). + distributions (int): Number of normal components to fit. + boundary_support (int | None): Number of dilution steps used to + extend censoring bounds (default 1); None leaves tails + unbounded. + + Returns: + None: Result of the operation.""" + + + validate_input_source(input) + validate_params_source(params) + + # read input dataframe or file + self.obj_df = read_input(input) + # check input values + validate_mic_data(self.obj_df) + + if params is not None: + # overide explicit arguments with input dict/file + dilution_factor, distributions, boundary_support, percentile = read_params( + params, dilution_factor, distributions, boundary_support + ) + self.percentile = percentile + + # check parameter values + validate_params(dilution_factor, distributions, boundary_support) + + self.dilution_factor = dilution_factor + self.distributions = distributions + self.boundary_support = boundary_support + + def fit(self, options: dict[str, Any] | None = None) -> "IntervalRegressionFitter": + """Define MIC intervals and fit either a single censored-normal model + or a finite mixture model. + + Args: + options (dict[str, Any] | None): Optional solver or EM settings. + + Returns: + self: The fitted interval-regression fitter instance.""" + # Define and log-transform intervals + self.y_low_, self.y_high_, self.weights_ = self.define_intervals() + + if self.distributions == 1: + return self.fit_single(options) + + else: + # multiple gaussians + return self.fit_mixture(options) + + def fit_single(self, options: dict[str, Any] | None = None) -> "IntervalRegressionFitter": + """Fit a single-component censored normal distribution using interval + regression. + + Args: + options (dict[str, Any] | None): Optimization options for the + interval regression solver. + + Returns: + self: The fitted interval-regression fitter instance with stored parameters.""" + + # single guassian + model = IntReg(self.y_low_, self.y_high_, weights=self.weights_) + model.fit(method="L-BFGS-B", options=options) + result = model.result + + self.model_ = model + self.x = result.x + self.mus_ = np.array([result.x[0]]) + self.sigmas_ = np.array([np.exp(result.x[1])]) + self.pis_ = np.array([1.0]) + self.loglike_ = -result.fun + self.converged_ = result.success + self.n_iter_ = result.nit if hasattr(result, "nit") else None + + return self + + def fit_mixture(self, options: dict[str, Any] | None = None) -> "IntervalRegressionFitter": + """Fit a K-component finite mixture of censored normals using the EM + algorithm followed by optional refinement. + + Args: + options (dict[str, Any] | None): EM settings (``max_iter``, + ``tol``) and refinement setting (``refine``). + + Returns: + self: The fitted interval-regression fitter instance with stored mixture parameters.""" + + options = options or {} + max_iter = options.get("max_iter", 500) + tol = options.get("tol", 1e-6) + + # Ensure weights array + weights = np.asarray(self.weights_, dtype=float) + + # Run EM algorithm + model = MixtureModel(self.y_low_, self.y_high_, weights, self.distributions) + model.fit(max_iter=max_iter, tol=tol, refine=options.get("refine", True)) + + self.model_ = model + self.x = model.x + self.mus_ = model.mus + self.sigmas_ = model.sigmas + self.pis_ = model.pis + self.loglike_ = model.loglike + self.converged_ = model.converged + self.n_iter_ = model.n_iter + + return self + + def define_intervals( + self, df: Optional[pd.DataFrame] = None + ) -> Tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + """Construct MIC interval bounds and apply left-, right-, and interval- + censoring rules, then transform to log dilution space. + + Args: + df (Optional[DataFrame]): Optional MIC data to override stored + input. + + Returns: + Tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + Log-transformed lower bounds, upper bounds, and observation + weights.""" + + if df is None: + df = self.obj_df + + y_low = np.zeros(len(df)) + y_high = np.zeros(len(df)) + weights = df.observations.to_numpy() + + # Calculate tail dilution factor if not censored + if self.boundary_support is not None: + tail_dilution_factor = self.dilution_factor**self.boundary_support + + def parse_mic_value(mic: str) -> float: + """Convert one MIC category to a numeric value. + + + + Args: + mic (str): Input value. + + Returns: + float: Result of the operation.""" + #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 = parse_mic_value(mic[2:]) + y_low[i] = ( + 1e-6 + if self.boundary_support is None + else lower_bound / tail_dilution_factor + ) + y_high[i] = lower_bound + + elif mic.startswith(">"): # Right-censored value + upper_bound = parse_mic_value(mic[1:]) + y_low[i] = upper_bound + y_high[i] = ( + np.inf + if self.boundary_support is None + else upper_bound * tail_dilution_factor + ) + + else: # Exact MIC value + mic_value = parse_mic_value(mic) + y_low[i] = mic_value / self.dilution_factor + y_high[i] = mic_value + + # Apply log transformation to intervals + y_low_log, y_high_log = self.log_transf_intervals(y_low, y_high) + + return y_low_log, y_high_log, weights + + def log_transf_intervals( + self, y_low: NDArray[np.floating], y_high: NDArray[np.floating] + ) -> Tuple[NDArray[np.floating], NDArray[np.floating]]: + """Transform interval bounds into log base–dilution_factor space. + + Args: + y_low (NDArray[np.floating]): Lower interval bounds. + y_high (NDArray[np.floating]): Upper interval bounds. + + Returns: + 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) / log_base + y_high_log = np.log(y_high) / log_base + + return y_low_log, y_high_log + + def generate( + self, percentile: int | float = 99, options: dict[str, Any] | None = None + ) -> Tuple[Any, ...]: + """Fit the model and compute the ECOFF at a specified percentile. + + Args: + percentile (int | float): Desired percentile (default 99). + options (dict[str, Any] | None): Optional fit settings. + + Returns: + Tuple[Any, ...]: ECOFF, percentile location, and fitted means and + standard deviations.""" + + if hasattr(self, "percentile"): + percentile = self.percentile + + self.fit(options=options) # updates self.model_, self.mus_, etc. + results = self.compute_ecoff(percentile) + self.ecoff_ = results[0] + self.z_percentile_ = results[1] + + return results + + 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, between + 0 and 100. + + Returns: + tuple: + For 1 component: + (ecoff, z_percentile, mu, sigma) + For K components: + (ecoff, z_percentile, mu1, sigma1, ..., muK, sigmaK)""" + + assert 0 < percentile < 100, "percentile must be between 0 and 100" + + z = norm.ppf(percentile / 100) + + # SINGLE COMPONENT + if self.distributions == 1: + mu = self.mus_[0] + sigma = self.sigmas_[0] + z_percentile = mu + z * sigma + ecoff = self.dilution_factor**z_percentile + return ecoff, z_percentile, mu, sigma + + # MULTI-COMPONENT + K = self.distributions + + mus = self.mus_ + sigmas = self.sigmas_ + + # WT = component with lowest mean + wt_idx = np.argmin(mus) + mu_wt = mus[wt_idx] + sigma_wt = sigmas[wt_idx] + + # compute ECOFF on WT + z_percentile = mu_wt + z * sigma_wt + ecoff = self.dilution_factor**z_percentile + + # flatten + mus_sigmas = [] + for k in range(K): + mus_sigmas.extend([mus[k], sigmas[k]]) + + 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. + + Args: + None.""" + + K = self.distributions + n = self.obj_df.observations.sum() + wt_idx = int(np.argmin(self.mus_)) + + summary = { + "model_family": "interval-censored log-normal", + "model_type": "mixture" if K > 1 else "single", + "components": K, + "wild_type_component": wt_idx + 1, + "dilution_factor": self.dilution_factor, + "boundary_support": self.boundary_support, + "n_observations": n, + "log_likelihood": self.loglike_, + "converged": self.converged_, + "n_iter": self.n_iter_, + "pis": self.pis_, + } + + # Information criteria (if identifiable) + k_params = 2 * K + (K - 1) + summary["aic"] = 2 * k_params - 2 * self.loglike_ + summary["bic"] = np.log(n) * k_params - 2 * self.loglike_ + + return summary + + diff --git a/src/ecoff_fitter/least_squares.py b/src/ecoff_fitter/least_squares.py new file mode 100644 index 0000000..bc63cc2 --- /dev/null +++ b/src/ecoff_fitter/least_squares.py @@ -0,0 +1,354 @@ +from typing import Any + +import numpy as np +from numpy.typing import NDArray +from scipy.optimize import least_squares +from scipy.stats import norm + +MIN_SIGMA = 0.1 + + +class LeastSquaresRangeSearch: + """Find a WT inclusion range with least-squares candidate fits. + + The first-local-peak rule uses a fixed MIC grid and selects the first + eligible local peak. The largest-bin rule selects the highest-frequency + active bin. + """ + + def __init__( + self, + pmic: NDArray[np.float64], + frequencies: NDArray[np.float64], + detection_level: float = 10.0, + cumulative: bool = True, + first_best: bool = False, + selector: str = "first-local-peak", + ) -> None: + """Initialize the range search with sorted MIC frequencies. + + Args: + pmic (NDArray[np.float64]): Sorted log-dilution MIC values. + frequencies (NDArray[np.float64]): Frequency at each MIC value. + detection_level (float): Minimum eligible peak size as a + percentage of total observations. + cumulative (bool): Whether the least-squares fit uses cumulative + counts rather than per-dilution counts. + first_best (bool): Whether to stop when the count-difference + criterion starts increasing after its best value. + selector (str): ``"largest-bin"`` or ``"first-local-peak"``. + + Raises: + ValueError: If input arrays are not one-dimensional and equal in + length, or if no observations are present. + + Returns: + None.""" + self.pmic = np.asarray(pmic, dtype=float) + self.frequencies = np.asarray(frequencies, dtype=float) + if self.pmic.ndim != 1 or self.frequencies.ndim != 1: + raise ValueError("pMIC and frequencies must be one-dimensional.") + if self.pmic.shape != self.frequencies.shape: + raise ValueError("pMIC and frequencies must have the same length.") + if self.pmic.size == 0: + raise ValueError("At least one MIC value is required.") + + self.detection_level = detection_level + self.cumulative = cumulative + self.first_best = first_best + if not isinstance(selector, str) or selector not in {"first-local-peak", "largest-bin"}: + raise ValueError("selector must be 'largest-bin' or 'first-local-peak'.") + self.selector = selector + self.cumulative_frequencies = np.cumsum(self.frequencies) + + def _find_mode(self) -> int: + """Return a mode index using the selected workbook's detection rule. + + The first-local-peak rule scans for the first eligible local peak. + The largest-bin rule selects the largest remaining raw-count bin, with + the first bin winning ties. + + + Returns: + int: Zero-based selected mode index. + + Args: + None.""" + total = float(np.sum(self.frequencies)) + if total <= 0: + raise ValueError("No MIC observations available for fitting.") + + if self.selector == "largest-bin": + return int(np.argmax(self.frequencies)) + + maximum_row = 1 + for row in range(1, len(self.frequencies) + 1): + count = self.frequencies[row - 1] + maximum_count = self.frequencies[maximum_row - 1] + if maximum_count <= count: + if count / total * 100 > self.detection_level: + maximum_row = row + else: + if row == maximum_row + 1 and maximum_row > 1: + return maximum_row - 1 + + raise ValueError("No eligible local MIC peak was detected.") + + def _initial_range(self, mode: int) -> tuple[int, int]: + """Set the initial range using the selected mode's starting row. + + Args: + mode (int): Zero-based selected mode index. + + Returns: + tuple[int, int]: Inclusive start and end indices.""" + if self.selector == "first-local-peak": + # Mirror VBA FirstNonZero: scan backward from the one-based Mode + # to the nearest zero. Include that row only when it is directly + # below the mode; otherwise start just after the zero. + mode_row = mode + 1 + start_row = 1 + for row in range(mode_row, 0, -1): + if self.frequencies[row - 1] == 0: + start_row = row if row == mode_row - 1 else row + 1 + break + start = start_row - 1 + else: + nonzero = np.flatnonzero(self.frequencies > 0) + start = int(nonzero[0]) + end = min(mode + 1, len(self.pmic) - 1) + return start, max(start, end) + + def _initial_parameters(self, start: int, end: int) -> NDArray[np.float64]: + """Calculate starting values for mean, log-SD, and fitted count. + + Args: + start (int): Inclusive start index. + end (int): Inclusive end index. + + Returns: + NDArray[np.float64]: Initial mean, log-SD, and count.""" + x = self.pmic[start : end + 1] + counts = self.frequencies[start : end + 1] + if self.selector == "first-local-peak": + # Mirror Initial!Mean: OFFSET(pMIC, Mode, 0), plus 0.5 when + # fitting noncumulative density counts. + mu = float(self.pmic[self._detected_mode]) + if not self.cumulative: + mu += 0.5 + + # Mirror XDev(target, From, To, 1): population SD over the + # inclusive range, ignoring zero-frequency bins, defaulting to 1 + # when N <= 1, then clipping to SDevMin/SDevMax (0.1 and 9). + total = float(np.sum(counts)) + if total > 1: + weighted_mean = float(np.sum(x * counts) / total) + variance = float( + np.sum((x - weighted_mean) ** 2 * counts) / total + ) + sigma = float(np.sqrt(variance)) + else: + sigma = 1.0 + sigma = float(np.clip(sigma, MIN_SIGMA, 9.0)) + nest = total + else: + total = max(float(np.sum(counts)), 1.0) + weights = np.maximum(counts, 1e-12) + weighted_mean = float(np.average(x, weights=weights)) + mu = weighted_mean + sigma = float( + np.sqrt(np.average((x - weighted_mean) ** 2, weights=weights)) + ) + sigma = max(sigma, MIN_SIGMA) + nest = total + return np.array([mu, np.log(sigma), nest], dtype=float) + + def _predicted_counts( + self, params: NDArray[np.float64], start: int, end: int + ) -> NDArray[np.float64]: + """Calculate cumulative or per-bin normal predictions. + + Args: + params (NDArray[np.float64]): Mean, log-SD, and fitted count. + start (int): Inclusive start index. + end (int): Inclusive end index. + + Returns: + NDArray[np.float64]: Predicted counts across the range.""" + mu, log_sigma, n_est = params + sigma = float(np.exp(log_sigma)) + x = self.pmic[start : end + 1] + + if self.cumulative: + predicted = n_est * norm.cdf(x, loc=mu, scale=sigma) + elif self.selector == "first-local-peak": + # The fixed-grid method returns the density at each + # bin center, multiplied by Nest; it does not integrate over a + # one-dilution interval. + predicted = n_est * norm.pdf(x, loc=mu, scale=sigma) + else: + lower = x - 0.5 + upper = x + 0.5 + predicted = n_est * ( + norm.cdf(upper, loc=mu, scale=sigma) + - norm.cdf(lower, loc=mu, scale=sigma) + ) + return np.asarray(predicted, dtype=float) + + def _fit_range( + self, + start: int, + end: int, + initial: NDArray[np.float64] | None = None, + ) -> dict[str, Any]: + """Fit the normal model to one candidate inclusion range. + + Args: + start (int): Inclusive start index. + end (int): Inclusive end index. + initial (NDArray[np.float64] | None): Optional starting parameters. + + Returns: + dict[str, Any]: Fit parameters, score, and optimizer result.""" + if initial is None: + initial = self._initial_parameters(start, end) + + # The largest-bin method fits cumulative counts from its fixed + # lower grid boundary (pMIC = -10), including zero-count rows. Keep + # the candidate's selected lower bound unchanged for downstream use. + fit_start = ( + int(np.searchsorted(self.pmic, -10.0, side="left")) + if self.cumulative and self.selector == "largest-bin" + else start + ) + observed = ( + self.cumulative_frequencies[fit_start : end + 1] + if self.cumulative + else self.frequencies[fit_start : end + 1] + ) + + def residuals(params: NDArray[np.float64]) -> NDArray[np.float64]: + """Calculate observed minus predicted counts. + + Args: + params (NDArray[np.float64]): Mean, log-SD, and fitted count. + + Returns: + NDArray[np.float64]: Residuals for the candidate range.""" + return observed - self._predicted_counts(params, fit_start, end) + + result = least_squares( + residuals, + initial, + bounds=( + np.array([-9.0, np.log(MIN_SIGMA), 1.0]), + np.array([9.0, np.log(9.0), 1_000_000.0]), + ), + ) + mu, log_sigma, n_est = result.x + residual = residuals(result.x) + return { + "start": start, + "end": end, + "mu": float(mu), + "sigma": float(np.exp(log_sigma)), + "n_est": float(n_est), + "sumsq": float(np.sum(residual**2)), + "observed_count": float(np.sum(self.frequencies[start : end + 1])), + "success": bool(result.success), + "result": result, + } + + def fit(self) -> dict[str, Any]: + """Iterate candidate ranges and return the best count-matching fit. + + + Returns: + dict[str, Any]: Selected fit and all candidate range fits. + + Args: + None.""" + mode = self._find_mode() + self._detected_mode = mode + start, initial_end = self._initial_range(mode) + + if self.selector == "first-local-peak": + # Match Analyze's range loop: start from its current To (Reset + # gives Mode + 1), refit each candidate from Initial parameters, + # and stop allowing candidates to replace the current best after + # the first zero-frequency bin. Analyze(False) continues fitting + # later bins for display, so retain those candidate diagnostics. + best_difference = float( + np.sum(self.frequencies[start : initial_end + 1]) + ) + best_end = initial_end + stopped = False + candidates = [] + + for end in range(initial_end, len(self.frequencies)): + fit = self._fit_range(start, end) + difference = abs(fit["observed_count"] - fit["n_est"]) + fit["count_difference"] = difference + fit["sd_at_floor"] = bool( + np.isclose(fit["sigma"], MIN_SIGMA, rtol=0.0, atol=1e-6) + ) + candidates.append(fit) + + if self.frequencies[end] == 0: + stopped = True + if not stopped and best_difference >= difference: + best_difference = difference + best_end = end + elif self.first_best: + stopped = True + + # Analyze restores the selected range and runs Solver one more + # time from the workbook's Initial values. + best = self._fit_range(start, best_end) + best["count_difference"] = abs( + best["observed_count"] - best["n_est"] + ) + best["sd_at_floor"] = bool( + np.isclose(best["sigma"], MIN_SIGMA, rtol=0.0, atol=1e-6) + ) + return {"best": best, "candidates": candidates, "mode": mode} + + last_nonzero = len(self.frequencies) - 1 + zero_rows = np.flatnonzero(self.frequencies[initial_end + 1 :] == 0) + if zero_rows.size: + last_nonzero = initial_end + int(zero_rows[0]) + + candidates = [] + params = None + best_difference = np.inf + for end in range(initial_end, max(initial_end, last_nonzero) + 1): + fit = self._fit_range(start, end, params) + params = np.array( + [fit["mu"], np.log(fit["sigma"]), fit["n_est"]], dtype=float + ) + difference = abs(fit["observed_count"] - fit["n_est"]) + fit["count_difference"] = difference + sd_at_floor = np.isclose( + fit["sigma"], MIN_SIGMA, rtol=0.0, atol=1e-6 + ) + fit["sd_at_floor"] = bool(sd_at_floor) + candidates.append(fit) + + # A floor-SD fit is a degenerate candidate. Do not let it trigger + # first_best stopping or set the score threshold for valid fits. + if self.selector == "largest-bin" and not sd_at_floor: + if self.first_best and difference > best_difference: + break + best_difference = min(best_difference, difference) + elif self.selector != "largest-bin": + if self.first_best and difference > best_difference: + break + best_difference = min(best_difference, difference) + + eligible = candidates + if self.selector == "largest-bin": + non_floor = [fit for fit in candidates if not fit["sd_at_floor"]] + if non_floor: + eligible = non_floor + best = min(eligible, key=lambda fit: fit["count_difference"]) + return {"best": best, "candidates": candidates, "mode": mode} diff --git a/src/ecoff_fitter/mixture.py b/src/ecoff_fitter/mixture.py index 34eda7d..2771cc2 100755 --- a/src/ecoff_fitter/mixture.py +++ b/src/ecoff_fitter/mixture.py @@ -38,8 +38,7 @@ def __init__( weights: NDArray[np.floating] | list[float], distributions: int, ) -> None: - """ - Initialise a K-component mixture model using K-means clustering. + """Initialise a K-component mixture model using K-means clustering. Initial parameters are generated as follows: - μ_k: K-means cluster centres of interval midpoints. @@ -54,7 +53,10 @@ def __init__( weights (NDArray[np.floating] | list[float]): Weight for each interval. distributions (int): Number of mixture components (K). - """ + + Returns: + None: Result of the operation.""" + self.K = distributions y_low = np.asarray(y_low, dtype=float) @@ -110,8 +112,7 @@ def __init__( def fit( self, max_iter: int = 500, tol: float = 1e-6, refine: bool = True ) -> "MixtureModel": - """ - Fit the mixture model using EM and optional refinement. + """Fit the mixture model using EM and optional refinement. Args: max_iter (int): Maximum number of EM iterations. @@ -120,8 +121,7 @@ def fit( (μ, log σ, logits) after EM using L-BFGS-B. Returns: - self: The fitted MixtureModel instance. - """ + self: The fitted MixtureModel instance.""" self.em(max_iter, tol) @@ -131,8 +131,7 @@ def fit( return self def em(self, max_iter: int = 500, tol: float = 1e-6) -> "MixtureModel": - """ - Expectation–Maximization (EM) algorithm for a K-component mixture + """Expectation–Maximization (EM) algorithm for a K-component mixture of interval-censored normal distributions. E-step: @@ -151,8 +150,7 @@ def em(self, max_iter: int = 500, tol: float = 1e-6) -> "MixtureModel": Notes: The EM loop records the final iteration count, convergence flag, - log-likelihood, and packed parameter vector on this instance. - """ + log-likelihood, and packed parameter vector on this instance.""" N = len(self.y_low) @@ -230,8 +228,7 @@ def em(self, max_iter: int = 500, tol: float = 1e-6) -> "MixtureModel": return self def refine_mixture(self) -> "MixtureModel": - """ - Refinement step for a general K-component mixture model using L-BFGS-B. + """Refinement step for a general K-component mixture model using L-BFGS-B. Optimizes all parameters jointly: mus, log(sigmas), and mixture logits (K−1 free parameters), @@ -243,7 +240,10 @@ def refine_mixture(self) -> "MixtureModel": Notes: The joint objective is the weighted negative log-likelihood of the observed intervals under the mixture. - """ + + Args: + None.""" + y_low = np.asarray(self.y_low, float) y_high = np.asarray(self.y_high, float) @@ -262,8 +262,7 @@ def unpack_params( Returns: tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: - Component means, scales, and normalized mixture weights. - """ + Component means, scales, and normalized mixture weights.""" mus = params[: self.K] sigmas = np.exp(params[self.K : 2 * self.K]) @@ -282,8 +281,7 @@ def neg_log_likelihood(params: NDArray[np.floating]) -> float: params (NDArray[np.floating]): Flat mixture parameter vector. Returns: - float: Negative weighted log-likelihood. - """ + float: Negative weighted log-likelihood.""" mus, sigmas, pis = unpack_params(params) # P(interval | component k) diff --git a/src/ecoff_fitter/range_search.py b/src/ecoff_fitter/range_search.py index cee97ae..195d33c 100644 --- a/src/ecoff_fitter/range_search.py +++ b/src/ecoff_fitter/range_search.py @@ -1,184 +1,501 @@ +"""Count-based WT range selection and fitted range results.""" + +from dataclasses import dataclass from typing import Any import numpy as np +import pandas as pd from numpy.typing import NDArray -from scipy.optimize import least_squares from scipy.stats import norm +from ecoff_fitter.defence import ( + validate_input_source, + validate_mic_data, + validate_params, + validate_params_source, + validate_range_search_params, +) +from ecoff_fitter.intervals import IntervalRegressionFitter +from ecoff_fitter.least_squares import LeastSquaresRangeSearch +from ecoff_fitter.utils import prepare_input, read_range_search_params + + +@dataclass(frozen=True) +class RangeSelection: + """Selected MIC rows and diagnostics from a count-based WT search.""" -class ECOFFinderRangeSearch: - """Find the WT inclusion range using the ECOFFinder least-squares method. + range_search: str + dilution_factor: int + boundary_support: int | None + percentile: float + selected_df: pd.DataFrame + inclusion_range: tuple[int, int] + mode_idx: int + selection_mu: float + selection_sigma: float + selection_n_est: float + selection_sumsq: float + selection_result: Any + candidates: list[dict[str, Any]] + detection_level: float + cumulative: bool + park_from_mic: float | None - This class owns mode detection, candidate range iteration, least-squares - fitting, and selection by the observed-versus-estimated count difference. - The current candidate-range iteration is an approximation pending - validation against reference workbook outputs. + +class CountRangeSelector: + """Select a wild-type MIC range with a count-based selector. + + Candidate ranges are evaluated using least squares on the log-dilution + scale. The selected observations and diagnostics are returned separately. """ def __init__( self, - pmic: NDArray[np.float64], - frequencies: NDArray[np.float64], + input: Any, + *, + range_search: str, + dilution_factor: int = 2, detection_level: float = 10.0, cumulative: bool = True, first_best: bool = False, + boundary_support: int | None = 1, + park_from_mic: float | None = None, + params: dict[str, Any] | str | None = None, + percentile: float = 99.9, ) -> None: - """Initialize the range search with sorted MIC frequencies. + """Initialize count-based WT range selection with MIC frequencies. Args: - pmic (NDArray[np.float64]): Sorted log-dilution MIC values. - frequencies (NDArray[np.float64]): Frequency at each MIC value. - detection_level (float): Minimum eligible peak size as a - percentage of total observations. - cumulative (bool): Whether the least-squares fit uses cumulative - counts rather than per-dilution counts. - first_best (bool): Whether to stop when the count-difference - criterion starts increasing after its best value. + input: Input accepted by :func:`prepare_input`. + dilution_factor (int): Ratio between adjacent MIC dilution steps. + detection_level (float): Minimum mode frequency as a percentage + of the total count. + cumulative (bool): Fit cumulative counts when True; otherwise fit + per-dilution frequencies. + first_best (bool): Stop range search after the count-difference + criterion begins increasing from its best value. + range_search (str): ``"largest-bin"`` or ``"first-local-peak"``. + boundary_support (int | None): Censoring-bound setting retained + from the shared parameter source. + park_from_mic (float | None): MIC at which values enter the parked + region for largest-bin selection; that MIC and higher bins + are excluded from the range search. + params (dict[str, Any] | str | None): Optional mapping or YAML/TXT + file with common or range-search settings. Values in + the parameter source override the corresponding arguments. + percentile (float): ECOFF percentile retained from the shared + parameter source. Raises: - ValueError: If input arrays are not one-dimensional and equal in - length, or if no observations are present. - """ - self.pmic = np.asarray(pmic, dtype=float) - self.frequencies = np.asarray(frequencies, dtype=float) - if self.pmic.ndim != 1 or self.frequencies.ndim != 1: - raise ValueError("pMIC and frequencies must be one-dimensional.") - if self.pmic.shape != self.frequencies.shape: - raise ValueError("pMIC and frequencies must have the same length.") - if self.pmic.size == 0: - raise ValueError("At least one MIC value is required.") + ValueError: If the dilution factor, detection level, or MIC table + is invalid. + + Returns: + None: Result of the operation.""" + + validate_params_source(params) + if range_search not in {"largest-bin", "first-local-peak"}: + raise ValueError("range_search must be 'largest-bin' or 'first-local-peak'.") + + if params is not None: + ( + dilution_factor, + detection_level, + cumulative, + first_best, + boundary_support, + percentile, + range_search, + park_from_mic, + ) = read_range_search_params( + params, + dilution_factor, + detection_level, + cumulative, + first_best, + boundary_support, + percentile, + range_search, + park_from_mic, + ) + + validate_params(dilution_factor, 1, boundary_support) + validate_range_search_params( + detection_level, cumulative, first_best, percentile, range_search, park_from_mic + ) + + prepared = prepare_input(input) + if prepared.has_individuals: + raise ValueError( + "Range selection expects one MIC distribution. Pass a single " + "MIC/observations table or one assay column." + ) + self.obj_df = prepared.global_df.copy() + validate_input_source(self.obj_df) + validate_mic_data(self.obj_df) + self.dilution_factor = dilution_factor self.detection_level = detection_level self.cumulative = cumulative self.first_best = first_best - self.cumulative_frequencies = np.cumsum(self.frequencies) - - def _find_mode(self) -> int: - """Find the leftmost local mode meeting the detection threshold.""" - total = float(np.sum(self.frequencies)) - if total <= 0: - raise ValueError("No MIC observations available for fitting.") - - threshold = total * self.detection_level / 100 - local_modes = [] - for i, count in enumerate(self.frequencies): - left = self.frequencies[i - 1] if i > 0 else -np.inf - right = ( - self.frequencies[i + 1] if i + 1 < len(self.frequencies) else -np.inf + self.range_search = range_search + self.park_from_mic = park_from_mic + self.boundary_support = boundary_support + self.percentile = float(percentile) + self.pmic_: NDArray[np.float64] + self.observed_: NDArray[np.float64] + self.observed_cumulative_: NDArray[np.float64] + self.inclusion_range_: tuple[int, int] + self.mu_: float + self.sigma_: float + self.n_est_: float + self.sumsq_: float + self.ecoff_: float + self.z_percentile_: float + self.converged_: bool + self.result_: Any + + def prepare_data(self) -> "CountRangeSelector": + """Convert the input table to sorted pMIC and frequency arrays. + + The first-local-peak selector uses a fixed 19-bin grid and rounded log2 + MIC mapping. The largest-bin selector keeps supplied MIC categories + and their exact log-dilution coordinates. + + Returns: + self: The instance with prepared pMIC and frequency arrays. + + Args: + None.""" + + df = self.obj_df.copy() + mic = df["MIC"].astype(str).str.strip() + + # The workbook frequency algorithm expects numeric MIC categories. + # Represent censored categories at their stated threshold for now. + mic = mic.str.replace("<=", "", regex=False) + mic = mic.str.replace(">", "", regex=False) + mic = mic.str.split("/").str[0] + mic_values = pd.to_numeric(mic, errors="raise").to_numpy(dtype=float) + + if np.any(mic_values <= 0): + raise ValueError("MIC values must be greater than zero.") + + frequencies = df["observations"].to_numpy(dtype=float) + + if self.range_search == "first-local-peak": + if self.dilution_factor != 2: + raise ValueError( + "first-local-peak requires dilution_factor=2." + ) + + # fixed-grid #Main has pMIC bin centers -9.5, -8.5, ..., 8.5. + # Its input categories are rounded to the nearest integer log2 + # MIC, and that integer k maps to the center k - 0.5. + log2_mic = np.log2(mic_values) + rounded_bins = np.sign(log2_mic) * np.floor(np.abs(log2_mic) + 0.5) + bin_indices = rounded_bins.astype(int) + 9 + pmic = np.arange(-9.5, 9.0, 1.0, dtype=float) + binned_frequencies = np.zeros(pmic.size, dtype=float) + in_grid = (bin_indices >= 0) & (bin_indices < pmic.size) + outside_nonzero = (~in_grid) & (frequencies > 0) + if np.any(outside_nonzero): + values = mic_values[outside_nonzero].tolist() + raise ValueError( + "Nonzero MIC observations fall outside fixed-grid's " + f"19-bin grid: {values}." + ) + np.add.at( + binned_frequencies, + bin_indices[in_grid], + frequencies[in_grid], ) - if count >= left and count >= right and count >= threshold: - local_modes.append(i) - - if not local_modes: - raise ValueError("No MIC mode meets the configured detection level.") - return local_modes[0] - - def _initial_range(self, mode: int) -> tuple[int, int]: - """Set the initial range from the first count through above the mode.""" - nonzero = np.flatnonzero(self.frequencies > 0) - start = int(nonzero[0]) - end = min(mode + 1, len(self.pmic) - 1) - return start, max(start, end) - - def _initial_parameters(self, start: int, end: int) -> NDArray[np.float64]: - """Calculate starting values for mean, log-SD, and fitted count.""" - x = self.pmic[start : end + 1] - counts = self.frequencies[start : end + 1] - total = max(float(np.sum(counts)), 1.0) - weights = np.maximum(counts, 1e-12) - mu = float(np.average(x, weights=weights)) - sigma = float(np.sqrt(np.average((x - mu) ** 2, weights=weights))) - sigma = max(sigma, 0.1) - return np.array([mu, np.log(sigma), total], dtype=float) - - def _predicted_counts( - self, params: NDArray[np.float64], start: int, end: int - ) -> NDArray[np.float64]: - """Calculate cumulative or per-bin normal predictions.""" - mu, log_sigma, n_est = params - sigma = float(np.exp(log_sigma)) - x = self.pmic[start : end + 1] - - if self.cumulative: - predicted = n_est * norm.cdf(x, loc=mu, scale=sigma) + self._fixed_grid_bin_indices_ = bin_indices + frequencies = binned_frequencies else: - lower = x - 0.5 - upper = x + 0.5 - predicted = n_est * ( - norm.cdf(upper, loc=mu, scale=sigma) - - norm.cdf(lower, loc=mu, scale=sigma) - ) - return np.asarray(predicted, dtype=float) + pmic = np.log(mic_values) / np.log(self.dilution_factor) - def _fit_range( - self, - start: int, - end: int, - initial: NDArray[np.float64] | None = None, - ) -> dict[str, Any]: - """Fit the normal model to one candidate inclusion range.""" - if initial is None: - initial = self._initial_parameters(start, end) - - observed = ( - self.cumulative_frequencies[start : end + 1] - if self.cumulative - else self.frequencies[start : end + 1] + if self.park_from_mic is not None: + pmic_cutoff = np.log(self.park_from_mic) / np.log(self.dilution_factor) + active = pmic < pmic_cutoff + pmic = pmic[active] + frequencies = frequencies[active] + if pmic.size == 0 or float(np.sum(frequencies)) <= 0: + raise ValueError("Parking cutoff excludes all MIC observations.") + if self.range_search == "first-local-peak": + self.pmic_ = pmic + self.observed_ = frequencies + else: + order = np.argsort(pmic) + self.pmic_ = pmic[order] + self.observed_ = frequencies[order] + self.observed_cumulative_ = np.cumsum(self.observed_) + return self + + def search_ranges(self) -> "CountRangeSelector": + """Search candidate ranges and retain the best count-matching fit. + + Candidate iteration and least-squares scoring are handled by + :class:`LeastSquaresRangeSearch`. + + Returns: + self: The instance populated with the selected range and fit. + + Args: + None.""" + + range_search = LeastSquaresRangeSearch( + pmic=self.pmic_, + frequencies=self.observed_, + detection_level=self.detection_level, + cumulative=self.cumulative, + first_best=self.first_best, + selector=self.range_search, ) + search_result = range_search.fit() + best = search_result["best"] + candidates = search_result["candidates"] + self.mode_idx_ = search_result["mode"] + self.inclusion_range_ = (best["start"], best["end"]) + self.selection_mu_ = best["mu"] + self.selection_sigma_ = best["sigma"] + self.selection_n_est_ = best["n_est"] + self.selection_sumsq_ = best["sumsq"] + self.mu_ = self.selection_mu_ + self.sigma_ = self.selection_sigma_ + self.n_est_ = self.selection_n_est_ + self.sumsq_ = best["sumsq"] + self.converged_ = best["success"] + self.result_ = best["result"] + self.range_fits_ = candidates + self.mus_ = np.array([self.mu_], dtype=float) + self.sigmas_ = np.array([self.sigma_], dtype=float) + self.pis_ = np.array([1.0], dtype=float) + return self - def residuals(params: NDArray[np.float64]) -> NDArray[np.float64]: - return observed - self._predicted_counts(params, start, end) + def _selected_df(self) -> pd.DataFrame: + """Return original MIC rows within the selected inclusive range. - result = least_squares( - residuals, - initial, - bounds=( - np.array([-9.0, np.log(0.1), 1.0]), - np.array([9.0, np.log(9.0), 1_000_000.0]), - ), + Args: + None. + + Returns: + pd.DataFrame: Result of the operation.""" + + if not hasattr(self, "inclusion_range_"): + raise RuntimeError("Call search_ranges() before selecting MIC rows.") + + start, end = self.inclusion_range_ + selected_pmic = self.pmic_[start : end + 1] + mic_values = self.obj_df["MIC"].astype(str).str.strip() + numeric_mic = mic_values.str.replace("<=", "", regex=False) + numeric_mic = numeric_mic.str.replace(">", "", regex=False) + numeric_mic = numeric_mic.str.split("/").str[0] + numeric_mic = pd.to_numeric(numeric_mic, errors="raise") + pmic = ( + np.log(numeric_mic.to_numpy(dtype=float)) + / np.log(self.dilution_factor) ) - mu, log_sigma, n_est = result.x - residual = residuals(result.x) - return { - "start": start, - "end": end, - "mu": float(mu), - "sigma": float(np.exp(log_sigma)), - "n_est": float(n_est), - "sumsq": float(np.sum(residual**2)), - "observed_count": float(np.sum(self.frequencies[start : end + 1])), - "success": bool(result.success), - "result": result, - } + if self.range_search == "first-local-peak": + rounded_bins = np.sign(pmic) * np.floor(np.abs(pmic) + 0.5) + bin_indices = rounded_bins.astype(int) + 9 + selected = (bin_indices >= start) & (bin_indices <= end) + else: + selected_min = self.dilution_factor ** selected_pmic[0] + selected_max = self.dilution_factor ** selected_pmic[-1] + selected = (numeric_mic >= selected_min) & (numeric_mic <= selected_max) + selected_df = self.obj_df.loc[selected, ["MIC", "observations"]].copy() + + if selected_df.empty: + raise ValueError("The selected wild-type range contains no MIC rows.") + return selected_df - def fit(self) -> dict[str, Any]: - """Iterate candidate ranges and return the best count-matching fit. + + def select(self) -> "RangeSelection": + """Select and return the wild-type MIC range. Returns: - dict[str, Any]: Selected fit and all candidate range fits. + RangeSelection: Selected MIC rows and range-search diagnostics. + + Args: + None.""" + + self.prepare_data() + self.search_ranges() + return RangeSelection( + range_search=self.range_search, + dilution_factor=self.dilution_factor, + boundary_support=self.boundary_support, + percentile=self.percentile, + selected_df=self._selected_df(), + inclusion_range=self.inclusion_range_, + mode_idx=self.mode_idx_, + selection_mu=self.selection_mu_, + selection_sigma=self.selection_sigma_, + selection_n_est=self.selection_n_est_, + selection_sumsq=self.selection_sumsq_, + selection_result=self.result_, + candidates=self.range_fits_, + detection_level=self.detection_level, + cumulative=self.cumulative, + park_from_mic=self.park_from_mic, + ) + + +class _RangeSearchFitResult: + """Expose a fitted count-selected model through the reporting interface.""" + + def __init__( + self, + selection: RangeSelection, + *, + fitter: str, + interval_fitter: IntervalRegressionFitter | None, + ) -> None: + """Build the report-facing result for a selected MIC range. + + Args: + selection (RangeSelection): Selected observations and diagnostics. + fitter (str): Fitting method used for the selected observations. + interval_fitter (IntervalRegressionFitter | None): Fitted interval + model, or None when least squares supplied the final fit. + + Returns: + None. """ - mode = self._find_mode() - start, initial_end = self._initial_range(mode) - last_nonzero = len(self.frequencies) - 1 - zero_rows = np.flatnonzero(self.frequencies[initial_end + 1 :] == 0) - if zero_rows.size: - last_nonzero = initial_end + int(zero_rows[0]) - - candidates = [] - params = None - best_difference = np.inf - for end in range(initial_end, max(initial_end, last_nonzero) + 1): - fit = self._fit_range(start, end, params) - params = np.array( - [fit["mu"], np.log(fit["sigma"]), fit["n_est"]], dtype=float + self.selection_ = selection + self.fitter = fitter + self.range_search = selection.range_search + self.dilution_factor = selection.dilution_factor + self.boundary_support = selection.boundary_support + self.percentile = selection.percentile + self.distributions = 1 + self.density = False + self.inclusion_range_ = selection.inclusion_range + self.mode_idx_ = selection.mode_idx + self.selection_mu_ = selection.selection_mu + self.selection_sigma_ = selection.selection_sigma + self.selection_n_est_ = selection.selection_n_est + self.selection_sumsq_ = selection.selection_sumsq + self.range_fits_ = selection.candidates + self.interval_fitter_ = interval_fitter + + if interval_fitter is None: + self.mu_ = selection.selection_mu + self.sigma_ = selection.selection_sigma + self.n_est_ = selection.selection_n_est + self.converged_ = bool(selection.selection_result.success) + self.result_ = selection.selection_result + self.mus_ = np.array([self.mu_], dtype=float) + self.sigmas_ = np.array([self.sigma_], dtype=float) + self.pis_ = np.array([1.0], dtype=float) + else: + self.mu_ = float(interval_fitter.mus_[0]) + self.sigma_ = float(interval_fitter.sigmas_[0]) + self.n_est_ = float(np.sum(selection.selected_df["observations"])) + self.converged_ = bool(interval_fitter.converged_) + self.result_ = interval_fitter.model_ + self.mus_ = interval_fitter.mus_.copy() + self.sigmas_ = interval_fitter.sigmas_.copy() + self.pis_ = interval_fitter.pis_.copy() + self.loglike_ = interval_fitter.loglike_ + + def define_intervals( + self, + ) -> tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: + """Return the selected observations as censoring intervals. + + Args: + None. + + Returns: + tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: Result of the operation.""" + + if self.interval_fitter_ is None: + fitter = IntervalRegressionFitter( + input=self.selection_.selected_df, + dilution_factor=self.dilution_factor, + distributions=1, + boundary_support=self.boundary_support, ) - difference = abs(fit["observed_count"] - fit["n_est"]) - fit["count_difference"] = difference - candidates.append(fit) + return fitter.define_intervals() + return self.interval_fitter_.define_intervals() + + def compute_ecoff(self, percentile: float | None = None) -> tuple[float, float]: + """Calculate an ECOFF and its log-dilution location. + + Args: + percentile (float | None): Input value. + + Returns: + tuple[float, float]: Result of the operation.""" - if self.first_best and difference > best_difference: - break - best_difference = min(best_difference, difference) + if percentile is None: + percentile = self.percentile + if not 0 < percentile < 100: + raise ValueError("percentile must be between 0 and 100.") + z_percentile = self.mu_ + norm.ppf(percentile / 100) * self.sigma_ + ecoff = float(self.dilution_factor**z_percentile) + self.ecoff_ = ecoff + self.z_percentile_ = float(z_percentile) + return ecoff, float(z_percentile) - best = min(candidates, key=lambda fit: fit["count_difference"]) - return {"best": best, "candidates": candidates, "mode": mode} + def generate(self, percentile: float | None = None) -> tuple[Any, ...]: + """Return ECOFF, fitted parameters, and the selected inclusive range. + + Args: + percentile (float | None): Input value. + + Returns: + tuple[Any, ...]: Result of the operation.""" + + ecoff, z_percentile = self.compute_ecoff(percentile) + result = ( + ecoff, z_percentile, self.mu_, self.sigma_, self.n_est_, + self.inclusion_range_, + ) + self.generated_result_ = result + return result + + def model_summary(self) -> dict[str, Any]: + """Return selected range, fit parameters, and optimization status. + + Args: + None. + + Returns: + dict[str, Any]: Result of the operation.""" + + return { + "model_family": ( + "interval-censored normal" + if self.fitter == "interval_regression" + else "normal cumulative least squares" + ), + "model_type": "selected MIC range search", + "range_selection_method": "cumulative least squares", + "final_fit_method": ( + "interval regression" + if self.fitter == "interval_regression" + else "cumulative least squares" + ), + "dilution_factor": self.dilution_factor, + "detection_level": self.selection_.detection_level, + "range_search": self.range_search, + "park_from_mic": self.selection_.park_from_mic, + "cumulative": self.selection_.cumulative, + "inclusion_range": self.inclusion_range_, + "mean_log2_mic": self.mu_, + "sd_log2_mic": self.sigma_, + "estimated_wt_count": self.n_est_, + "range_selection_mean_log2_mic": self.selection_mu_, + "range_selection_sd_log2_mic": self.selection_sigma_, + "range_selection_estimated_count": self.selection_n_est_, + "sum_squared_error": self.selection_sumsq_, + "fit_method": ( + "interval regression" + if self.fitter == "interval_regression" + else "cumulative least squares" + ), + "converged": self.converged_, + } diff --git a/src/ecoff_fitter/report.py b/src/ecoff_fitter/report.py index e58d52b..8cacbdd 100755 --- a/src/ecoff_fitter/report.py +++ b/src/ecoff_fitter/report.py @@ -24,20 +24,18 @@ class GenerateReport: @classmethod def from_fitter(cls, fitter: Any, result: Tuple[Any, ...]) -> "GenerateReport": - """ - Construct a GenerateReport from an ECOFFitter and generate() output. + """Construct a GenerateReport from a fitted model and generate() output. result = (ecoff, z_percentile, mu, sigma) # single result = (ecoff, z_percentile, mu1, sigma1, ..., muK, sigmaK) # mixture Args: - fitter (Any): Fitted ECOFFitter instance. + fitter (Any): Fitted model instance. result (Tuple[Any, ...]): Result returned by - :meth:`ECOFFitter.generate`. + :meth:`IntervalRegressionFitter.generate`. Returns: - GenerateReport: Report initialized with ECOFF values and fitter. - """ + GenerateReport: Report initialized with ECOFF values and fitter.""" # Percentiles derived from fitter z0 = fitter.compute_ecoff(percentile=99)[0] @@ -55,32 +53,74 @@ def from_fitter(cls, fitter: Any, result: Tuple[Any, ...]) -> "GenerateReport": @property def distributions(self) -> int: - """Return the number of fitted mixture components.""" + """Return the number of fitted mixture components. + + Args: + None. + + Returns: + int: Result of the operation.""" + return cast(int, self.fitter.distributions) @property def dilution_factor(self) -> float: - """Return the MIC dilution factor used by the fitter.""" + """Return the MIC dilution factor used by the fitter. + + Args: + None. + + Returns: + float: Result of the operation.""" + return cast(float, self.fitter.dilution_factor) @property def mus(self) -> NDArray[np.floating]: - """Return fitted component means in log-dilution space.""" + """Return fitted component means in log-dilution space. + + Args: + None. + + Returns: + NDArray[np.floating]: Result of the operation.""" + return cast(NDArray[np.floating], self.fitter.mus_) @property def sigmas(self) -> NDArray[np.floating]: - """Return fitted component standard deviations.""" + """Return fitted component standard deviations. + + Args: + None. + + Returns: + NDArray[np.floating]: Result of the operation.""" + return cast(NDArray[np.floating], self.fitter.sigmas_) @property def pis(self) -> Optional[NDArray[np.floating]]: - """Return component weights when available.""" + """Return component weights when available. + + Args: + None. + + Returns: + Optional[NDArray[np.floating]]: Result of the operation.""" + return getattr(self.fitter, "pis_", None) @property def model(self) -> Any: - """Return the fitted underlying model object when available.""" + """Return the fitted underlying model object when available. + + Args: + None. + + Returns: + Any: Result of the operation.""" + return getattr(self.fitter, "model_", None) @@ -93,7 +133,10 @@ def intervals( Returns: tuple[NDArray[np.floating], NDArray[np.floating], NDArray[np.floating]]: Lower bounds, upper bounds, and observation weights. - """ + + Args: + None.""" + return cast( tuple[ NDArray[np.floating], @@ -105,14 +148,12 @@ def intervals( def to_text(self, label: str | None = None, verbose: bool = False) -> str: - """ - Args: + """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. - """ + str: Formatted ECOFF and component summary.""" lines = [] if label: @@ -121,7 +162,7 @@ def to_text(self, label: str | None = None, verbose: bool = False) -> str: lines.append(f" ECOFF: {self.ecoff:.4f}") # z-values stored in self.z are ECOFF values for 99, 97.5, 95 percentiles - lines.append(f" log scale: {np.log2(self.ecoff):.4f}\n") + lines.append(f" log scale: {np.log2(self.ecoff):.4f}\n") # Mixture components for i, (mu, sigma) in enumerate(zip(self.mus, self.sigmas), start=1): @@ -147,7 +188,10 @@ def write_out(self, path: str) -> None: Args: path (str): Destination file path. - """ + + Returns: + None: Result of the operation.""" + with open(path, "w") as f: f.write(self.to_text()) @@ -158,7 +202,10 @@ def save_pdf(self, outfile: str) -> None: Args: outfile (str): Destination PDF path. - """ + + Returns: + None: Result of the operation.""" + with PdfPages(outfile) as pdf: fig = self._make_pdf() pdf.savefig(fig) @@ -173,8 +220,7 @@ def _make_pdf(self, title: Optional[str] = None) -> Figure: title (Optional[str]): Optional plot title and report label. Returns: - Figure: Matplotlib figure for the report page. - """ + Figure: Matplotlib figure for the report page.""" fig, (ax_plot, ax_text) = plt.subplots( nrows=1, ncols=2, @@ -220,14 +266,16 @@ def _make_pdf(self, title: Optional[str] = None) -> Figure: fig.tight_layout(rect=(0, 0, 1, 0.95)) return fig - + def _format_model_summary(self) -> list[str]: - """ - Format a structured model summary from the fitter, if available. + """Format a structured model summary from the fitter, if available. Returns: list[str]: Formatted summary lines, or an unavailable notice. - """ + + Args: + None.""" + if not hasattr(self.fitter, "model_summary"): return [" (model summary unavailable)"] @@ -254,20 +302,21 @@ def __init__( global_report: GenerateReport, individual_reports: Dict[str, GenerateReport], ) -> None: - """ - Args: + """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. - """ + + Returns: + None: Result of the operation.""" + self.outfile = outfile self.global_report = global_report self.individual_reports = individual_reports def write_out(self) -> None: - """ - Write a consolidated text report containing: + """Write a consolidated text report containing: - Global fit summary - Individual fit summaries @@ -275,7 +324,10 @@ def write_out(self) -> None: Returns: None - """ + + Args: + None.""" + lines: list[str] = [] # ----- GLOBAL REPORT ----- @@ -293,14 +345,17 @@ def write_out(self) -> None: f.write(text) print(f"\nCombined text report saved to: {self.outfile}") - + def save_pdf(self) -> None: """Write the global and individual reports to a multi-page PDF. Returns: None - """ + + Args: + 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 index 7193fb6..6e3169e 100755 --- a/src/ecoff_fitter/utils.py +++ b/src/ecoff_fitter/utils.py @@ -20,7 +20,14 @@ class PreparedInput: @property def has_individuals(self) -> bool: - """Whether input preparation produced any individual group tables.""" + """Whether input preparation produced any individual group tables. + + Args: + None. + + Returns: + bool: Result of the operation.""" + return len(self.individual_dfs) > 0 @@ -29,8 +36,7 @@ def read_input( data: DataFrame | list[Any] | tuple[Any, ...] | dict[str, Any] | str, sheet_name: Optional[str] = None, ) -> DataFrame: - """ - Strict single-fit reader for ECOFFitter. + """Strict single-fit reader for interval regression. Accepts raw MIC values or a canonical ``MIC`` and ``observations`` table. @@ -43,13 +49,12 @@ def read_input( DataFrame: Canonical table with ``MIC`` and ``observations`` columns. Raises: - ValueError: If the normalized input contains individual group columns. - """ + 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. " + "IntervalRegressionFitter expects a single MIC + observations table. " "For multi-column input, use prepare_input() or run_ecoff_analysis()." ) @@ -59,8 +64,7 @@ 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. + """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. @@ -74,8 +78,7 @@ def prepare_input( sheet_name (Optional[str]): Worksheet name for Excel input. Returns: - PreparedInput: Aggregate table and any per-column tables. - """ + PreparedInput: Aggregate table and any per-column tables.""" df = _load_raw_frame(data, sheet_name=sheet_name) if df.shape[1] == 1: @@ -130,8 +133,7 @@ def _load_raw_frame( DataFrame: Loaded table with whitespace removed from column names. Raises: - ValueError: If the input type or file extension is unsupported. - """ + ValueError: If the input type or file extension is unsupported.""" if isinstance(data, pd.DataFrame): df = data.copy() elif isinstance(data, (list, tuple)): @@ -164,8 +166,7 @@ def read_params( dflt_dists: int, dflt_tails: Optional[int], ) -> Tuple[int, int, Optional[int], float]: - """ - Read ECOFF model parameters from a YAML, TXT, or dictionary source. + """Read ECOFF model parameters from a YAML, TXT, or dictionary source. Args: params (str | dict): File path to a YAML or text parameter file, @@ -181,8 +182,7 @@ def read_params( Raises: FileNotFoundError: If the specified file does not exist. ValueError: If file type is unsupported. - ValueError: If ``params`` is not a mapping after path handling. - """ + ValueError: If ``params`` is not a mapping after path handling.""" params = _load_params_mapping(params) @@ -195,38 +195,54 @@ def read_params( return dilution_factor, distributions, boundary_support, percentile -def read_ecoffinder_params( +def read_range_search_params( params: str | dict[str, Any], dflt_dilution: int, dflt_detection: float, dflt_cumulative: bool, dflt_first_best: bool, - dflt_intervals: bool, dflt_tails: int | None, dflt_percentile: float, -) -> tuple[int, Any, float, bool, bool, bool, int | None, float]: - """Read common and ECOFFinder-specific settings from a config source. + dflt_range_search: str, + dflt_park_from_mic: float | None = None, +) -> tuple[int, float, bool, bool, int | None, float, str, float | None]: + """Read shared and count-based range-search settings from configuration. - Supported keys are ``dilution_factor``, ``distributions``, - ``detection_level``, ``cumulative``, ``first_best``, ``intervals``, - ``boundary_support``, and ``percentile``. ``distributions`` is included - so callers can reject mixture settings that ECOFFinder cannot use. - """ + Args: + params (str | dict[str, Any]): Configuration mapping or file path. + dflt_dilution (int): Default dilution factor. + dflt_detection (float): Default peak detection threshold. + dflt_cumulative (bool): Default cumulative fitting setting. + dflt_first_best (bool): Default early-stop setting. + dflt_tails (int | None): Default censoring-bound support. + dflt_percentile (float): Default ECOFF percentile. + dflt_range_search (str): Default range-search selector. + dflt_park_from_mic (float | None): Default parked MIC threshold. + + Returns: + tuple: Updated settings in the same order as the default arguments.""" values = _load_params_mapping(params) return ( values.get("dilution_factor", dflt_dilution), - values.get("distributions", 1), values.get("detection_level", dflt_detection), values.get("cumulative", dflt_cumulative), values.get("first_best", dflt_first_best), - values.get("intervals", dflt_intervals), values.get("boundary_support", dflt_tails), values.get("percentile", dflt_percentile), + values.get("range_search", dflt_range_search), + values.get("park_from_mic", dflt_park_from_mic), ) def _load_params_mapping(params: str | dict[str, Any]) -> dict[str, Any]: - """Load a parameter mapping and coerce known values in TXT files.""" + """Load a parameter mapping and coerce known values in TXT files. + + Args: + params (str | dict[str, Any]): Input value. + + Returns: + dict[str, Any]: Result of the operation.""" + if isinstance(params, str): if not os.path.exists(params): raise FileNotFoundError(f"Parameter file not found: {params}") @@ -257,7 +273,11 @@ def _load_params_mapping(params: str | dict[str, Any]) -> dict[str, Any]: parsed[key] = float(val) elif key == "detection_level": parsed[key] = float(val) - elif key in {"cumulative", "first_best", "intervals"}: + elif key == "park_from_mic": + parsed[key] = float(val) + elif key == "range_search": + parsed[key] = val.strip().lower() + elif key in {"cumulative", "first_best"}: parsed[key] = _parse_bool(val) else: parsed[key] = val @@ -271,7 +291,14 @@ def _load_params_mapping(params: str | dict[str, Any]) -> dict[str, Any]: def _parse_bool(value: str) -> bool: - """Parse a boolean value used in a text parameter file.""" + """Parse a boolean value used in a text parameter file. + + Args: + value (str): Input value. + + Returns: + bool: Result of the operation.""" + normalized = value.strip().lower() if normalized in {"true", "yes", "1"}: return True @@ -292,7 +319,6 @@ def read_multi_obs_input( Returns: Dict[str, Any]: Mapping with ``"global"`` and ``"individual"`` - entries. - """ + 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 index 4c665c8..54e657d 100755 --- a/src/ecoff_fitter/workflow.py +++ b/src/ecoff_fitter/workflow.py @@ -1,15 +1,10 @@ from dataclasses import dataclass -from typing import Any, Dict, Tuple, cast +from typing import Any, Dict, Tuple -import numpy as np - -from ecoff_fitter.core import ECOFFitter -from ecoff_fitter.ecoffinder_core import ECOFFinder +from ecoff_fitter.core import CoordinateFit, Fitter from ecoff_fitter.report import GenerateReport from ecoff_fitter.utils import PreparedInput, prepare_input -Fitter = ECOFFitter | ECOFFinder - @dataclass class ECOFFRun: @@ -26,6 +21,7 @@ class ECOFFRun: individual_reports (Dict[str, GenerateReport]): Reports for individual input columns. """ + prepared: PreparedInput selected_k: int global_fitter: Fitter @@ -38,6 +34,8 @@ class ECOFFRun: def run_ecoff_analysis( data: Any, *, + fitter: str = "interval_regression", + range_search: str | None = None, params: dict[str, Any] | str | None = None, dilution_factor: int = 2, distributions: int | str = 1, @@ -50,255 +48,92 @@ def run_ecoff_analysis( density: bool = False, options: dict[str, Any] | None = None, sheet_name: str | None = None, - method: str = "ecoffitter", detection_level: float = 10.0, cumulative: bool = True, first_best: bool = False, - intervals: bool = False, + park_from_mic: float | None = None, ) -> ECOFFRun: - """Fit ECOFF models to aggregate data and optionally each input group. + """Fit aggregate and optional individual data with independent method choices. 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. + fitter (str): ``"least_squares"`` or ``"interval_regression"``. + range_search (str | None): ``"largest-bin"``, + ``"first-local-peak"``, or ``"mixture"``. Mixture selection + requires interval regression. + params (dict[str, Any] | str | None): Optional fitting configuration. 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. + distributions (int | str): Number of interval-regression components, + or ``"auto"`` to select a count by score and mixture diagnostics. + max_distributions (int): Maximum component count for automatic selection. + criterion (str): Score used for automatic component selection. + min_delta (float): Minimum score improvement for another component. + boundary_support (int | None): Censoring-bound support setting. 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. - method (str): Fitting method, either ``"ecoffitter"`` or - ``"ecoffinder"``. - detection_level (float): Minimum mode size as a percentage of all - observations when using ECOFFinder. - cumulative (bool): Whether ECOFFinder fits cumulative frequencies. - first_best (bool): Whether ECOFFinder stops after its score begins to - increase from its best value. - intervals (bool): Whether ECOFFinder refits its selected range using - interval regression. + density (bool): Whether reports plot probability density instead of counts. + options (dict[str, Any] | None): Solver and EM options. + sheet_name (str | None): Worksheet to read from Excel input. + detection_level (float): Minimum eligible local-peak size. + cumulative (bool): Whether range fitting uses cumulative counts. + first_best (bool): Whether to stop when the range score increases. + park_from_mic (float | None): Upper MIC threshold for active bins with + the largest-bin selector. Returns: - ECOFFRun: Global fit, optional individual fits, and their reports. - """ + ECOFFRun: Global fit, optional individual fits, and their reports.""" prepared = prepare_input(data, sheet_name=sheet_name) - - if method not in {"ecoffitter", "ecoffinder"}: - raise ValueError("method must be 'ecoffitter' or 'ecoffinder'.") - - if method == "ecoffinder": - if distributions != 1: - raise ValueError( - "ECOFFinder fits one wild-type distribution; " - "distributions must be 1." - ) - - def fit_one(input_df: Any) -> tuple[Fitter, Tuple[Any, ...]]: - if method == "ecoffinder": - fitter = ECOFFinder( - input=input_df, - dilution_factor=dilution_factor, - detection_level=detection_level, - cumulative=cumulative, - first_best=first_best, - intervals=intervals, - boundary_support=boundary_support, - params=params, - percentile=percentile, - ) - result = fitter.generate(options=options) - else: - fitter = ECOFFitter( - input=input_df, - params=params, - dilution_factor=dilution_factor, - distributions=cast(int, distributions), - boundary_support=boundary_support, - ) - result = fitter.generate(percentile=percentile, options=options) - setattr(fitter, "density", density) - return fitter, result - - if method == "ecoffinder": - global_fitter, global_result = fit_one(prepared.global_df) - k = 1 - elif distributions == "auto": - k, score, global_fitter, global_result = select_best_k( - data, - dilution_factor=dilution_factor, - boundary_support=boundary_support, - max_distributions=max_distributions, - percentile=percentile, - criterion=criterion, - min_delta=min_delta, - params=params, - options=options, - sheet_name=sheet_name, - ) - - else: - fixed_distributions = cast(int, distributions) - global_fitter, global_result = fit_one(prepared.global_df) - k = fixed_distributions + coordinator = CoordinateFit() + selected_k, global_fitter, global_result = coordinator.fit( + prepared.global_df, + fitter=fitter, + range_search=range_search, + distributions=distributions, + max_distributions=max_distributions, + criterion=criterion, + min_delta=min_delta, + params=params, + dilution_factor=dilution_factor, + boundary_support=boundary_support, + percentile=percentile, + detection_level=detection_level, + cumulative=cumulative, + first_best=first_best, + park_from_mic=park_from_mic, + options=options, + ) + setattr(global_fitter, "density", density) global_report = GenerateReport.from_fitter(global_fitter, global_result) - individual_fits: Dict[str, Tuple[Fitter, Tuple[Any, ...]]] = {} individual_reports: Dict[str, GenerateReport] = {} - if fit_individual: for name, subdf in prepared.individual_dfs.items(): - if method == "ecoffinder": - fitter, result = fit_one(subdf) - elif 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, result = fit_one(subdf) - - individual_fits[name] = (fitter, result) - individual_reports[name] = GenerateReport.from_fitter(fitter, result) + k, model, result = coordinator.fit( + subdf, + fitter=fitter, + range_search=range_search, + distributions=distributions if distributions == "auto" else selected_k, + max_distributions=max_distributions, + criterion=criterion, + min_delta=min_delta, + params=params, + dilution_factor=dilution_factor, + boundary_support=boundary_support, + percentile=percentile, + detection_level=detection_level, + cumulative=cumulative, + first_best=first_best, + park_from_mic=park_from_mic, + options=options, + ) + setattr(model, "density", density) + individual_fits[name] = (model, result) + individual_reports[name] = GenerateReport.from_fitter(model, 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, + prepared=prepared, selected_k=selected_k, global_fitter=global_fitter, + global_result=global_result, global_report=global_report, + individual_fits=individual_fits, individual_reports=individual_reports, ) - - -def select_best_k( - data: Any, - dilution_factor: int = 2, - boundary_support: int | None = 1, - percentile: float = 99, - criterion: str = "bic", - min_delta: float = 15, - min_pi: float = 0.05, - min_separation: float = 1.0, - max_distributions: int = 2, - params: dict[str, Any] | str | None = None, - options: dict[str, Any] | None = None, - sheet_name: str | None = None, -) -> Tuple[int, float, ECOFFitter, Tuple[Any, ...]]: - """Select a component count by score and mixture diagnostics. - - Candidate models are fitted in increasing component count. Selection - stops when the score improvement is too small, a component weight is - below ``min_pi``, or adjacent components are insufficiently separated. - - Args: - data (Any): MIC input accepted by :func:`prepare_input`. - dilution_factor (int): Ratio between adjacent MIC dilution steps. - boundary_support (int | None): Censoring-bound support setting. - percentile (float): Percentile used to calculate each ECOFF. - criterion (str): Key in ``ECOFFitter.model_summary()`` to minimize. - min_delta (float): Minimum score improvement for adding a component. - min_pi (float): Minimum accepted component mixture weight. - min_separation (float): Minimum adjacent mean separation in pooled - standard deviations. - max_distributions (int): Maximum number of components to evaluate. - params (dict[str, Any] | str | None): Optional parameter mapping or - configuration file path. - options (dict[str, Any] | None): Solver and EM options passed to fits. - sheet_name (str | None): Worksheet to read from Excel input. - - Returns: - tuple[int, float, ECOFFitter, tuple[Any, ...]]: Selected component - count, criterion score, fitted model, and generated result. - """ - - df = prepare_input( - data, - sheet_name=sheet_name, - ).global_df - - n_informative = int((df["observations"] > 0).sum()) - - if n_informative == 0: - raise ValueError("No MIC observations available for fitting.") - - max_k = min( - max_distributions, - n_informative, - ) - - best = None - - for k in range(1, max_k + 1): - - # Fit model - fitter = ECOFFitter( - input=df, - params=params, - dilution_factor=dilution_factor, - distributions=k, - boundary_support=boundary_support, - ) - - result = fitter.generate( - percentile=percentile, - options=options, - ) - - score = fitter.model_summary()[criterion] - - # K=1 is always the starting model - if best is None: - best = (k, score, fitter, result) - continue - - # improve model fit? - _, best_score, _, _ = best - - if best_score - score < min_delta: - break - - # components sufficiently large? - pis = np.asarray(fitter.pis_) - - if np.any(pis < min_pi): - break - - # Are adjacent components sufficiently separated? - order = np.argsort(fitter.mus_) - - mus = np.asarray(fitter.mus_)[order] - sigmas = np.asarray(fitter.sigmas_)[order] - - pooled_sigmas = np.sqrt((sigmas[:-1] ** 2 + sigmas[1:] ** 2) / 2) - - separations = np.diff(mus) / pooled_sigmas - - if np.any(separations < min_separation): - break - - best = (k, score, fitter, result) - - assert best is not None - return best diff --git a/tests/test_ecoff_fitter.py b/tests/test_ecoff_fitter.py index dee18e7..12898f1 100755 --- a/tests/test_ecoff_fitter.py +++ b/tests/test_ecoff_fitter.py @@ -2,16 +2,16 @@ import numpy as np import pandas as pd -from ecoff_fitter import ECOFFitter +from ecoff_fitter import IntervalRegressionFitter # __init__.py AND PACKAGE IMPORT TESTS -def test_ecoffitter_importable_from_root(): - """Package root must expose ECOFFitter.""" +def test_interval_regression_fitter_importable_from_root(): + """Package root must expose IntervalRegressionFitter.""" import ecoff_fitter - assert hasattr(ecoff_fitter, "ECOFFitter") - assert ecoff_fitter.ECOFFitter is ECOFFitter + assert hasattr(ecoff_fitter, "IntervalRegressionFitter") + assert ecoff_fitter.IntervalRegressionFitter is IntervalRegressionFitter def test_main_invokes_cli(monkeypatch): @@ -51,7 +51,7 @@ def censored_data(): def test_init_with_dataframe(simple_data): - fitter = ECOFFitter(simple_data, dilution_factor=2, distributions=1) + fitter = IntervalRegressionFitter(simple_data, dilution_factor=2, distributions=1) assert fitter.dilution_factor == 2 assert fitter.distributions == 1 assert "MIC" in fitter.obj_df.columns @@ -61,7 +61,7 @@ def test_init_with_dataframe(simple_data): # INTERVAL CONSTRUCTION def test_define_intervals_uncensored(simple_data): - fitter = ECOFFitter(simple_data) + fitter = IntervalRegressionFitter(simple_data) y_low, y_high, weights = fitter.define_intervals() assert np.all(y_low < y_high) @@ -77,7 +77,7 @@ def test_define_intervals_uncensored(simple_data): def test_define_intervals_with_censoring(censored_data): - fitter = ECOFFitter(censored_data, boundary_support=None) + fitter = IntervalRegressionFitter(censored_data, boundary_support=None) y_low, y_high, _ = fitter.define_intervals() # left censored: <=0.5 → low = ~0 @@ -88,7 +88,7 @@ def test_define_intervals_with_censoring(censored_data): def test_log_transf_intervals_direct(simple_data): - fitter = ECOFFitter(simple_data) + fitter = IntervalRegressionFitter(simple_data) y_low = np.array([0.5, 1.0, 2.0]) y_high = np.array([1.0, 2.0, 4.0]) low_log, high_log = fitter.log_transf_intervals(y_low, y_high) @@ -103,7 +103,7 @@ def test_log_transf_intervals_direct(simple_data): @pytest.mark.parametrize("dists", [1, 2]) def test_fit_model_runs(simple_data, dists): - fitter = ECOFFitter(simple_data, distributions=dists) + fitter = IntervalRegressionFitter(simple_data, distributions=dists) result = fitter.fit() # After fitting, Fitter must have mus_, sigmas_, etc. @@ -117,7 +117,7 @@ def test_fit_model_runs(simple_data, dists): def test_fit_mixture_returns_structure(simple_data): - fitter = ECOFFitter(simple_data, distributions=2) + fitter = IntervalRegressionFitter(simple_data, distributions=2) fitter.fit() assert len(fitter.mus_) == 2 @@ -133,7 +133,7 @@ def test_fit_mixture_returns_structure(simple_data): # ============================================================ def test_generate_returns_valid_output(simple_data): - fitter = ECOFFitter(simple_data, distributions=1) + fitter = IntervalRegressionFitter(simple_data, distributions=1) ecoff, z_pt, mu, sigma = fitter.generate(99) assert isinstance(ecoff, float) @@ -142,7 +142,7 @@ def test_generate_returns_valid_output(simple_data): def test_compute_ecoff_matches_generate(simple_data): - fitter = ECOFFitter(simple_data) + fitter = IntervalRegressionFitter(simple_data) ecoff_g, z_g, mu_g, sig_g = fitter.generate(99) ecoff_d, z_d, mu_d, sig_d = fitter.compute_ecoff(99) @@ -154,7 +154,7 @@ def test_compute_ecoff_matches_generate(simple_data): def test_compute_ecoff_percentiles_increase(simple_data): - fitter = ECOFFitter(simple_data) + fitter = IntervalRegressionFitter(simple_data) fitter.fit() ecoff95, *_ = fitter.compute_ecoff(95) @@ -168,7 +168,7 @@ def test_compute_ecoff_percentiles_increase(simple_data): # ============================================================ def test_full_pipeline_mixture(simple_data): - fitter = ECOFFitter(simple_data, distributions=2) + fitter = IntervalRegressionFitter(simple_data, distributions=2) results = fitter.generate(97.5) ecoff = results[0] @@ -198,7 +198,7 @@ def test_em_mixture_handles_overlap_and_separation(mu1, mu2): "observations": weight, }) - fitter = ECOFFitter(df, distributions=2) + fitter = IntervalRegressionFitter(df, distributions=2) fitter.y_low_ = np.log2(y_low) fitter.y_high_ = np.log2(y_high) fitter.weights_ = weight @@ -215,7 +215,7 @@ def test_em_mixture_handles_overlap_and_separation(mu1, mu2): def test_fit_mixture_refine_flag(monkeypatch, simple_data): """Ensure refine=True path runs without error.""" - fitter = ECOFFitter(simple_data, distributions=2) + fitter = IntervalRegressionFitter(simple_data, distributions=2) # monkeypatch MixtureModel.fit to simulate convergence class FakeModel: @@ -242,7 +242,7 @@ def test_model_summary_basic(simple_data): model_summary() should return a structured, self-consistent summary after fitting. """ - fitter = ECOFFitter(simple_data, distributions=2) + fitter = IntervalRegressionFitter(simple_data, distributions=2) fitter.fit() summary = fitter.model_summary() diff --git a/tests/test_range_search.py b/tests/test_range_search.py new file mode 100644 index 0000000..6f621b3 --- /dev/null +++ b/tests/test_range_search.py @@ -0,0 +1,45 @@ +import numpy as np +import pytest + +from ecoff_fitter.least_squares import LeastSquaresRangeSearch + + +def make_search(frequencies, detection_level=10): + return LeastSquaresRangeSearch( + pmic=np.arange(len(frequencies), dtype=float), + frequencies=np.asarray(frequencies, dtype=float), + detection_level=detection_level, + selector="first-local-peak", + ) + + +def test_find_mode_returns_first_qualifying_local_peak(): + search = make_search([1, 15, 2, 20, 1]) + + assert search._find_mode() == 1 + + +def test_find_mode_keeps_first_local_peak_even_if_it_is_below_threshold(): + search = make_search([1, 8, 1, 1, 20, 1]) + + assert search._find_mode() == 1 + + +def test_find_mode_threshold_controls_candidate_replacement(): + search = make_search([1, 20, 2, 30, 1], detection_level=10) + + # The first confirmed peak is returned; later candidates are not reached. + assert search._find_mode() == 1 + + +def test_find_mode_skips_first_bin_and_finds_next_qualifying_peak(): + search = make_search([20, 1, 2, 15, 1], detection_level=40) + + with pytest.raises(ValueError, match="No eligible local MIC peak"): + search._find_mode() + + +def test_find_mode_does_not_treat_last_bin_as_a_local_mode(): + search = make_search([1, 20, 1, 2, 15]) + + assert search._find_mode() == 1 diff --git a/tests/test_report.py b/tests/test_report.py index ac607d1..2aa4382 100755 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -25,14 +25,6 @@ def _mock_run(): return run -@pytest.fixture -def mock_fitter(monkeypatch): - mock = MagicMock(name="ECOFFitterMock") - mock.generate.return_value = (4.0, 2.0, 1.0, 0.5) - monkeypatch.setattr(cli, "ECOFFitter", MagicMock(return_value=mock)) - return mock - - @pytest.fixture def mock_report(monkeypatch): report_instance = MagicMock(name="ReportInstance") @@ -72,7 +64,7 @@ def test_parser_accepts_basic_args(): # CLI integration tests -def test_main_runs_with_minimal_args(mock_loader, mock_fitter, mock_report): +def test_main_runs_with_minimal_args(mock_loader, mock_report): cli.main(["--input", "fake.csv"]) mock_loader.assert_called_once_with( @@ -84,6 +76,12 @@ def test_main_runs_with_minimal_args(mock_loader, mock_fitter, mock_report): percentile=99.0, fit_individual=False, density=False, + fitter="interval_regression", + range_search=None, + detection_level=10.0, + cumulative=True, + first_best=False, + park_from_mic=None, ) diff --git a/tests/test_workflow.py b/tests/test_workflow.py index 3886260..44fa2a6 100644 --- a/tests/test_workflow.py +++ b/tests/test_workflow.py @@ -5,6 +5,7 @@ import pytest import ecoff_fitter.workflow as workflow +import ecoff_fitter.core as core from ecoff_fitter.utils import PreparedInput @@ -26,8 +27,11 @@ def test_run_ecoff_analysis_fixed_components_with_individual_fits(monkeypatch): global_fitter = _fitter() individual_fitter = _fitter() - fitter_factory = MagicMock(side_effect=[global_fitter, individual_fitter]) - monkeypatch.setattr(workflow, "ECOFFitter", fitter_factory) + coordinator = MagicMock(side_effect=[ + (2, global_fitter, global_fitter.generate.return_value), + (2, individual_fitter, individual_fitter.generate.return_value), + ]) + monkeypatch.setattr(workflow.CoordinateFit, "fit", coordinator) monkeypatch.setattr( workflow.GenerateReport, "from_fitter", @@ -37,6 +41,7 @@ def test_run_ecoff_analysis_fixed_components_with_individual_fits(monkeypatch): run = workflow.run_ecoff_analysis( "input", distributions=2, + range_search="mixture", percentile=97.5, fit_individual=True, density=True, @@ -49,10 +54,10 @@ def test_run_ecoff_analysis_fixed_components_with_individual_fits(monkeypatch): 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} - ) + assert coordinator.call_count == 2 + for call_args in coordinator.call_args_list: + assert call_args.kwargs["fitter"] == "interval_regression" + assert call_args.kwargs["range_search"] == "mixture" def test_run_ecoff_analysis_skips_individual_fits(monkeypatch): @@ -62,15 +67,15 @@ def test_run_ecoff_analysis_skips_individual_fits(monkeypatch): ) 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) + coordinator = MagicMock(return_value=(1, fitter, fitter.generate.return_value)) + monkeypatch.setattr(workflow.CoordinateFit, "fit", coordinator) 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 coordinator.call_count == 1 assert run.global_report is not None @@ -81,12 +86,13 @@ def test_run_ecoff_analysis_auto_selection(monkeypatch): 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) + select = MagicMock(return_value=(3, fitter, result)) + monkeypatch.setattr(workflow.CoordinateFit, "fit", select) monkeypatch.setattr(workflow.GenerateReport, "from_fitter", MagicMock()) run = workflow.run_ecoff_analysis( - "input", distributions="auto", max_distributions=4, fit_individual=False + "input", distributions="auto", range_search="mixture", + max_distributions=4, fit_individual=False ) assert run.selected_k == 3 @@ -98,16 +104,16 @@ def test_run_ecoff_analysis_auto_selection(monkeypatch): 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) + core.CoordinateFit._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) + monkeypatch.setattr(core, "IntervalRegressionFitter", factory) - k, score, fitter, result = workflow.select_best_k( + k, score, fitter, result = core.CoordinateFit._select_best_k( data, max_distributions=3, min_delta=15 ) @@ -129,9 +135,9 @@ def test_select_best_k_rejects_small_or_overlapping_component( 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) + monkeypatch.setattr(core, "IntervalRegressionFitter", factory) - selected = workflow.select_best_k( + selected = core.CoordinateFit._select_best_k( data, max_distributions=2, min_delta=15, min_pi=0.05, min_separation=1.0 ) From af2fa883aecf55729e8bfebe12dc01cb25f020aa Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Tue, 27 Oct 2026 17:10:15 +0200 Subject: [PATCH 3/4] test --- tests/test_core.py | 165 +++++++++++++++++++++++++++ tests/test_range_search.py | 225 +++++++++++++++++++++++++++++++++++++ 2 files changed, 390 insertions(+) create mode 100644 tests/test_core.py diff --git a/tests/test_core.py b/tests/test_core.py new file mode 100644 index 0000000..1cd1fdb --- /dev/null +++ b/tests/test_core.py @@ -0,0 +1,165 @@ +from unittest.mock import MagicMock + +import numpy as np +import pandas as pd +import pytest +from scipy.optimize import OptimizeResult + +import ecoff_fitter.core as core +from ecoff_fitter.range_search import RangeSelection + + +def _selection(): + return RangeSelection( + range_search="largest-bin", + dilution_factor=2, + boundary_support=1, + percentile=99.0, + selected_df=pd.DataFrame({"MIC": ["1"], "observations": [4]}), + inclusion_range=(0, 0), + mode_idx=0, + selection_mu=0.0, + selection_sigma=1.0, + selection_n_est=4.0, + selection_sumsq=0.3, + selection_result=OptimizeResult(success=True), + candidates=[], + detection_level=10.0, + cumulative=True, + park_from_mic=None, + ) + + +class FakeIntervalFitter: + def __init__(self, **kwargs): + self.kwargs = kwargs + self.mus_ = np.array([0.25]) + self.sigmas_ = np.array([0.5]) + self.pis_ = np.array([1.0]) + self.converged_ = True + self.model_ = object() + self.loglike_ = -2.0 + + def generate(self, **kwargs): + self.generate_kwargs = kwargs + return (2.5, 1.25, 0.25, 0.5) + + def fit(self, **kwargs): + self.fit_kwargs = kwargs + return self + + +@pytest.mark.parametrize( + "fitter,range_search,distributions,match", + [ + ("bad", "largest-bin", 1, "fitter must be"), + ("interval_regression", "unknown", 1, "range_search must be"), + ("least_squares", "mixture", 2, "requires a count-based"), + ("least_squares", None, 1, "requires a count-based"), + ("interval_regression", "mixture", 1, "at least two"), + ("interval_regression", None, 2, "Multiple components require"), + ("interval_regression", "largest-bin", 2, "fit one wild-type"), + ], +) +def test_fit_fixed_rejects_incompatible_fitter_and_selector( + fitter, range_search, distributions, match +): + with pytest.raises(ValueError, match=match): + core.CoordinateFit._fit_fixed( + pd.DataFrame({"MIC": ["1"], "observations": [1]}), + fitter=fitter, + range_search=range_search, + distributions=distributions, + ) + + +@pytest.mark.parametrize("selector", ["mixture", None]) +def test_fit_fixed_direct_interval_path(monkeypatch, selector): + fake = FakeIntervalFitter() + monkeypatch.setattr(core, "IntervalRegressionFitter", lambda **kwargs: fake) + + model, result = core.CoordinateFit._fit_fixed( + pd.DataFrame({"MIC": ["1"], "observations": [5]}), + fitter="interval_regression", + range_search=selector, + distributions=2 if selector == "mixture" else 1, + options={"max_iter": 3}, + ) + + assert model is fake + assert result == (2.5, 1.25, 0.25, 0.5) + assert fake.generate_kwargs["options"] == {"max_iter": 3} + + +@pytest.mark.parametrize("fitter", ["least_squares", "interval_regression"]) +def test_fit_fixed_count_selector_routes_to_final_fitter(monkeypatch, fitter): + selection = _selection() + selector = MagicMock() + selector.return_value.select.return_value = selection + monkeypatch.setattr(core, "CountRangeSelector", selector) + fake = FakeIntervalFitter() + monkeypatch.setattr(core, "IntervalRegressionFitter", lambda **kwargs: fake) + + model, result = core.CoordinateFit._fit_fixed( + selection.selected_df, + fitter=fitter, + range_search="largest-bin", + distributions=1, + ) + + assert result[0] == pytest.approx(2 ** result[1]) + assert selector.call_args.kwargs["range_search"] == "largest-bin" + if fitter == "least_squares": + assert model.interval_fitter_ is None + else: + assert model.interval_fitter_ is fake + assert fake.fit_kwargs == {"options": None} + + +def test_select_best_k_accepts_well_separated_improved_model(monkeypatch): + data = pd.DataFrame({"MIC": ["1", "2"], "observations": [5, 5]}) + first = MagicMock() + first.generate.return_value = (1.0, 0.0) + first.model_summary.return_value = {"bic": 100.0} + second = MagicMock() + second.generate.return_value = (2.0, 1.0) + second.model_summary.return_value = {"bic": 70.0} + second.pis_ = np.array([0.5, 0.5]) + second.mus_ = np.array([0.0, 3.0]) + second.sigmas_ = np.array([0.5, 0.5]) + factory = MagicMock(side_effect=[first, second]) + monkeypatch.setattr(core, "IntervalRegressionFitter", factory) + + k, score, model, result = core.CoordinateFit._select_best_k( + data, max_distributions=2, min_delta=15, min_separation=1.0 + ) + + assert (k, score, model, result) == (2, 70.0, second, (2.0, 1.0)) + + +def test_fit_auto_component_count_routes_to_selection(monkeypatch): + model = MagicMock() + result = (2.0, 1.0) + select = MagicMock(return_value=(2, 80.0, model, result)) + monkeypatch.setattr(core.CoordinateFit, "_select_best_k", select) + + chosen_k, chosen_model, chosen_result = core.CoordinateFit().fit( + pd.DataFrame({"MIC": ["1"], "observations": [5]}), + fitter="interval_regression", + range_search="mixture", + distributions="auto", + max_distributions=3, + ) + + assert (chosen_k, chosen_model, chosen_result) == (2, model, result) + select.assert_called_once() + + +def test_fit_auto_component_count_rejects_other_methods(): + with pytest.raises(ValueError, match="Automatic component selection requires"): + core.CoordinateFit().fit( + pd.DataFrame({"MIC": ["1"], "observations": [5]}), + fitter="least_squares", + range_search="largest-bin", + distributions="auto", + ) diff --git a/tests/test_range_search.py b/tests/test_range_search.py index 6f621b3..8cd50ce 100644 --- a/tests/test_range_search.py +++ b/tests/test_range_search.py @@ -2,6 +2,7 @@ import pytest from ecoff_fitter.least_squares import LeastSquaresRangeSearch +from ecoff_fitter.range_search import CountRangeSelector, _RangeSearchFitResult def make_search(frequencies, detection_level=10): @@ -43,3 +44,227 @@ def test_find_mode_does_not_treat_last_bin_as_a_local_mode(): search = make_search([1, 20, 1, 2, 15]) assert search._find_mode() == 1 + + +def test_largest_bin_range_search_fits_candidates_and_returns_best(): + search = LeastSquaresRangeSearch( + pmic=np.arange(5, dtype=float), + frequencies=np.array([1, 4, 20, 8, 1], dtype=float), + selector="largest-bin", + ) + + result = search.fit() + + assert result["mode"] == 2 + assert result["best"]["start"] == 0 + assert result["best"]["end"] in range(3, 5) + assert result["candidates"] + assert result["best"]["sumsq"] >= 0 + + +def test_largest_bin_first_best_stops_when_score_worsens(): + search = LeastSquaresRangeSearch( + pmic=np.arange(6, dtype=float), + frequencies=np.array([1, 4, 20, 8, 3, 1], dtype=float), + selector="largest-bin", + first_best=True, + ) + + result = search.fit() + + assert len(result["candidates"]) <= 4 + assert result["best"] in result["candidates"] + + +@pytest.mark.parametrize( + "pmic,frequencies,selector", + [ + (np.array([[0.0]]), np.array([1.0]), "largest-bin"), + (np.array([0.0]), np.array([[1.0]]), "largest-bin"), + (np.array([0.0]), np.array([1.0, 2.0]), "largest-bin"), + (np.array([], dtype=float), np.array([], dtype=float), "largest-bin"), + ], +) +def test_range_search_rejects_invalid_arrays(pmic, frequencies, selector): + with pytest.raises(ValueError): + LeastSquaresRangeSearch(pmic, frequencies, selector=selector) + + +def test_range_search_rejects_unknown_selector(): + with pytest.raises(ValueError, match="selector must be"): + LeastSquaresRangeSearch(np.array([0.0]), np.array([1.0]), selector="other") + + +def test_largest_bin_mode_rejects_zero_counts(): + search = LeastSquaresRangeSearch( + np.array([0.0, 1.0]), np.array([0.0, 0.0]), selector="largest-bin" + ) + with pytest.raises(ValueError, match="No MIC observations"): + search._find_mode() + + +@pytest.mark.parametrize( + "selector,frequencies,expected", + [ + ("largest-bin", [1, 5, 3], (0, 2)), + ("first-local-peak", [1, 5, 1], (0, 2)), + ], +) +def test_initial_range_and_parameters_cover_both_selectors( + selector, frequencies, expected +): + search = LeastSquaresRangeSearch( + np.arange(3, dtype=float), + np.asarray(frequencies, dtype=float), + selector=selector, + ) + mode = search._find_mode() + search._detected_mode = mode + + assert search._initial_range(mode) == expected + params = search._initial_parameters(*expected) + assert params.shape == (3,) + assert np.all(np.isfinite(params)) + + +def test_predicted_count_paths_return_finite_values(): + params = np.array([1.0, np.log(0.8), 20.0]) + grid = np.arange(3, dtype=float) + cumulative = LeastSquaresRangeSearch(grid, np.array([2.0, 4.0, 3.0])) + density = LeastSquaresRangeSearch( + grid, np.array([2.0, 4.0, 3.0]), cumulative=False, + selector="first-local-peak", + ) + bins = LeastSquaresRangeSearch( + grid, np.array([2.0, 4.0, 3.0]), cumulative=False, + selector="largest-bin", + ) + + assert np.all(np.isfinite(cumulative._predicted_counts(params, 0, 2))) + assert np.all(np.isfinite(density._predicted_counts(params, 0, 2))) + assert np.all(np.isfinite(bins._predicted_counts(params, 0, 2))) + + +def test_first_local_peak_non_cumulative_fit_and_single_count_initialization(): + search = LeastSquaresRangeSearch( + pmic=np.array([-1.0, 0.0, 1.0]), + frequencies=np.array([1.0, 20.0, 1.0]), + cumulative=False, + selector="first-local-peak", + ) + mode = search._find_mode() + search._detected_mode = mode + single_observation = LeastSquaresRangeSearch( + pmic=np.array([-1.0, 0.0, 1.0]), + frequencies=np.array([0.0, 1.0, 0.0]), + cumulative=False, + selector="first-local-peak", + ) + single_observation._detected_mode = 1 + params = single_observation._initial_parameters(1, 1) + assert params[0] == pytest.approx(0.5) + assert params[1] == pytest.approx(np.log(1.0)) + + fit = search._fit_range(0, 2) + assert np.isfinite(fit["sumsq"]) + assert fit["success"] + + +def test_count_selector_reads_overrides_from_params_mapping(): + import pandas as pd + + frame = pd.DataFrame( + {"MIC": ["0.5", "1", "2", "4", "8"], "observations": [1, 5, 20, 8, 1]} + ) + selected = CountRangeSelector( + frame, + range_search="largest-bin", + params={"detection_level": 5, "cumulative": False}, + ).select() + + assert selected.detection_level == 5 + assert selected.cumulative is False + + +def test_count_selector_runs_largest_bin_and_first_local_peak(): + import pandas as pd + + frame = pd.DataFrame( + {"MIC": ["0.5", "1", "2", "4", "8"], "observations": [1, 20, 2, 1, 0]} + ) + local = CountRangeSelector( + frame, range_search="first-local-peak", detection_level=2 + ).select() + largest = CountRangeSelector( + frame, range_search="largest-bin", detection_level=2 + ).select() + + assert len(local.selected_df) > 0 + assert len(largest.selected_df) > 0 + assert local.range_search == "first-local-peak" + assert largest.range_search == "largest-bin" + + +def test_count_selector_rejects_micdat_non_doubling_and_parking_empty_range(): + import pandas as pd + + frame = pd.DataFrame({"MIC": ["1", "2"], "observations": [2, 4]}) + with pytest.raises(ValueError, match="requires dilution_factor=2"): + CountRangeSelector( + frame, range_search="first-local-peak", dilution_factor=3 + ).prepare_data() + with pytest.raises(ValueError, match="excludes all MIC observations"): + CountRangeSelector( + frame, range_search="largest-bin", park_from_mic=0.5 + ).prepare_data() + + +def test_count_selector_rejects_invalid_selector_and_multiple_groups(): + import pandas as pd + + frame = pd.DataFrame({"MIC": ["1"], "observations": [2]}) + with pytest.raises(ValueError, match="range_search must be"): + CountRangeSelector(frame, range_search="mixture") + with pytest.raises(ValueError, match="expects one MIC distribution"): + CountRangeSelector( + pd.DataFrame({"MIC": ["1"], "A": [2], "B": [3]}), + range_search="largest-bin", + ) + + +def test_range_result_adapter_generates_ecoff_and_reports_summary(): + import pandas as pd + from scipy.optimize import OptimizeResult + from ecoff_fitter.range_search import RangeSelection + + selection = RangeSelection( + range_search="largest-bin", + dilution_factor=2, + boundary_support=1, + percentile=99.0, + selected_df=pd.DataFrame({"MIC": ["1"], "observations": [3]}), + inclusion_range=(0, 0), + mode_idx=0, + selection_mu=0.0, + selection_sigma=1.0, + selection_n_est=3.0, + selection_sumsq=0.2, + selection_result=OptimizeResult(success=True), + candidates=[], + detection_level=10.0, + cumulative=True, + park_from_mic=None, + ) + result = _RangeSearchFitResult( + selection, fitter="least_squares", interval_fitter=None + ) + + ecoff, location = result.compute_ecoff() + generated = result.generate() + + assert ecoff == pytest.approx(2 ** location) + assert generated[-1] == (0, 0) + assert result.model_summary()["fit_method"] == "cumulative least squares" + assert result.define_intervals()[2].tolist() == [3] + with pytest.raises(ValueError, match="percentile must be between"): + result.compute_ecoff(100) From 57e0aa94d4c5a68a400ffa71dd63877a65b2f420 Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Tue, 27 Oct 2026 17:13:51 +0200 Subject: [PATCH 4/4] test --- src/ecoff_fitter/least_squares.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ecoff_fitter/least_squares.py b/src/ecoff_fitter/least_squares.py index bc63cc2..3e95feb 100644 --- a/src/ecoff_fitter/least_squares.py +++ b/src/ecoff_fitter/least_squares.py @@ -1,4 +1,4 @@ -from typing import Any +from typing import Any, Callable, cast import numpy as np from numpy.typing import NDArray @@ -237,7 +237,8 @@ def residuals(params: NDArray[np.float64]) -> NDArray[np.float64]: NDArray[np.float64]: Residuals for the candidate range.""" return observed - self._predicted_counts(params, fit_start, end) - result = least_squares( + solver = cast(Callable[..., Any], least_squares) + result = solver( residuals, initial, bounds=(