diff --git a/docs/adr/0011-public-api-and-object-model.md b/docs/adr/0011-public-api-and-object-model.md index 773be2e3..0c0bc91a 100644 --- a/docs/adr/0011-public-api-and-object-model.md +++ b/docs/adr/0011-public-api-and-object-model.md @@ -1,6 +1,6 @@ # ADR 0011 — Public API and object model -- Status: Accepted +- Status: Accepted; public-flow section partially superseded by ADR 0022 - Recorded: 2026-09-11 (retrospective) ## Context @@ -17,7 +17,9 @@ misda.evaluate(mis_set, metrics=(...), candidates=...) ranking = misda.rank(mis_set, policy="size_span") ``` -The canonical ranking policy name is governed by ADR 0017. +This low-level flow remains valid for scientific instrumentation and advanced use, but ADR 0022 supersedes it as the canonical user-facing workflow with `profile(Y) -> discovery(profile)`. + +The canonical low-level structural ranking policy name is governed by ADR 0017. ### MISSet diff --git a/docs/adr/0019-user-facing-mis-ranking-workflow.md b/docs/adr/0019-user-facing-mis-ranking-workflow.md index 366813ae..15832f1b 100644 --- a/docs/adr/0019-user-facing-mis-ranking-workflow.md +++ b/docs/adr/0019-user-facing-mis-ranking-workflow.md @@ -1,6 +1,6 @@ # ADR 0019 — User-facing MIS, ranking, and evaluation workflow -- Status: Accepted +- Status: Superseded by ADR 0022 - Recorded: 2026-09-20 ## Context diff --git a/docs/adr/0022-profile-to-discovery-user-workflow.md b/docs/adr/0022-profile-to-discovery-user-workflow.md new file mode 100644 index 00000000..e83e06c2 --- /dev/null +++ b/docs/adr/0022-profile-to-discovery-user-workflow.md @@ -0,0 +1,165 @@ +# ADR 0022 — Profile-to-discovery user workflow + +- Status: Accepted +- Recorded: 2026-10-01 +- Supersedes: ADR 0019 as the canonical user-facing workflow +- Partially supersedes: ADR 0011 public-flow section +- Refines but does not supersede: ADR 0017 and ADR 0021 + +## Context + +The low-level MISDA API deliberately separated structural discovery, +candidate evaluation, and ranking: + +```python +mis_set = misda.discover(Y) +mis_set.evaluate(...) +ranking = misda.rank(mis_set, policy=...) +``` + +That separation remains valuable for benchmarks, validation, and expert +instrumentation. It is, however, too low-level as the canonical workflow for a +user who wants a defensible reduction recommendation. + +Two logically distinct decisions were being exposed as if they were one: + +1. which alpha/aggressiveness regime should be used for the observed `Y`; +2. which MIS should represent the chosen regime. + +The ranking-policy experiments in issues #83 and #84 further showed that these +questions should remain distinct. Structural support and threshold sensitivity +are properties of the observed-data profile. Representative selection is a +ranking problem within a selected regime. + +## Decision + +The canonical user-facing workflow is: + +```python +profile = misda.profile(Y) +profile.report() + +result = misda.discovery(profile) +result.report() +``` + +The convenience form + +```python +result = misda.discovery(Y) +``` + +is equivalent to profiling first and then discovering from the resulting +profile. + +The low-level `discover`, `evaluate`, and `rank` functions remain public and +retain their existing semantics for scientific and advanced use. + +## Profile semantics + +`profile(Y)` is a diagnostic map over the calibrated alpha/aggressiveness path. +It enumerates distinct structural regimes induced by threshold changes and +shows their consequences, including: + +- alpha/aggressiveness; +- latent and structural dimensions; +- structural/latent topology and components through the stored regime result; +- MIS universe and structural ranking; +- dimensional-support assessment and reasons; +- `alpha_onset`, `alpha_null`, and separation/null-envelope context. + +Regimes are represented at their **most aggressive boundary**. Critical +thresholds are probed on both sides and structurally equivalent consecutive +states are compressed. This lets the stored aggressiveness of a regime mean the +most aggressive point at which that same structural state still holds. + +`profile.report()` must remain observational: reporting does not trigger +additional candidate evaluation. + +## Selected regime + +`profile.selected` is the **most aggressive acceptable regime**. + +A regime is acceptable when the canonical structural selection at that regime +has assessment: + +```text +NO_REDUNDANCY +SUPPORTED_REDUCTION +``` + +A regime whose canonical structural selection is +`UNSUPPORTED_REDUCTION` is not acceptable for automatic selection. + +If no acceptable regime exists, `profile.selected` is `None` and the high-level +workflow abstains rather than silently using `aggressiveness=1`. + +Selection does not hide alternatives: all regimes remain available for +inspection in the profile. + +## Discovery semantics + +`discovery(profile)` operates only on `profile.selected` and then chooses a +representative MIS within that regime. + +The default high-level ranking policy is: + +```text +dominance_preservation +``` + +because the clean end-to-end experiments in #83 showed that it is more aligned +with downstream optimization than the structural `size_span` order when the +observed geometry is representative. Issue #84 established the epistemic +boundary: severe corruption of `Y` can mislead dominance ranking and even +support inferred from the same data. The default is therefore an +observed-data recommendation, not an unconditional noise-robustness claim. + +Users may request the structural policy explicitly: + +```python +result = misda.discovery(profile, rank_policy="size_span") +``` + +The low-level call `misda.rank(mis_set)` continues to default to `size_span`. +This preserves ADR 0017: `size_span` remains the canonical zero-cost structural +ordering. The new high-level default applies only to the recommendation layer. + +## Abstention and assessment + +If `profile.selected is None`, `discovery(profile)` returns an abstaining result +rather than inventing a reduction. + +If a selected regime exists, the ranking-selected MIS retains its +candidate-specific `ReductionAssessment`. A high-level result therefore remains +inspectable even when alternative ranking evidence exposes a candidate-specific +warning. + +## Data-quality boundary + +`profile()` diagnoses structure **conditional on the observed `Y`**. It does not +claim to estimate an external measurement-noise variance, reliability ratio, or +systematic distortion from a single matrix. + +Known data-quality information may inform how a user interprets the profile or +chooses a ranking policy. X-aware or replicate-aware diagnostics remain separate +research questions. + +## Compatibility + +- `misda.discover(Y, aggressiveness=...)` remains available. +- `MISSet.evaluate(...)` remains available. +- `misda.rank(...)` remains available and defaults to `size_span`. +- benchmark runners may continue using the low-level API where exact control of + regime, candidate scope, and evaluation cost is scientifically necessary. +- notebook and user-document migration is tracked separately after this API + contract stabilizes. + +## Research basis + +The default-policy and data-quality rationale is recorded in: + +- `docs/research-notes/2026-10-ranking-policy-optimization.md`; +- `docs/research-notes/2026-10-noisy-ranking-safety.md`; +- `docs/research-notes/2026-10-noisy-ranking-supported-stress.md`; +- `docs/research-notes/2026-10-ranking-policy-noise-scale-and-default-hypothesis.md`. diff --git a/docs/adr/README.md b/docs/adr/README.md index c9d47115..017720b1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -27,7 +27,7 @@ Each record may contain: Context, Definitions, Decision, Formal specification, R - [0008 — Canonical structural coverage ordering (superseded by ADR 0017)](0008-canonical-structural-coverage-ordering.md) - [0009 — Explicit evaluation scope](0009-explicit-evaluation-scope.md) - [0010 — Decision-stable sequential alpha-null estimation](0010-decision-stable-alpha-null.md) -- [0011 — Public API and object model](0011-public-api-and-object-model.md) +- [0011 — Public API and object model (public-flow section partially superseded by ADR 0022)](0011-public-api-and-object-model.md) - [0012 — Reproducibility and stochastic computation](0012-reproducibility-and-stochastic-computation.md) - [0013 — Benchmark and validation contract](0013-benchmark-and-validation-contract.md) - [0014 — Public diagnostics and reporting semantics](0014-public-diagnostics-and-reporting-semantics.md) @@ -35,8 +35,9 @@ Each record may contain: Context, Definitions, Decision, Formal specification, R - [0016 — Public capability non-regression contract](0016-public-capability-non-regression.md) - [0017 — Size-span canonical structural ranking](0017-size-span-canonical-ranking.md) - [0018 — Ranking-selected visualization views](0018-ranking-selected-visualization-views.md) -- [0019 — User-facing MIS, ranking, and evaluation workflow](0019-user-facing-mis-ranking-workflow.md) +- [0019 — User-facing MIS, ranking, and evaluation workflow (superseded by ADR 0022)](0019-user-facing-mis-ranking-workflow.md) - [0020 — Experimental empirical-Pareto ranking](0020-experimental-empirical-pareto-ranking.md) - [0021 — Conservative dominance-preservation reduction selection](0021-conservative-dominance-preservation-ranking.md) +- [0022 — Profile-to-discovery user workflow](0022-profile-to-discovery-user-workflow.md) -All records below are retrospective unless explicitly stated otherwise. They document the current MISDA design, with later records superseding earlier decisions where explicitly stated. +All records below are retrospective unless explicitly stated otherwise. They document the current MISDA design, with later records superseding earlier decisions where explicitly stated. \ No newline at end of file diff --git a/misda/__init__.py b/misda/__init__.py index f911f1e6..05ede8c0 100644 --- a/misda/__init__.py +++ b/misda/__init__.py @@ -3,23 +3,21 @@ """MISDA public API. -The alpha-stage public surface is intentionally small. Static analysis keeps -three responsibilities separate: +The canonical user workflow separates structural regime diagnosis from the +final representative choice:: -``discover`` -> structural inference and MIS universe -``MISSet.evaluate`` -> candidate-level evidence -``rank`` -> an ordered view whose ``mis()`` selector exposes one MIS + profile = misda.profile(Y) + result = misda.discovery(profile) -The module-level ``evaluate(mis_set, ...)`` form remains public and equivalent. -Adaptive analysis and the previous ``analyze``/``heavy`` result model are not -part of this API. +The lower-level ``discover`` / ``evaluate`` / ``rank`` primitives remain public +for scientific instrumentation and advanced use. """ from ._metadata import __version__ -# The canonical discovery implementation lives in ``api``. Correlation -# selection is injected only at the statistics boundary so Pearson and the -# experimental Spearman backend share the complete downstream pipeline. +# The canonical low-level discovery implementation lives in ``api``. +# Correlation selection is injected only at the statistics boundary so Pearson +# and the experimental Spearman backend share the complete downstream pipeline. from . import api as _api from ._correlation_backend import ( compute_correlation_statistics as _compute_correlation_statistics, @@ -53,8 +51,17 @@ ParetoMetrics, Ranking, ReductionAssessment, + StructuralMetrics, rank, ) +from ._profile import ( + ABSTAINED, + DiscoveryResult, + Profile, + ProfileRegime, + discovery as _discovery_high_level, + profile as _profile_impl, +) def discover( @@ -67,9 +74,9 @@ def discover( correlation="pearson", experimental=False, ): - """Discover the complete static structural MIS universe. + """Low-level discovery of the complete static structural MIS universe. - Pearson is the canonical MISDA correlation backend. Spearman is retained + Pearson is the canonical MISDA correlation backend. Spearman is retained for reproducible research and requires the explicit opt-in ``experimental=True``. """ @@ -82,8 +89,6 @@ def discover( name=name, cancel_requested=cancel_requested, ) - # MISSet is intentionally a mutable result container for evaluation state; - # record the discovery backend so experimental results remain auditable. result.correlation = backend result.experimental = backend != "pearson" return result @@ -93,6 +98,64 @@ def discover( # that import the implementation module directly. _api.discover = discover + +def profile( + Y, + *, + seed=123, + name=None, + cancel_requested=None, + correlation="pearson", + experimental=False, +): + """Map distinct structural regimes across the calibrated alpha path.""" + + with _correlation_backend(correlation, experimental) as backend: + result = _profile_impl( + Y, + seed=seed, + name=name, + cancel_requested=cancel_requested, + ) + result.correlation = backend + result.experimental = backend != "pearson" + for regime in result: + regime.mis_set.correlation = backend + regime.mis_set.experimental = backend != "pearson" + return result + + +def discovery( + source, + *, + rank_policy=DOMINANCE_PRESERVATION, + seed=123, + name=None, + cancel_requested=None, + correlation="pearson", + experimental=False, +): + """Return a high-level reduction decision from observed Y or a Profile. + + When ``source`` is raw Y, profiling is performed first. When it is already + a :class:`Profile`, the stored selected regime is used directly. The + high-level default is ``dominance_preservation``; low-level ``rank()`` keeps + its historical ``size_span`` default. + """ + + if isinstance(source, Profile): + return _discovery_high_level(source, rank_policy=rank_policy) + observed_profile = profile( + source, + seed=seed, + name=name, + cancel_requested=cancel_requested, + correlation=correlation, + experimental=experimental, + ) + return _discovery_high_level(observed_profile, rank_policy=rank_policy) + + from ._pareto_stability import ParetoStabilityDiagnostics, evaluate from . import _reporting as _reporting # installs the legacy-complete MISSet report from . import _front_plotting as _front_plotting # installs graph/front plot views @@ -115,6 +178,7 @@ def discover( "UNSUPPORTED_REDUCTION", "STRUCTURAL_COVERAGE", "PARTIALLY_SUPPORTED", + "ABSTAINED", "StructuralMetrics", "JackknifeMetrics", "LinearMetrics", @@ -130,6 +194,11 @@ def discover( "DiscoveryAnalysis", "MISSet", "Ranking", + "ProfileRegime", + "Profile", + "DiscoveryResult", + "profile", + "discovery", "discover", "evaluate", "rank", diff --git a/misda/_profile.py b/misda/_profile.py new file mode 100644 index 00000000..e4186d11 --- /dev/null +++ b/misda/_profile.py @@ -0,0 +1,460 @@ +# SPDX-FileCopyrightText: 2026 Monaco F. J. +# SPDX-License-Identifier: GPL-3.0-or-later + +"""High-level structural profile and discovery workflow.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +import numpy as np + +from . import api as _api +from ._graph import build_dependency_graphs +from ._statistics import interpolate_log_alpha, separation_status +from ._support import evaluate_dimensional_support_group +from ._validation import normalize_input_matrix + + +ABSTAINED = "ABSTAINED" + + +@dataclass(frozen=True) +class ProfileRegime: + """One distinct structural regime along the alpha/aggressiveness path.""" + + index: int + aggressiveness: float + alpha: float + log_alpha: float + mis_set: _api.MISSet + + @property + def analysis(self): + return self.mis_set.analysis + + @property + def ranking(self): + return self.mis_set.structural_ranking + + @property + def assessment(self): + return self.ranking.assessment + + @property + def status(self): + return self.assessment.status if self.assessment is not None else ABSTAINED + + @property + def acceptable(self): + return self.status in {_api.NO_REDUNDANCY, _api.SUPPORTED_REDUCTION} + + +class Profile: + """Diagnostic map of structural regimes inferred from one observed Y.""" + + def __init__( + self, + *, + regimes, + selected_index, + alpha_onset, + alpha_null, + separation, + seed, + name=None, + correlation="pearson", + experimental=False, + ): + self._regimes = tuple(regimes) + self.selected_index = selected_index + self.alpha_onset = alpha_onset + self.alpha_null = float(alpha_null) + self.separation_status = separation + self.seed = int(seed) + self.name = name + self.correlation = correlation + self.experimental = bool(experimental) + + def __len__(self): + return len(self._regimes) + + def __iter__(self): + return iter(self._regimes) + + def __getitem__(self, key): + return self._regimes[key] + + @property + def regimes(self): + return self._regimes + + @property + def selected(self) -> Optional[ProfileRegime]: + if self.selected_index is None: + return None + return self._regimes[self.selected_index] + + def report(self): + lines = [f"MISDA profile: {self.name or 'Untitled'}"] + onset = "None" if self.alpha_onset is None else f"{self.alpha_onset:.6g}" + lines.append( + f"Threshold path: alpha_onset={onset}; alpha_null={self.alpha_null:.6g}; " + f"separation={getattr(self.separation_status, 'value', self.separation_status)}" + ) + lines.append( + "Regimes: idx aggressiveness alpha latent structural MISs assessment" + ) + for regime in self._regimes: + marker = "*" if self.selected_index == regime.index else " " + analysis = regime.analysis + lines.append( + f"{marker} {regime.index:>3} {regime.aggressiveness:>14.6f} " + f"{regime.alpha:>10.6g} {analysis.latent_dimension:>6} " + f"{analysis.structural_dimension:>10} {len(regime.mis_set):>4} " + f"{regime.status}" + ) + if self.selected is None: + lines.append("Selected regime: none — no acceptable structural regime.") + else: + lines.append( + f"Selected regime: {self.selected.index} — most aggressive acceptable " + f"regime (aggressiveness={self.selected.aggressiveness:.6f}, " + f"alpha={self.selected.alpha:.6g})." + ) + return "\n".join(lines) + + +@dataclass(frozen=True) +class DiscoveryResult: + """High-level reduction decision derived from one selected profile regime.""" + + profile: Profile + regime: Optional[ProfileRegime] + ranking: Optional[_api.Ranking] + rank_policy: str + + @property + def mis_set(self): + return None if self.regime is None else self.regime.mis_set + + @property + def selected(self): + return None if self.ranking is None else self.ranking.selected + + @property + def assessment(self): + return None if self.ranking is None else self.ranking.assessment + + @property + def status(self): + return ABSTAINED if self.assessment is None else self.assessment.status + + @property + def analysis(self): + return None if self.regime is None else self.regime.analysis + + def mis(self): + return self.selected + + def report(self): + lines = [f"MISDA discovery: {self.profile.name or 'Untitled'}"] + if self.regime is None: + lines.append("Decision: ABSTAINED — profile found no acceptable regime.") + return "\n".join(lines) + lines.append( + f"Profile regime: {self.regime.index}; " + f"aggressiveness={self.regime.aggressiveness:.6f}; " + f"alpha={self.regime.alpha:.6g}" + ) + lines.append(f"Ranking policy: {self.rank_policy}") + objectives = ", ".join(map(str, self.selected.objectives)) if self.selected else "none" + lines.append(f"Selected MIS: {objectives}") + if self.assessment is not None: + reasons = ", ".join(self.assessment.reasons) or "none" + lines.append(f"Assessment: {self.assessment.status}; reasons={reasons}") + return "\n".join(lines) + + +def _critical_aggressiveness(correlation_statistics, alpha_onset, alpha_null): + """Return boundary probes spanning every threshold transition on the path.""" + + if alpha_onset is None: + return (1.0,) + alpha_onset = float(alpha_onset) + alpha_null = float(alpha_null) + if alpha_onset == alpha_null: + return (1.0,) + + upper = np.triu(correlation_statistics.valid_pairs, k=1) + pair_log_p = correlation_statistics.log_p[upper] + pair_alpha = np.exp(pair_log_p[np.isfinite(pair_log_p)]) + lo = min(alpha_onset, alpha_null) + hi = max(alpha_onset, alpha_null) + pair_alpha = np.unique(pair_alpha[(pair_alpha >= lo) & (pair_alpha <= hi)]) + + executed = [alpha_onset, alpha_null] + for threshold in pair_alpha: + threshold = float(threshold) + if threshold == alpha_onset or threshold == alpha_null: + continue + for direction in (-np.inf, 0.0, np.inf): + value = threshold if direction == 0.0 else float(np.nextafter(threshold, direction)) + if lo <= value <= hi: + executed.append(value) + + denominator = alpha_null - alpha_onset + values = [] + for alpha in executed: + aggressiveness = (float(alpha) - alpha_onset) / denominator + aggressiveness = min(1.0, max(0.0, float(aggressiveness))) + values.append(aggressiveness) + return tuple(sorted(set(values))) + + +def _state_signature(correlation_statistics, log_alpha): + structure = build_dependency_graphs(correlation_statistics, log_alpha) + ranked, groups = _api._rank_size_span(structure, correlation_statistics.labels) + grouped_mis = tuple( + tuple(tuple(ranked[index]["mis_indices"]) for index in group) + for group in groups + ) + return ( + structure.structural_dimension, + structure.latent_dimension, + structure.structural_components, + structure.latent_components, + grouped_mis, + ) + + +def _build_regime( + *, + normalized, + correlation_statistics, + null_estimate, + separation, + aggressiveness, + seed, + name, + support_cache, +): + if correlation_statistics.log_alpha_onset is None: + log_alpha = null_estimate.log_alpha_null + else: + log_alpha = interpolate_log_alpha( + correlation_statistics.log_alpha_onset, + null_estimate.log_alpha_null, + aggressiveness, + ) + structure = build_dependency_graphs(correlation_statistics, log_alpha) + ranked, groups = _api._rank_size_span(structure, normalized.labels) + candidates = tuple( + _api.MISCandidate( + objectives=tuple(item["mis_labels"]), + indices=tuple(item["mis_indices"]), + structural=_api.StructuralMetrics( + neighborhood=int(item["neighborhood"]), + neighborhood_ratio=float(item["neighborhood_ratio"]), + span=int(item["span"]), + avg_external_degree=float(item["avg_external_degree"]), + avg_internal_degree=float(item["avg_internal_degree"]), + ), + ) + for item in ranked + ) + + # Profiling needs support only for the canonical first structural group. + # Candidate-specific support for an alternative final ranking is evaluated + # lazily in discovery(). The null computation is cached whenever the same + # retained sets and latent dimension recur in another alpha regime. + first_group = groups[0] if groups else tuple() + selected_sets = tuple(candidates[index].indices for index in first_group) + support_key = (int(structure.latent_dimension), selected_sets) + raw_support = support_cache.get(support_key) + if raw_support is None: + raw_support = evaluate_dimensional_support_group( + normalized.data, + selected_sets, + structure.latent_dimension, + seed=seed, + ) + support_cache[support_key] = raw_support + support_results = tuple( + _api._candidate_support(raw, index) + for raw, index in zip(raw_support, first_group) + ) + support_by_index = {item.candidate_index: item for item in support_results} + + analysis = _api.DiscoveryAnalysis( + original_dimension=normalized.n_objectives, + latent_dimension=structure.latent_dimension, + structural_dimension=structure.structural_dimension, + alpha_onset=correlation_statistics.alpha_onset, + log_alpha_onset=correlation_statistics.log_alpha_onset, + alpha_null=null_estimate.alpha_null, + log_alpha_null=null_estimate.log_alpha_null, + alpha=float(np.exp(log_alpha)), + log_alpha=float(log_alpha), + aggressiveness=float(aggressiveness), + separation_status=separation, + structural_graph=structure.structural_graph, + dependence_graph=structure.dependence_graph, + structural_components=structure.structural_components, + latent_components=structure.latent_components, + alpha_null_converged=bool(null_estimate.converged), + alpha_null_reason=null_estimate.reason, + alpha_null_permutations=int(null_estimate.n_permutations), + alpha_null_se_mc=float(null_estimate.se_mc), + alpha_null_r_interval=tuple(null_estimate.r_interval), + alpha_null_log_interval=tuple(null_estimate.log_alpha_interval), + ) + result = _api.MISSet( + analysis=analysis, + candidates=candidates, + rank_groups=groups, + data=normalized.data, + labels=normalized.labels, + seed=seed, + name=name, + ) + result.support = _api.DimensionalSupport(support_results, result._candidates) + result._support_by_index = support_by_index + return result + + +def _ensure_candidate_support(mis_set, candidate_index): + """Attach candidate-specific support if profiling did not need that MIS.""" + + candidate_index = int(candidate_index) + if candidate_index in mis_set._support_by_index: + return mis_set._support_by_index[candidate_index] + candidate = mis_set[candidate_index] + raw = evaluate_dimensional_support_group( + mis_set._data, + (candidate.indices,), + mis_set.analysis.latent_dimension, + seed=mis_set.seed, + )[0] + support = _api._candidate_support(raw, candidate_index) + mis_set._support_by_index[candidate_index] = support + return support + + +def profile(Y, *, seed=123, name=None, cancel_requested=None): + """Map distinct structural regimes over the calibrated alpha path.""" + + normalized = normalize_input_matrix(Y) + correlation_statistics = _api.compute_correlation_statistics(normalized) + + def signature(log_alpha): + return _api._discovery_signature(correlation_statistics, log_alpha) + + null_estimate = _api.estimate_null_positive_correlation( + normalized, + signature=signature, + seed=seed, + cancel_requested=cancel_requested, + ) + separation = separation_status( + correlation_statistics.log_alpha_onset, + null_estimate.log_alpha_null, + ) + + points = _critical_aggressiveness( + correlation_statistics, + correlation_statistics.alpha_onset, + null_estimate.alpha_null, + ) + + compressed = [] + for aggressiveness in points: + if correlation_statistics.log_alpha_onset is None: + log_alpha = null_estimate.log_alpha_null + else: + log_alpha = interpolate_log_alpha( + correlation_statistics.log_alpha_onset, + null_estimate.log_alpha_null, + aggressiveness, + ) + current_signature = _state_signature(correlation_statistics, log_alpha) + if compressed and compressed[-1][0] == current_signature: + compressed[-1] = (current_signature, float(aggressiveness)) + else: + compressed.append((current_signature, float(aggressiveness))) + + regimes = [] + support_cache = {} + for _signature, aggressiveness in compressed: + mis_set = _build_regime( + normalized=normalized, + correlation_statistics=correlation_statistics, + null_estimate=null_estimate, + separation=separation, + aggressiveness=aggressiveness, + seed=seed, + name=name, + support_cache=support_cache, + ) + regimes.append( + ProfileRegime( + index=len(regimes), + aggressiveness=float(aggressiveness), + alpha=float(mis_set.analysis.alpha), + log_alpha=float(mis_set.analysis.log_alpha), + mis_set=mis_set, + ) + ) + + selected_index = next( + (regime.index for regime in reversed(regimes) if regime.acceptable), + None, + ) + return Profile( + regimes=regimes, + selected_index=selected_index, + alpha_onset=correlation_statistics.alpha_onset, + alpha_null=null_estimate.alpha_null, + separation=separation, + seed=seed, + name=name, + ) + + +def discovery(source, *, rank_policy=_api.DOMINANCE_PRESERVATION, **profile_kwargs): + """Return the recommended MIS from a profile or directly from observed Y.""" + + if isinstance(source, Profile): + if profile_kwargs: + unexpected = ", ".join(sorted(profile_kwargs)) + raise TypeError( + f"profile options are not accepted when source is already a Profile: {unexpected}" + ) + observed_profile = source + else: + observed_profile = profile(source, **profile_kwargs) + + regime = observed_profile.selected + if regime is None: + return DiscoveryResult( + profile=observed_profile, + regime=None, + ranking=None, + rank_policy=rank_policy, + ) + + ranking = _api.rank( + regime.mis_set, + policy=rank_policy, + candidates="all", + accept_cost=True, + ) + if ranking.indices: + _ensure_candidate_support(regime.mis_set, ranking.indices[0]) + return DiscoveryResult( + profile=observed_profile, + regime=regime, + ranking=ranking, + rank_policy=rank_policy, + ) diff --git a/tests/test_profile_discovery.py b/tests/test_profile_discovery.py new file mode 100644 index 00000000..f3a71e88 --- /dev/null +++ b/tests/test_profile_discovery.py @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: 2026 Monaco F. J. +# SPDX-License-Identifier: GPL-3.0-or-later + +import numpy as np + +import misda + + +def _two_blocks(seed=7, n=36): + rng = np.random.default_rng(seed) + x = rng.normal(size=n) + y = rng.normal(size=n) + return np.column_stack( + [ + x, + 2.0 * x + 0.01 * rng.normal(size=n), + y, + -3.0 * y + 0.01 * rng.normal(size=n), + ] + ) + + +def test_public_profile_exposes_ordered_regimes_and_selected_boundary(): + observed = misda.profile(_two_blocks(), seed=11, name="two blocks") + + assert isinstance(observed, misda.Profile) + assert len(observed) >= 1 + aggressiveness = [regime.aggressiveness for regime in observed] + assert aggressiveness == sorted(aggressiveness) + assert len(set(aggressiveness)) == len(aggressiveness) + + acceptable = [regime for regime in observed if regime.acceptable] + if acceptable: + assert observed.selected is acceptable[-1] + assert observed.selected.aggressiveness == max( + regime.aggressiveness for regime in acceptable + ) + else: + assert observed.selected is None + + text = observed.report() + assert "alpha_onset=" in text + assert "alpha_null=" in text + assert "Selected regime:" in text + + +def test_profile_report_is_side_effect_free_for_candidate_evidence(): + observed = misda.profile(_two_blocks(), seed=13) + before = [ + tuple(candidate.dominance for candidate in regime.mis_set) + for regime in observed + ] + + observed.report() + + after = [ + tuple(candidate.dominance for candidate in regime.mis_set) + for regime in observed + ] + assert after == before + assert all(value is None for row in after for value in row) + + +def test_discovery_from_profile_defaults_to_dominance_preservation(): + observed = misda.profile(_two_blocks(), seed=17) + result = misda.discovery(observed) + + assert isinstance(result, misda.DiscoveryResult) + if observed.selected is None: + assert result.status == misda.ABSTAINED + assert result.selected is None + else: + assert result.regime is observed.selected + assert result.rank_policy == misda.DOMINANCE_PRESERVATION + assert result.ranking.policy == misda.DOMINANCE_PRESERVATION + assert result.selected is result.ranking.selected + assert all(candidate.dominance is not None for candidate in result.mis_set) + + +def test_discovery_y_is_equivalent_to_profile_then_discovery(): + data = _two_blocks(seed=19) + direct = misda.discovery(data, seed=23) + staged_profile = misda.profile(data, seed=23) + staged = misda.discovery(staged_profile) + + assert direct.status == staged.status + assert direct.rank_policy == staged.rank_policy + if direct.selected is None: + assert staged.selected is None + else: + assert direct.selected.indices == staged.selected.indices + assert direct.regime.analysis.structural_dimension == staged.regime.analysis.structural_dimension + assert direct.regime.aggressiveness == staged.regime.aggressiveness + + +def test_size_span_remains_available_and_low_level_default_is_unchanged(): + observed = misda.profile(_two_blocks(seed=29), seed=31) + if observed.selected is None: + return + + high_level = misda.discovery(observed, rank_policy=misda.SIZE_SPAN) + low_level = misda.rank(observed.selected.mis_set) + + assert high_level.rank_policy == misda.SIZE_SPAN + assert high_level.ranking.policy == misda.SIZE_SPAN + assert high_level.selected.indices == low_level.selected.indices + assert low_level.policy == misda.SIZE_SPAN + + +def test_discovery_abstains_when_profile_has_no_selected_regime(): + base = misda.profile(_two_blocks(seed=37), seed=41) + abstaining = misda.Profile( + regimes=base.regimes, + selected_index=None, + alpha_onset=base.alpha_onset, + alpha_null=base.alpha_null, + separation=base.separation_status, + seed=base.seed, + name="forced abstention contract", + correlation=base.correlation, + experimental=base.experimental, + ) + + result = misda.discovery(abstaining) + + assert result.status == misda.ABSTAINED + assert result.regime is None + assert result.ranking is None + assert result.selected is None + assert "ABSTAINED" in result.report()