diff --git a/backend/app/models/schemas.py b/backend/app/models/schemas.py index d4d6159..2378609 100644 --- a/backend/app/models/schemas.py +++ b/backend/app/models/schemas.py @@ -2,7 +2,7 @@ from __future__ import annotations from typing import Any, Optional, List, Dict -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, model_validator from enum import Enum @@ -106,6 +106,8 @@ class BeamParams(BaseModel): k_stop: int = Field(100, ge=1, le=100000) best_models_criterion: float = 10.0 max_nb_of_models: int = Field(10000, ge=1, le=10000000) + # OR (clause) languages only: maximum number of features per clause (0 = unlimited) + max_clause_size: int = Field(3, ge=0, le=100000) class McmcParams(BaseModel): @@ -257,6 +259,22 @@ class GpuParams(BaseModel): max_buffer_size_mb: int = Field(128, ge=1, le=1048576) +# OR (clause) languages of gpredomics: accepted spellings, and the one that is +# reserved but not implemented by the engine. +OR_LANGUAGE_ALIASES = frozenset({ + "bin-or", "bin_or", "binary-or", "binary_or", "0-or", + "ter-or", "ter_or", "ternary-or", "ternary_or", "1-or", + "ratio-or", "ratio_or", "3-or", +}) +RESERVED_LANGUAGE_ALIASES = frozenset({"pow2-or", "pow2_or", "2-or"}) + + +def or_languages_in(language: str) -> list[str]: + """The OR languages named in a comma-separated ``general.language`` value.""" + return [v.strip().lower() for v in str(language or "").split(",") + if v.strip().lower() in OR_LANGUAGE_ALIASES] + + class RunConfig(BaseModel): """Full configuration for a gpredomics run.""" general: GeneralParams = GeneralParams() @@ -282,6 +300,24 @@ class RunConfig(BaseModel): voting: VotingParams = VotingParams() gpu: GpuParams = GpuParams() + @model_validator(mode="after") + def _or_languages_need_beam(self): + """The engine only grows clause models with Beam; refuse the rest up front.""" + picked = [v.strip().lower() for v in str(self.general.language or "").split(",") if v.strip()] + reserved = [v for v in picked if v in RESERVED_LANGUAGE_ALIASES] + if reserved: + raise ValueError( + f"Language '{reserved[0]}' (Pow2-OR) is reserved but not implemented by the engine." + ) + algo = self.general.algo.value if hasattr(self.general.algo, "value") else str(self.general.algo) + or_langs = or_languages_in(self.general.language) + if or_langs and algo != "beam": + raise ValueError( + f"OR languages ({', '.join(or_langs)}) are only available with the Beam algorithm " + f"(general.algo = beam), not with '{algo}'." + ) + return self + # --------------------------------------------------------------------------- # Response schemas @@ -299,6 +335,7 @@ class IndividualResponse(BaseModel): data_type: str epoch: int features: dict[int, int] # feature_index -> coefficient sign + clauses: Optional[List[List[int]]] = None # OR languages: feature indices per clause class PopulationResponse(BaseModel): diff --git a/backend/app/routers/export.py b/backend/app/routers/export.py index 7150c53..23e79d9 100644 --- a/backend/app/routers/export.py +++ b/backend/app/routers/export.py @@ -17,6 +17,7 @@ from ..core.deps import get_current_user, get_project_access from ..models.db_models import User, Job from ..services import results_io +from ..services.model_format import format_model_formula, model_terms router = APIRouter(prefix="/export", tags=["export"]) @@ -63,14 +64,14 @@ async def export_csv( writer.writerow(["Metric", "Value"]) for key in ["auc", "fit", "accuracy", "sensitivity", "specificity", "threshold", "language", "data_type", "k", "epoch"]: writer.writerow([key, best.get(key, "")]) + writer.writerow(["formula", format_model_formula(best, feature_names)]) writer.writerow([]) - writer.writerow(["Feature", "Coefficient"]) - features = best.get("features", {}) - for idx_str, coef in sorted(features.items(), key=lambda x: int(x[0])): - idx = int(idx_str) - name = feature_names[idx] if idx < len(feature_names) else f"feature_{idx}" - writer.writerow([name, coef]) + # OR (clause) languages: the "Clause" column groups the features of one clause + writer.writerow(["Feature", "Coefficient", "Clause"]) + for n, term in enumerate(model_terms(best, feature_names), 1): + for name in term["features"]: + writer.writerow([name, term["coef"], n]) filename = f"best_model_{job_id[:8]}.csv" @@ -79,7 +80,7 @@ async def export_csv( if not pop: raise HTTPException(status_code=404, detail="No population data") - writer.writerow(["Rank", "AUC", "Fit", "Accuracy", "Sensitivity", "Specificity", "Threshold", "Language", "Data Type", "k", "Epoch", "Features"]) + writer.writerow(["Rank", "AUC", "Fit", "Accuracy", "Sensitivity", "Specificity", "Threshold", "Language", "Data Type", "k", "Epoch", "Features", "Formula"]) for ind in pop: m = ind.get("metrics", {}) # Build feature string @@ -92,6 +93,7 @@ async def export_csv( m.get("threshold", ""), m.get("language", ""), m.get("data_type", ""), m.get("k", ""), m.get("epoch", ""), feat_str, + format_model_formula(ind, feature_names), ]) filename = f"population_{job_id[:8]}.csv" @@ -177,13 +179,22 @@ async def export_report( pop_top = [] for ind in pop[:20]: m = ind.get("metrics", {}) - named = ind.get("named_features", {}) + if ind.get("named_clauses"): + # OR (clause) languages: one entry per clause, "(A ∨ B)(+)" + feat_str = ", ".join( + (f"({' ∨ '.join(t['features'])})" if len(t["features"]) > 1 else t["features"][0]) + + f"({'+' if t['coef'] > 0 else '-'})" + for t in model_terms(ind, feature_names) + ) + else: + named = ind.get("named_features", {}) + feat_str = ", ".join(f"{n}({'+'if c>0 else '-'})" for n, c in sorted(named.items())) pop_top.append({ "rank": ind.get("rank", 0), "auc": m.get("auc"), "fit": m.get("fit"), "accuracy": m.get("accuracy"), "k": m.get("k"), "language": m.get("language"), "data_type": m.get("data_type"), - "features": ", ".join(f"{n}({'+'if c>0 else '-'})" for n, c in sorted(named.items())), + "features": feat_str, }) # Format execution time @@ -332,16 +343,19 @@ def _build_report_html(*, job_id, job_name, best, best_features, results, Uses string concatenation to avoid f-string nesting issues with JavaScript. """ - # Feature chips + # Feature chips: one per term (a clause groups several features for the OR languages) chips = [] - for f in best_features: - cls = "positive" if f["coef"] > 0 else "negative" - sign = "+" if f["coef"] > 0 else "" + for term in model_terms(best, feature_names): + cls = "positive" if term["coef"] > 0 else "negative" + sign = "+" if term["coef"] > 0 else "" chips.append( '' - + _esc(f["name"]) + " (" + sign + str(f["coef"]) + ")" + + _esc(" ∨ ".join(term["features"])) + " (" + sign + str(term["coef"]) + ")" ) chips_html = "".join(chips) + formula = format_model_formula(best, feature_names, with_threshold=True) + if formula: + chips_html += '

' + _esc(formula) + "

" # Population rows pop_rows = "" diff --git a/backend/app/services/engine.py b/backend/app/services/engine.py index 8d9d9a2..fcb236e 100644 --- a/backend/app/services/engine.py +++ b/backend/app/services/engine.py @@ -440,6 +440,7 @@ def _merge(section_key, defaults): beam_cfg = _merge("beam", { "method": "LimitedExhaustive", "k_start": 1, "k_stop": 100, "best_models_criterion": 10.0, "max_nb_of_models": 10000, + "max_clause_size": 3, }) # Rename k_start/k_stop to kmin/kmax for gpredomics YAML format beam_out = { @@ -448,6 +449,8 @@ def _merge(section_key, defaults): "kmax": beam_cfg.pop("k_stop"), "best_models_criterion": beam_cfg["best_models_criterion"], "max_nb_of_models": beam_cfg["max_nb_of_models"], + # OR (clause) languages: features per clause, 0 = unlimited + "max_clause_size": beam_cfg["max_clause_size"], } mcmc = config.get("mcmc", {}) @@ -578,6 +581,33 @@ def _mock_results() -> dict[str, Any]: "features": {}, "named_features": {f"feature_{rng.randint(0, 49)}": rng.choice([-1, 1]) for _ in range(3)}, }) + # A few OR (clause) models, so the frontend can be developed without the engine: + # each clause groups features sharing one coefficient, e.g. (A ∨ B) + C - D. + for i, (features, clauses) in enumerate([ + ({3: 1, 8: 1, 21: 1, 30: -1}, [[3, 8], [21], [30]]), + ({5: 1, 12: -1, 37: 1, 40: -1}, [[5, 37], [12, 40]]), + ({2: 1, 7: 1, 9: 1, 15: -1, 44: -1}, [[2, 7, 9], [15], [44]]), + ]): + auc_val = round(0.86 - i * 0.01, 4) + population.append({ + "rank": 20 + i, + "metrics": { + "auc": auc_val, + "fit": round(auc_val - 0.001, 4), + "accuracy": round(0.82 - i * 0.01, 4), + "sensitivity": round(0.84 - i * 0.01, 4), + "specificity": round(0.80 - i * 0.01, 4), + "k": len(features), + "language": "ternary-or", + "data_type": "prev", + }, + "features": {str(k): v for k, v in features.items()}, + "named_features": {f"feature_{k}": v for k, v in features.items()}, + "clauses": clauses, + "named_clauses": [ + {"coef": features[c[0]], "features": [f"feature_{k}" for k in c]} for c in clauses + ], + }) return { "mock": True, diff --git a/backend/app/services/model_format.py b/backend/app/services/model_format.py new file mode 100644 index 0000000..2194e7f --- /dev/null +++ b/backend/app/services/model_format.py @@ -0,0 +1,135 @@ +"""Human-readable form of a BTR model, shared by the exports (CSV, HTML, PDF). + +A model is a dict as stored in ``results.json``: ``named_features`` (name -> +coefficient) or ``features`` (index -> coefficient) plus ``language`` and +``data_type`` (either at the top level, as in ``best_individual``, or under +``metrics``, as in ``population``). OR-language models also carry +``named_clauses`` ([{"coef": c, "features": [names]}]) or ``clauses`` +([[index, ...]]); each clause is one term of the formula, written ``(A ∨ B)``. + +The spelling follows the engine's ``Individual::display``: terms are ordered by +feature index when it is known, a prevalence model marks its features with a +``⁰``, a log model wraps them in ``ln(...)``, Pow2 coefficients are written +``2*A`` and the Ratio languages read ``(pos) / (neg + ε)``. +""" + +from __future__ import annotations + +from typing import Any, Iterable + +OR_SYMBOL = " ∨ " # " ∨ " + + +def _metric(model: dict, key: str, default=None): + if key in model and model[key] is not None: + return model[key] + return (model.get("metrics") or {}).get(key, default) + + +def _language_family(language) -> str: + """'binary', 'ternary', 'pow2' or 'ratio', for a language name or alias (OR variants included).""" + key = str(language or "").strip().lower() + for suffix in ("-or", "_or"): + if key.endswith(suffix): + key = key[: -len(suffix)] + return { + "bin": "binary", "binary": "binary", "0": "binary", + "ter": "ternary", "ternary": "ternary", "1": "ternary", + "pow2": "pow2", "2": "pow2", + "ratio": "ratio", "3": "ratio", + }.get(key, "ternary") + + +def model_terms(model: dict, feature_names: list[str] | None = None) -> list[dict[str, Any]]: + """The terms of a model: ``[{"features": [name, ...], "coef": int}, ...]``. + + One term per clause for an OR model, one per feature otherwise. Terms are + ordered by feature index when ``features`` (index -> coefficient) is + available, else by name. + """ + feature_names = feature_names or [] + + def name_of(idx) -> str: + idx = int(idx) + return str(feature_names[idx]) if idx < len(feature_names) else f"feature_{idx}" + + named_clauses = model.get("named_clauses") + if named_clauses: + return [ + {"features": [str(n) for n in c.get("features", [])], "coef": int(c.get("coef", 0))} + for c in named_clauses + if c.get("features") + ] + + features = model.get("features") or {} + clauses = model.get("clauses") + if clauses and features: + coef_of = {int(i): int(c) for i, c in features.items()} + return [ + {"features": [name_of(i) for i in clause], "coef": coef_of.get(int(clause[0]), 0)} + for clause in clauses + if clause + ] + + if features: + items = sorted(((int(i), int(c)) for i, c in features.items()), key=lambda p: p[0]) + return [{"features": [name_of(i)], "coef": c} for i, c in items] + + named = model.get("named_features") or {} + return [{"features": [str(n)], "coef": int(c)} for n, c in sorted(named.items())] + + +def _term_text(term: dict, data_type: str) -> str: + names: Iterable[str] = term["features"] + if data_type in ("prev", "prevalence"): + names = [f"{n}⁰" for n in names] + elif data_type == "log": + names = [f"ln({n})" for n in names] + names = list(names) + if len(names) == 1: + return names[0] + return "(" + OR_SYMBOL.join(names) + ")" + + +def format_model_formula(model: dict, feature_names: list[str] | None = None, + with_threshold: bool = False) -> str: + """Formula of a model, e.g. ``((A ∨ B) + C) - (D ∨ E)`` or ``(A + B) / (C + ε)``. + + ``with_threshold`` appends ``≥ threshold`` when the model has one. + """ + terms = model_terms(model, feature_names) + if not terms: + return "" + family = _language_family(_metric(model, "language")) + data_type = str(_metric(model, "data_type", "raw") or "raw").strip().lower() + + positive, negative = [], [] + for term in terms: + coef = term["coef"] + if coef == 0: + continue + text = _term_text(term, data_type) + if family == "pow2" and abs(coef) != 1: + text = f"{abs(coef)}*{text}" + (positive if coef > 0 else negative).append(text) + + # A side with several terms is parenthesised; a lone term (a feature or a + # clause, which has its own parentheses) is not. + def side(parts: list[str]) -> str: + return parts[0] if len(parts) == 1 else "(" + " + ".join(parts) + ")" + + pos = side(positive) if positive else "0" + if family == "ratio": + formula = f"{pos} / {side(negative + ['ε'])}" + elif negative: + formula = f"{pos} - {side(negative)}" + else: + formula = " + ".join(positive) if positive else "0" + + threshold = _metric(model, "threshold") + if with_threshold and threshold is not None: + try: + formula = f"{formula} ≥ {float(threshold):.4g}" + except (TypeError, ValueError): + pass + return formula diff --git a/backend/app/services/pdf_report.py b/backend/app/services/pdf_report.py index 25507bf..a6c643d 100644 --- a/backend/app/services/pdf_report.py +++ b/backend/app/services/pdf_report.py @@ -5,6 +5,8 @@ import io from datetime import datetime +from .model_format import format_model_formula, model_terms + from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle @@ -115,20 +117,23 @@ def generate_pdf( f"{best.get('language', '?')} encoding.", styles["Normal"], )) + formula = _pdf_formula(best, feature_names) + if formula: + story.append(Paragraph(f"Formula: {_esc(formula)}", styles["Normal"])) story.append(Spacer(1, 6)) - features = best.get("features", {}) - feat_rows = [["#", "Feature", "Coefficient", "Direction"]] - for i, (idx_str, coef) in enumerate( - sorted(features.items(), key=lambda x: int(x[0])), 1 - ): - idx = int(idx_str) - name = feature_names[idx] if idx < len(feature_names) else f"feature_{idx}" - coef_val = int(coef) - direction = "Positive" if coef_val > 0 else "Negative" - feat_rows.append([str(i), _esc(name), str(coef_val), direction]) - - ft = Table(feat_rows, colWidths=[10 * mm, 70 * mm, 25 * mm, 25 * mm]) + # One row per feature; the "Clause" column groups the features of an OR + # (clause) model, and simply numbers the features of a classic model. + feat_rows = [["#", "Feature", "Coefficient", "Direction", "Clause"]] + i = 0 + for n, term in enumerate(model_terms(best, feature_names), 1): + for name in term["features"]: + i += 1 + coef_val = int(term["coef"]) + direction = "Positive" if coef_val > 0 else "Negative" + feat_rows.append([str(i), _esc(name), str(coef_val), direction, str(n)]) + + ft = Table(feat_rows, colWidths=[10 * mm, 60 * mm, 25 * mm, 25 * mm, 15 * mm]) ft.setStyle(_table_style(highlight_direction=True)) story.append(ft) @@ -203,6 +208,14 @@ def generate_pdf( # Helpers # --------------------------------------------------------------------------- + +def _pdf_formula(best: dict, feature_names: list) -> str: + """Model formula in plain ASCII: the standard PDF fonts lack the OR sign and superscripts.""" + formula = format_model_formula(best, feature_names, with_threshold=True) + return (formula.replace(" \u2228 ", " OR ").replace("\u2070", "") + .replace("\u03b5", "eps").replace(" \u2265 ", " >= ")) + + def _esc(s: str) -> str: """Escape XML entities for reportlab Paragraphs.""" return (s or "").replace("&", "&").replace("<", "<").replace(">", ">") diff --git a/backend/app/services/prediction.py b/backend/app/services/prediction.py index a1be403..eb779ea 100644 --- a/backend/app/services/prediction.py +++ b/backend/app/services/prediction.py @@ -25,7 +25,16 @@ "ter": "ternary", "ternary": "ternary", "pow2": "pow2", "ratio": "ratio", + # OR (clause) languages: each term is a disjunctive clause scored by the max + # of its features (gpredomics codes 4, 5 and 7; 6 = pow2-or is not implemented) + "bin-or": "binary-or", "bin_or": "binary-or", "binary-or": "binary-or", "binary_or": "binary-or", + "0-or": "binary-or", + "ter-or": "ternary-or", "ter_or": "ternary-or", "ternary-or": "ternary-or", "ternary_or": "ternary-or", + "1-or": "ternary-or", + "ratio-or": "ratio-or", "ratio_or": "ratio-or", "3-or": "ratio-or", } +_BASE_LANGUAGE = {"binary-or": "binary", "ternary-or": "ternary", "ratio-or": "ratio"} +OR_LANGUAGES = frozenset(_BASE_LANGUAGE) _DATA_TYPES = { "raw": "raw", "prev": "prevalence", "prevalence": "prevalence", @@ -45,11 +54,42 @@ def normalize_language(language) -> str: if key not in _LANGUAGES: raise UnsupportedModelError( f"Models of type '{language}' cannot be scored on new data " - "(supported model languages: binary, ternary, pow2, ratio)." + "(supported model languages: binary, ternary, pow2, ratio and their " + "OR variants binary-or, ternary-or, ratio-or)." ) return _LANGUAGES[key] +def is_or_language(language) -> bool: + """True for the clause languages (binary-or, ternary-or, ratio-or), accepting aliases.""" + try: + return normalize_language(language) in OR_LANGUAGES + except UnsupportedModelError: + return False + + +def base_language(language: str) -> str: + """The arithmetic language an OR language is built on (``ternary-or`` -> ``ternary``).""" + lang = normalize_language(language) + return _BASE_LANGUAGE.get(lang, lang) + + +def clause_columns(clauses, feature_indices) -> list[list[int]]: + """Translate clauses given as feature indices into positions of ``feature_indices``. + + ``feature_indices`` is the ordered list of model feature indices (one per + column of the scored matrix). Features missing from it are dropped; an empty + clause is dropped too. + """ + pos = {int(idx): j for j, idx in enumerate(feature_indices)} + out = [] + for clause in clauses or []: + cols = [pos[int(f)] for f in clause if int(f) in pos] + if cols: + out.append(cols) + return out + + def normalize_data_type(data_type) -> str: key = str(data_type or "raw").strip().lower() if key not in _DATA_TYPES: @@ -102,6 +142,7 @@ def score_matrix( epsilon: float = DEFAULT_EPSILON, means=None, stds=None, + clauses=None, ) -> np.ndarray: """Score samples exactly as ``Individual::evaluate`` does. @@ -114,8 +155,15 @@ def score_matrix( Model coefficients (+-1 for binary/ternary/ratio, +-powers of two for pow2). means, stds : arrays (k,), required for ``zscore`` models Training-set statistics of each feature (see :func:`zscore_stats`). + clauses : list of lists of column positions, for the OR languages + Each clause is scored by the max of its transformed features and carries + the coefficient of its features (one per clause). Without clauses, an OR + model is scored as its base language (every feature is its own clause). """ lang = normalize_language(language) + or_model = lang in OR_LANGUAGES + if or_model: + lang = _BASE_LANGUAGE[lang] dtype = normalize_data_type(data_type) x = np.nan_to_num(np.asarray(x, dtype=float), nan=0.0) if x.ndim != 2: @@ -143,6 +191,28 @@ def score_matrix( ) t = (x - np.asarray(means, dtype=float)) / np.asarray(stds, dtype=float) + if or_model and clauses: + # Mirrors Individual::evaluate_or_with: per clause the max of the transformed + # values, weighted by |coef|, summed into positive and negative parts. + positive = np.zeros(x.shape[0]) + negative = np.zeros(x.shape[0]) + for clause in clauses: + cols = [int(c) for c in clause] + if not cols: + continue + coef = coefs[cols[0]] + if coef == 0: + continue + v = t[:, cols].max(axis=1) * abs(coef) + if coef > 0: + positive += v + else: + negative += v + if lang == "ratio": + with np.errstate(divide="ignore", invalid="ignore"): + return positive / (negative + eps) + return positive - negative + if lang == "ratio": pos = coefs > 0 if dtype == "log": @@ -223,6 +293,7 @@ def predict_from_model( if not features: raise UnsupportedModelError("The job has no model features to apply.") language = normalize_language(best.get("language")) + clauses = best.get("clauses") if language in OR_LANGUAGES else None data_type = normalize_data_type(best.get("data_type", "raw")) threshold = float(best.get("threshold", 0.0)) epsilon = float(results.get("epsilon") or DEFAULT_EPSILON) @@ -249,7 +320,8 @@ def predict_from_model( except (KeyError, IndexError, TypeError, ValueError): means = stds = None # score_matrix raises the explanatory error - scores = score_matrix(x, coefs, language, data_type, epsilon, means, stds) + cols = clause_columns(clauses, sorted(int(i) for i in features)) if clauses else None + scores = score_matrix(x, coefs, language, data_type, epsilon, means, stds, clauses=cols) predicted = (scores >= threshold).astype(int) sample_names = [str(s) for s in x_data.index] diff --git a/backend/app/services/worker.py b/backend/app/services/worker.py index b6f149d..781c0e3 100644 --- a/backend/app/services/worker.py +++ b/backend/app/services/worker.py @@ -11,6 +11,7 @@ from .prediction import ( DEFAULT_EPSILON, UnsupportedModelError, + clause_columns, compute_auc, score_matrix, zscore_stats, @@ -155,6 +156,31 @@ def _prepare_test_context(experiment, param_path, zstats=None): return None +def _model_clauses(ind): + """Clause structure of an engine Individual (OR languages), or None. + + Older bindings have no ``get_clauses``; their models are all classic. + """ + getter = getattr(ind, "get_clauses", None) + if getter is None: + return None + clauses = getter() + if not clauses: + return None + return [[int(f) for f in clause] for clause in clauses] + + +def _named_clauses(clauses, features, feature_names): + """``[{"coef": c, "features": [name, ...]}, ...]`` for the results JSON.""" + out = [] + for clause in clauses: + names = [feature_names[f] for f in clause if f < len(feature_names)] + if not names: + continue + out.append({"coef": int(features.get(clause[0], 0)), "features": names}) + return out + + def _score_individual(ind, ctx): """Score one engine Individual on the test context (same maths as the engine).""" metrics = dict(ind.get_metrics()) @@ -162,6 +188,8 @@ def _score_individual(ind, ctx): idx = sorted(int(i) for i in features.keys()) idx = [i for i in idx if i < len(ctx["feature_names"])] coefs = np.array([float(features[i]) for i in idx]) + clauses = _model_clauses(ind) + cols = clause_columns(clauses, idx) if clauses else None means = stds = None if str(metrics.get("data_type")) == "zscore": try: @@ -172,7 +200,7 @@ def _score_individual(ind, ctx): means = stds = None return score_matrix( ctx["x"][:, idx], coefs, metrics.get("language"), metrics.get("data_type", "raw"), - ctx["epsilon"], means, stds, + ctx["epsilon"], means, stds, clauses=cols, ) @@ -471,6 +499,29 @@ def _run_sklearn_worker(param_yaml: dict, results_path: str): print(f"[worker] Results saved to {results_path}", flush=True) +NO_MODEL_MESSAGE = ( + "The engine produced no model.\n" + "Beam search stops when a level has no valid model, typically when few features pass the " + "feature selection (the k=1 level is then too small for the best models criterion) or when " + "every candidate has the same sign and the language requires both signs.\n" + "Try: relax the feature selection (feature_maximal_adj_pvalue, " + "feature_minimal_prevalence_pct), raise beam.best_models_criterion, add the bin language, " + "or run the GA instead." +) + + +def _require_models(best_pop) -> None: + """Stop the worker with a readable message when the engine returned an empty population. + + The job runner shows the tail of the console log as the job's error, so the + message is printed last and the process exits with a non-zero code. + """ + if len(best_pop) > 0: + return + print(f"[error] {NO_MODEL_MESSAGE}", flush=True) + sys.exit(1) + + def main(): import time as _time param_path = sys.argv[1] @@ -512,6 +563,7 @@ def main(): # Extract results t_extract = _time.monotonic() best_pop = experiment.best_population() + _require_models(best_pop) best = best_pop.best() metrics = dict(best.get_metrics()) feature_names = experiment.feature_names() @@ -527,12 +579,21 @@ def main(): for idx, coef in ind_features.items() if int(idx) < len(feature_names) } - population_data.append({ + entry = { "rank": i, "metrics": ind_metrics, "features": {str(k): int(v) for k, v in ind_features.items()}, "named_features": named_features, - }) + } + # OR (clause) languages: the terms of the model are clauses of features + # sharing one coefficient; classic models carry no clause keys. + ind_clauses = _model_clauses(ind) + if ind_clauses is not None: + entry["clauses"] = ind_clauses + entry["named_clauses"] = _named_clauses( + ind_clauses, {int(k): int(v) for k, v in ind_features.items()}, feature_names + ) + population_data.append(entry) extract_dur = _time.monotonic() - t_extract print(f"[worker] Population extracted: {len(population_data)} models. ({extract_dur:.1f}s)", flush=True) timing.append({"label": "Population extraction", "duration_s": round(extract_dur, 2)}) @@ -629,6 +690,7 @@ def main(): "data_type": metrics["data_type"], "epoch": metrics["epoch"], "features": best.get_features(), + "clauses": _model_clauses(best), }, "population_size": len(best_pop), "population": population_data, diff --git a/backend/tests/test_or_languages.py b/backend/tests/test_or_languages.py new file mode 100644 index 0000000..f4cde57 --- /dev/null +++ b/backend/tests/test_or_languages.py @@ -0,0 +1,414 @@ +"""OR (clause) languages of gpredomics in the web app. + +A clause model (binary-or, ternary-or, ratio-or) replaces each feature of a +classic BTR model by a positive disjunctive clause scored by the max of its +features. The engine produces them with Beam only. These tests cover the +scoring port, the results format, the run configuration, the mock engine and +the exports; the engine itself is tested in gpredomics. +""" + +from __future__ import annotations + +import csv +import io + +import numpy as np +import pandas as pd +import pytest +import yaml +from pydantic import ValidationError + +from app.models.schemas import RunConfig, or_languages_in +# Shared API fixtures live in test_api.py (importing them registers them here). +from tests.test_api import auth_client, clean_data, client, db_session # noqa: F401 +from app.services import engine as ml_engine +from app.services import worker +from app.services.model_format import format_model_formula, model_terms +from app.services.prediction import ( + UnsupportedModelError, + base_language, + clause_columns, + is_or_language, + normalize_language, + predict_from_model, + score_matrix, +) + + +# --------------------------------------------------------------------------- +# Language names +# --------------------------------------------------------------------------- + +class TestLanguageNames: + @pytest.mark.parametrize("alias,expected", [ + ("ter-or", "ternary-or"), ("Ternary-OR", "ternary-or"), ("1-or", "ternary-or"), + ("bin-or", "binary-or"), ("binary_or", "binary-or"), + ("ratio-or", "ratio-or"), ("3-or", "ratio-or"), + ]) + def test_aliases(self, alias, expected): + assert normalize_language(alias) == expected + assert is_or_language(alias) + assert base_language(alias) == expected.replace("-or", "") + + def test_classic_languages_are_not_or(self): + for lang in ("bin", "ternary", "pow2", "ratio"): + assert not is_or_language(lang) + assert base_language(lang) == normalize_language(lang) + + def test_pow2_or_is_not_scorable(self): + with pytest.raises(UnsupportedModelError): + normalize_language("pow2-or") + assert not is_or_language("pow2-or") + + def test_or_languages_in_config_value(self): + assert or_languages_in("bin, ter-or ,ratio-or") == ["ter-or", "ratio-or"] + assert or_languages_in("bin,ter,ratio") == [] + assert or_languages_in(None) == [] + + +# --------------------------------------------------------------------------- +# Scoring (mirrors Individual::evaluate_or_with) +# --------------------------------------------------------------------------- + +class TestClauseScoring: + # columns: a, b, c, d + X = np.array([ + [0.0, 0.5, 0.2, 0.0], + [0.3, 0.0, 0.0, 0.7], + [0.9, 0.8, 0.1, 0.1], + [0.0, 0.0, 0.0, 0.0], + ]) + + def test_ternary_or_raw_is_max_per_clause(self): + # (a ∨ b) + c - d + s = score_matrix(self.X, [1, 1, 1, -1], "ternary-or", "raw", clauses=[[0, 1], [2], [3]]) + expected = np.maximum(self.X[:, 0], self.X[:, 1]) + self.X[:, 2] - self.X[:, 3] + np.testing.assert_allclose(s, expected) + + def test_prevalence_is_boolean_or(self): + # (a ∨ b)⁰ - (c ∨ d)⁰ with epsilon 1e-5 + s = score_matrix(self.X, [1, 1, -1, -1], "ter-or", "prev", clauses=[[0, 1], [2, 3]]) + assert s.tolist() == [1.0 - 1.0, 1.0 - 1.0, 1.0 - 1.0, 0.0] + + def test_binary_or_counts_true_clauses(self): + s = score_matrix(self.X[:, :3], [1, 1, 1], "bin-or", "prev", clauses=[[0, 1], [2]]) + assert s.tolist() == [2.0, 1.0, 2.0, 0.0] + + def test_ratio_or(self): + eps = 1e-5 + s = score_matrix(self.X, [1, 1, -1, -1], "ratio-or", "raw", epsilon=eps, clauses=[[0, 1], [2, 3]]) + num = np.maximum(self.X[:, 0], self.X[:, 1]) + den = np.maximum(self.X[:, 2], self.X[:, 3]) + np.testing.assert_allclose(s, num / (den + eps)) + + def test_log_absent_values_contribute_zero(self): + eps = 0.1 + s = score_matrix(self.X, [1, 1, -1, -1], "ternary-or", "log", epsilon=eps, clauses=[[0, 1], [2, 3]]) + t = np.where(self.X != 0, np.log(np.where(self.X != 0, self.X, 1.0) / eps), 0.0) + expected = np.maximum(t[:, 0], t[:, 1]) - np.maximum(t[:, 2], t[:, 3]) + np.testing.assert_allclose(s, expected) + + def test_singleton_clauses_equal_the_classic_model(self): + coefs = [1, -1, 1, -1] + for dtype in ("raw", "prev", "log"): + classic = score_matrix(self.X, coefs, "ternary", dtype) + singles = score_matrix(self.X, coefs, "ternary-or", dtype, clauses=[[0], [1], [2], [3]]) + none = score_matrix(self.X, coefs, "ternary-or", dtype) + np.testing.assert_allclose(singles, classic) + np.testing.assert_allclose(none, classic) + + def test_zero_coefficient_clause_is_ignored(self): + s = score_matrix(self.X, [0, 0, 1, 0], "ternary-or", "raw", clauses=[[0, 1], [2], [3]]) + np.testing.assert_allclose(s, self.X[:, 2]) + + def test_clause_columns_maps_indices_to_positions(self): + assert clause_columns([[12, 3], [40]], [3, 12, 40]) == [[1, 0], [2]] + # unknown features are dropped, empty clauses vanish + assert clause_columns([[99], [3]], [3, 12]) == [[0]] + assert clause_columns(None, [3]) == [] + + +class TestPredictFromModel: + @staticmethod + def _results(language="ternary-or", clauses=None): + return { + "feature_names": ["fa", "fb", "fc", "fd"], + "epsilon": 1e-5, + "best_individual": { + "language": language, "data_type": "raw", "threshold": 0.5, + "features": {"0": 1, "1": 1, "2": -1}, + **({"clauses": clauses} if clauses is not None else {}), + }, + } + + @staticmethod + def _x(): + # features in rows (gpredomics convention), two samples + return pd.DataFrame({"s1": [0.2, 0.9, 0.1, 5.0], "s2": [0.0, 0.0, 0.4, 5.0]}, + index=["fa", "fb", "fc", "fd"]) + + def test_scores_use_the_clauses(self): + out = predict_from_model(self._results(clauses=[[0, 1], [2]]), self._x(), features_in_rows=True) + assert out["language"] == "ternary-or" + assert out["scores"] == pytest.approx([max(0.2, 0.9) - 0.1, 0.0 - 0.4]) + assert out["predicted_classes"] == [1, 0] + + def test_without_clauses_falls_back_to_the_base_language(self): + out = predict_from_model(self._results(), self._x(), features_in_rows=True) + assert out["scores"] == pytest.approx([0.2 + 0.9 - 0.1, -0.4]) + + def test_classic_model_ignores_a_stray_clauses_key(self): + out = predict_from_model(self._results("ternary", clauses=[[0, 1], [2]]), self._x(), features_in_rows=True) + assert out["scores"] == pytest.approx([0.2 + 0.9 - 0.1, -0.4]) + + +# --------------------------------------------------------------------------- +# Worker: results format +# --------------------------------------------------------------------------- + +class _FakeIndividual: + def __init__(self, features, clauses=None, language="ternary-or", data_type="raw"): + self._features = features + self._clauses = clauses + self._metrics = {"language": language, "data_type": data_type} + + def get_features(self): + return dict(self._features) + + def get_metrics(self): + return dict(self._metrics) + + def get_clauses(self): + return self._clauses + + +class _OldIndividual: + """Bindings without get_clauses (classic models only).""" + + def __init__(self, features): + self._features = features + + def get_features(self): + return dict(self._features) + + def get_metrics(self): + return {"language": "ternary", "data_type": "raw"} + + +class TestWorkerClauses: + def test_model_clauses(self): + assert worker._model_clauses(_FakeIndividual({0: 1}, [[0]])) == [[0]] + assert worker._model_clauses(_FakeIndividual({0: 1}, None)) is None + assert worker._model_clauses(_FakeIndividual({0: 1}, [])) is None + assert worker._model_clauses(_OldIndividual({0: 1})) is None + + def test_named_clauses_carry_one_coefficient_each(self): + named = worker._named_clauses([[0, 2], [1]], {0: 1, 2: 1, 1: -1}, ["a", "b", "c"]) + assert named == [{"coef": 1, "features": ["a", "c"]}, {"coef": -1, "features": ["b"]}] + + def test_named_clauses_drop_unknown_features(self): + assert worker._named_clauses([[7], [0]], {0: 1, 7: 1}, ["a"]) == [{"coef": 1, "features": ["a"]}] + + def test_score_individual_uses_clauses(self): + ctx = { + "feature_names": ["a", "b", "c"], + "x": np.array([[0.1, 0.8, 0.3], [0.0, 0.0, 0.5]]), + "epsilon": 1e-5, "zstats": {}, + } + ind = _FakeIndividual({0: 1, 1: 1, 2: -1}, [[0, 1], [2]]) + np.testing.assert_allclose(worker._score_individual(ind, ctx), [0.8 - 0.3, -0.5]) + old = _OldIndividual({0: 1, 1: 1, 2: -1}) + np.testing.assert_allclose(worker._score_individual(old, ctx), [0.1 + 0.8 - 0.3, -0.5]) + + +# --------------------------------------------------------------------------- +# Run configuration +# --------------------------------------------------------------------------- + +class TestRunConfig: + def test_or_language_requires_beam(self): + with pytest.raises(ValidationError, match="Beam"): + RunConfig.model_validate({"general": {"algo": "ga", "language": "bin,ter-or"}}) + + def test_or_language_with_beam_is_accepted(self): + cfg = RunConfig.model_validate({"general": {"algo": "beam", "language": "ter,ter-or,ratio-or"}, + "beam": {"max_clause_size": 2}}) + assert cfg.beam.max_clause_size == 2 + + def test_pow2_or_is_refused(self): + with pytest.raises(ValidationError, match="not implemented"): + RunConfig.model_validate({"general": {"algo": "beam", "language": "pow2-or"}}) + + def test_classic_languages_unchanged(self): + RunConfig.model_validate({"general": {"algo": "ga", "language": "bin,ter,ratio"}}) + + def test_max_clause_size_default_and_bounds(self): + assert RunConfig().beam.max_clause_size == 3 + with pytest.raises(ValidationError): + RunConfig.model_validate({"beam": {"max_clause_size": -1}}) + + def test_param_yaml_carries_max_clause_size(self, tmp_path): + cfg = {"general": {"algo": "beam", "language": "ter-or"}, "beam": {"max_clause_size": 2}} + path = ml_engine.write_param_yaml(cfg, "X.tsv", "y.tsv", "", "", output_dir=str(tmp_path)) + with open(path) as f: + param = yaml.safe_load(f) + assert param["beam"]["max_clause_size"] == 2 + assert param["general"]["language"] == "ter-or" + + def test_param_yaml_default_max_clause_size(self, tmp_path): + path = ml_engine.write_param_yaml({"general": {"algo": "beam"}}, "X.tsv", "y.tsv", "", "", + output_dir=str(tmp_path)) + with open(path) as f: + assert yaml.safe_load(f)["beam"]["max_clause_size"] == 3 + + @pytest.mark.asyncio + async def test_run_endpoint_rejects_or_language_with_ga(self, auth_client): # noqa: F811 + from tests.test_api import _create_project_with_datasets + + pid, x_id, y_id = await _create_project_with_datasets(auth_client) + config = {"general": {"algo": "ga", "language": "ter-or", "data_type": "prev"}} + resp = await auth_client.post(f"/api/analysis/{pid}/run", json=config, + params={"x_file_id": x_id, "y_file_id": y_id}) + assert resp.status_code == 422 + assert "Beam" in resp.text + + +# --------------------------------------------------------------------------- +# Formula formatting +# --------------------------------------------------------------------------- + +class TestModelFormula: + def test_ternary_or_prevalence(self): + model = { + "language": "ternary-or", "data_type": "prev", "threshold": 0.0, + "named_clauses": [{"coef": 1, "features": ["A", "B"]}, {"coef": 1, "features": ["C"]}, + {"coef": -1, "features": ["D", "E"]}], + } + assert format_model_formula(model) == "((A⁰ ∨ B⁰) + C⁰) - (D⁰ ∨ E⁰)" + assert format_model_formula(model, with_threshold=True).endswith(" ≥ 0") + + def test_from_indices_and_clauses(self): + model = {"metrics": {"language": "binary-or", "data_type": "raw"}, + "features": {"3": 1, "0": 1, "7": 1}, "clauses": [[0, 3], [7]]} + assert format_model_formula(model, ["a", "b", "c", "d", "e", "f", "g", "h"]) == "(a ∨ d) + h" + + def test_ratio_or(self): + model = {"language": "ratio-or", "data_type": "raw", + "named_clauses": [{"coef": 1, "features": ["A", "B"]}, {"coef": -1, "features": ["C"]}]} + assert format_model_formula(model) == "(A ∨ B) / (C + ε)" + + def test_classic_models(self): + ter = {"language": "ternary", "data_type": "log", "features": {"1": -1, "0": 1}} + assert format_model_formula(ter, ["A", "B"]) == "ln(A) - ln(B)" + pow2 = {"language": "pow2", "data_type": "raw", "named_features": {"A": 2, "B": -4, "C": 1}} + assert format_model_formula(pow2) == "(2*A + C) - 4*B" + ratio = {"language": "ratio", "data_type": "raw", "named_features": {"A": 1, "B": -1, "C": -1}} + assert format_model_formula(ratio) == "A / (B + C + ε)" + binary = {"metrics": {"language": "binary", "data_type": "raw"}, "named_features": {"B": 1, "A": 1}} + assert format_model_formula(binary) == "A + B" + assert format_model_formula({"language": "ternary"}) == "" + + def test_terms_order_follows_feature_index(self): + model = {"features": {"10": -1, "2": 1}, "language": "ternary"} + names = [f"f{i}" for i in range(11)] + assert model_terms(model, names) == [{"features": ["f2"], "coef": 1}, {"features": ["f10"], "coef": -1}] + + +# --------------------------------------------------------------------------- +# Mock engine and exports +# --------------------------------------------------------------------------- + +class TestMockAndExports: + def test_mock_results_include_consistent_or_models(self): + mock = ml_engine._mock_results() + or_models = [m for m in mock["population"] if m.get("clauses")] + assert len(or_models) >= 1 + for m in or_models: + assert m["metrics"]["language"].endswith("-or") + flat = sorted(f for c in m["clauses"] for f in c) + assert flat == sorted(int(i) for i in m["features"]) + assert len(m["named_clauses"]) == len(m["clauses"]) + for clause, named in zip(m["clauses"], m["named_clauses"], strict=True): + assert {m["features"][str(f)] for f in clause} == {named["coef"]} + assert named["features"] == [f"feature_{f}" for f in clause] + assert mock["population_size"] == len(mock["population"]) + + @pytest.mark.asyncio + async def test_exports_show_clauses(self, auth_client, db_session): # noqa: F811 + from sqlalchemy import text + + from app.services import storage + from tests.test_api import _create_project_with_datasets, _run_mock_analysis + + pid, x_id, y_id = await _create_project_with_datasets(auth_client) + job_id = await _run_mock_analysis(auth_client, pid, x_id, y_id) + mock = ml_engine._mock_results() + mock["best_individual"].update({ + "language": "ternary-or", "data_type": "prev", + "features": {"5": 1, "12": -1, "37": 1}, "clauses": [[5, 37], [12]], + }) + storage.save_job_result(pid, job_id, mock) + await db_session.execute(text("UPDATE jobs SET status = 'completed' WHERE id = :jid"), {"jid": job_id}) + await db_session.commit() + + resp = await auth_client.get(f"/api/export/{pid}/jobs/{job_id}/csv", params={"section": "best_model"}) + assert resp.status_code == 200 + rows = list(csv.reader(io.StringIO(resp.text))) + formula = next(r for r in rows if r and r[0] == "formula")[1] + assert formula == "(feature_5⁰ ∨ feature_37⁰) - feature_12⁰" + header = rows.index(["Feature", "Coefficient", "Clause"]) + assert rows[header + 1:header + 4] == [["feature_5", "1", "1"], ["feature_37", "1", "1"], ["feature_12", "-1", "2"]] + + resp = await auth_client.get(f"/api/export/{pid}/jobs/{job_id}/csv", params={"section": "population"}) + assert resp.status_code == 200 + rows = list(csv.reader(io.StringIO(resp.text))) + assert rows[0][-1] == "Formula" + assert any("∨" in r[-1] for r in rows[1:]) + + resp = await auth_client.get(f"/api/export/{pid}/jobs/{job_id}/report") + assert resp.status_code == 200 + assert "feature_5 ∨ feature_37 (+1)" in resp.text + assert "model-formula" in resp.text + + resp = await auth_client.get(f"/api/export/{pid}/jobs/{job_id}/pdf") + assert resp.status_code == 200 + assert resp.content[:5] == b"%PDF-" + + @pytest.mark.asyncio + async def test_classic_exports_unchanged(self, auth_client, db_session): # noqa: F811 + from sqlalchemy import text + + from app.services import storage + from tests.test_api import _create_project_with_datasets, _run_mock_analysis + + pid, x_id, y_id = await _create_project_with_datasets(auth_client) + job_id = await _run_mock_analysis(auth_client, pid, x_id, y_id) + storage.save_job_result(pid, job_id, ml_engine._mock_results()) + await db_session.execute(text("UPDATE jobs SET status = 'completed' WHERE id = :jid"), {"jid": job_id}) + await db_session.commit() + + resp = await auth_client.get(f"/api/export/{pid}/jobs/{job_id}/csv", params={"section": "best_model"}) + rows = list(csv.reader(io.StringIO(resp.text))) + formula = next(r for r in rows if r and r[0] == "formula")[1] + assert formula == "(feature_5 + feature_37) - feature_12" + header = rows.index(["Feature", "Coefficient", "Clause"]) + assert [r[2] for r in rows[header + 1:header + 4]] == ["1", "2", "3"] + + +class TestEmptyPopulation: + """An engine run that yields no model must fail with an explanation, not an index error.""" + + def test_empty_best_population_stops_the_worker_with_a_message(self, capsys): + from app.services import worker + + with pytest.raises(SystemExit) as exc: + worker._require_models([]) + assert exc.value.code == 1 + out = capsys.readouterr().out + assert "The engine produced no model" in out + assert "best_models_criterion" in out + + def test_non_empty_population_passes(self): + from app.services import worker + + worker._require_models([object()]) diff --git a/docs/parameter_analysis.md b/docs/parameter_analysis.md index fc0c9c7..f0d0468 100644 --- a/docs/parameter_analysis.md +++ b/docs/parameter_analysis.md @@ -18,7 +18,7 @@ This document compares all parameters from the gpredomics engine (`param.yaml` / | General | 20 | 18 | 18 | 18 | | Data | 14 | 0 (managed by DataTab) | 7 | 7 | | GA | 17 | 17 | 17 | 17 | -| Beam | 5 | 5 | 5 | 5 | +| Beam | 6 | 6 | 6 | 6 | | MCMC | 4 | 4 | 4 | 4 | | CV | 7 | 7 | 7 | 7 | | Importance | 4 | 4 | 4 | 4 | @@ -39,7 +39,7 @@ This document compares all parameters from the gpredomics engine (`param.yaml` / | `cv` | false | Y | Y | Y | | | `thread_number` | 8 | Y | Y | Y | Default changed to 4 in web | | `gpu` | false | Y | Y | Y | | -| `language` | bin,ratio,pow2,ter | Y | Y | Y | Default: bin,ter,ratio | +| `language` | bin,ratio,pow2,ter | Y | Y | Y | Default: bin,ter,ratio. OR (clause) variants `bin-or`, `ter-or`, `ratio-or` offered with Beam only; the backend refuses them with any other algorithm | | `data_type` | raw,prev,log | Y | Y | Y | Default: raw,prev | | `epsilon` | 1e-5 | Y | Y | Y | | | `fit` | auc | Y | Y | Y | | @@ -103,7 +103,7 @@ Data parameters are **not in the Parameters tab** — they are managed by the ** | `random_sampling_epochs` | 1 | Y | Y | Y | | | `n_epochs_before_global` | — | Y | Y | Y | Not in param.yaml but in param.rs | -### Beam (5 in gpredomics, 5 in web app) — Complete +### Beam (6 in gpredomics, 6 in web app) — Complete | Parameter | gpredomics default | Frontend | Backend | Engine | Notes | |-----------|-------------------|:--------:|:-------:|:------:|-------| @@ -112,6 +112,7 @@ Data parameters are **not in the Parameters tab** — they are managed by the ** | `k_stop` (→ kmax) | 100 | Y | Y | Y | Renamed to kmax in YAML | | `best_models_criterion` | 10 | Y | Y | Y | | | `max_nb_of_models` | 20000 | Y | Y | Y | Web default: 10000 | +| `max_clause_size` | 3 | Y | Y | Y | OR (clause) languages only: features per clause, 0 = unlimited | ### MCMC (4 in gpredomics, 4 in web app) — Complete diff --git a/frontend/src/__tests__/orLanguages.test.js b/frontend/src/__tests__/orLanguages.test.js new file mode 100644 index 0000000..5072e5d --- /dev/null +++ b/frontend/src/__tests__/orLanguages.test.js @@ -0,0 +1,215 @@ +/** + * OR (clause) languages in the frontend: model terms, chips, parameter form. + */ +import { describe, it, expect, beforeEach } from 'vitest' +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import i18n from '../i18n/index.js' +import { modelTerms, termsFromIndices, termLabel, coefLabel, formatModelFormula, isOrLanguage } from '../utils/modelTerms' +import { PARAM_DEFS } from '../data/parameterDefs' +import { validateForm } from '../utils/paramValidation' + +const OR_MODEL = { + rank: 3, + metrics: { language: 'ternary-or', data_type: 'prev', auc: 0.9 }, + features: { 3: 1, 8: 1, 21: 1, 30: -1 }, + named_features: { f3: 1, f8: 1, f21: 1, f30: -1 }, + clauses: [[3, 8], [21], [30]], + named_clauses: [ + { coef: 1, features: ['f3', 'f8'] }, + { coef: 1, features: ['f21'] }, + { coef: -1, features: ['f30'] }, + ], +} +const CLASSIC = { metrics: { language: 'ternary', data_type: 'raw' }, named_features: { b: 1, a: -1, c: 1 } } + +describe('modelTerms', () => { + it('one term per clause for an OR model, in clause order', () => { + const terms = modelTerms(OR_MODEL) + expect(terms.map(t => t.names)).toEqual([['f3', 'f8'], ['f21'], ['f30']]) + expect(terms.map(t => t.coef)).toEqual([1, 1, -1]) + }) + + it('one term per feature for a classic model, negatives first then alphabetical', () => { + expect(modelTerms(CLASSIC).map(t => `${t.names[0]}:${t.coef}`)).toEqual(['a:-1', 'b:1', 'c:1']) + }) + + it('handles missing data', () => { + expect(modelTerms(null)).toEqual([]) + expect(modelTerms({})).toEqual([]) + expect(modelTerms({ named_clauses: [], named_features: { x: 1 } })).toHaveLength(1) + }) + + it('termsFromIndices groups indices by clause and resolves names', () => { + const names = Array.from({ length: 40 }, (_, i) => `f${i}`) + const terms = termsFromIndices({ 3: 1, 8: 1, 21: 1, 30: -1 }, [[3, 8], [21], [30]], names) + expect(terms.map(t => termLabel(t))).toEqual(['f3 ∨ f8', 'f21', 'f30']) + expect(terms[2].coef).toBe(-1) + const classic = termsFromIndices({ '12': -1, '2': 1 }, null, names) + expect(classic.map(t => t.names[0])).toEqual(['f2', 'f12']) + expect(termsFromIndices({ 99: 1 }, null, names)[0].names).toEqual(['feature_99']) + }) + + it('labels', () => { + expect(coefLabel(1)).toBe('+1') + expect(coefLabel(-1)).toBe('-1') + expect(coefLabel(2)).toBe('+2') + expect(termLabel({ names: ['a', 'b'] }, n => n.toUpperCase())).toBe('A ∨ B') + expect(isOrLanguage('ternary-or')).toBe(true) + expect(isOrLanguage('ternary')).toBe(false) + }) + + it('formatModelFormula', () => { + expect(formatModelFormula(OR_MODEL)).toBe('((f3⁰ ∨ f8⁰) + f21⁰) - f30⁰') + expect(formatModelFormula(CLASSIC)).toBe('(b + c) - a') + expect(formatModelFormula({ metrics: { language: 'ratio-or', data_type: 'raw' }, + named_clauses: [{ coef: 1, features: ['A', 'B'] }, { coef: -1, features: ['C'] }] })).toBe('(A ∨ B) / (C + ε)') + expect(formatModelFormula({ metrics: { language: 'pow2', data_type: 'log' }, named_features: { A: 2, B: -1 } })).toBe('2*ln(A) - ln(B)') + expect(formatModelFormula({ metrics: { language: 'binary' }, named_features: { A: 1 } })).toBe('A') + expect(formatModelFormula({ metrics: { language: 'binary-or' }, named_features: { A: 1, B: 1, C: 1 }, + named_clauses: [{ coef: 1, features: ['A', 'B'] }, { coef: 1, features: ['C'] }] })).toBe('(A ∨ B) + C') + expect(formatModelFormula({})).toBe('') + }) +}) + +describe('ModelTerms component', () => { + it('renders one chip per clause with the OR sign and the real coefficient', async () => { + const { default: ModelTerms } = await import('../components/results/ModelTerms.vue') + const wrapper = mount(ModelTerms, { props: { model: OR_MODEL, labelOf: n => n.toUpperCase() } }) + const chips = wrapper.findAll('.feature-chip') + expect(chips).toHaveLength(3) + expect(chips[0].classes()).toContain('clause') + expect(chips[0].classes()).toContain('positive') + expect(chips[0].text()).toBe('F3 ∨ F8 (+1)') + expect(chips[1].classes()).not.toContain('clause') + expect(chips[2].classes()).toContain('negative') + expect(chips[2].text()).toBe('F30 (-1)') + }) + + it('shows classic models as before', async () => { + const { default: ModelTerms } = await import('../components/results/ModelTerms.vue') + const wrapper = mount(ModelTerms, { props: { model: CLASSIC } }) + expect(wrapper.findAll('.feature-chip').map(c => c.text())).toEqual(['a (-1)', 'b (+1)', 'c (+1)']) + }) +}) + +describe('model basket keeps clauses', () => { + beforeEach(() => { + setActivePinia(createPinia()) + localStorage.clear() + }) + + it('copies named_clauses when present', async () => { + const { useModelBasket } = await import('../composables/useModelBasket') + const { basketItems, addToBasket } = useModelBasket('projOr') + addToBasket('job1', 'Job 1', OR_MODEL) + addToBasket('job1', 'Job 1', { ...CLASSIC, rank: 4 }) + expect(basketItems.value[0].named_clauses).toEqual(OR_MODEL.named_clauses) + expect(basketItems.value[0].named_clauses).not.toBe(OR_MODEL.named_clauses) + expect(basketItems.value[1]).not.toHaveProperty('named_clauses') + }) +}) + +describe('parameter form', () => { + const languageDef = PARAM_DEFS.find(p => p.category === 'general' && p.key === 'language') + const algoDef = PARAM_DEFS.find(p => p.category === 'general' && p.key === 'algo') + const clauseDef = PARAM_DEFS.find(p => p.category === 'beam' && p.key === 'max_clause_size') + + it('offers the OR languages, tied to the Beam algorithm', () => { + const or = languageDef.options.filter(o => o.value.endsWith('-or')) + expect(or.map(o => o.value)).toEqual(['bin-or', 'ter-or', 'ratio-or']) + for (const o of or) expect(o.onlyWith).toEqual({ key: 'algo', values: ['beam'], hint: 'parameters.beamOnly' }) + expect(languageDef.options.some(o => o.value === 'pow2-or')).toBe(false) + expect(clauseDef).toBeTruthy() + expect(clauseDef.defaultValue).toBe(3) + expect(clauseDef.min).toBe(0) + }) + + it('validateForm reports an OR language picked with another algorithm', () => { + const defs = [algoDef, languageDef] + const bad = validateForm({ general: { algo: 'ga', language: 'bin,ter-or' } }, defs) + expect(bad['general.language']).toEqual({ + code: 'onlyWith', params: { option: 'Ternary-OR', other: 'algo', values: 'beam' }, + }) + expect(validateForm({ general: { algo: 'beam', language: 'bin,ter-or' } }, defs)).toEqual({}) + expect(validateForm({ general: { algo: 'ga', language: 'bin,ter' } }, defs)).toEqual({}) + }) + + it('ParamField disables unavailable options and keeps a picked one clearable', async () => { + const { default: ParamField } = await import('../components/ParamField.vue') + const mountWith = form => mount(ParamField, { props: { def: languageDef, form }, global: { plugins: [i18n] } }) + const byValue = (wrapper, value) => wrapper.findAll('.checkbox-group-item')[languageDef.options.findIndex(o => o.value === value)] + + let w = mountWith({ algo: 'ga', language: 'bin' }) + expect(byValue(w, 'ter-or').classes()).toContain('unavailable') + expect(byValue(w, 'ter-or').find('input').attributes('disabled')).toBeDefined() + expect(byValue(w, 'ter-or').attributes('title')).toContain('Beam') + expect(byValue(w, 'ter').classes()).not.toContain('unavailable') + expect(byValue(w, 'ter').find('input').attributes('disabled')).toBeUndefined() + + w = mountWith({ algo: 'beam', language: 'bin' }) + expect(byValue(w, 'ter-or').classes()).not.toContain('unavailable') + expect(byValue(w, 'ter-or').find('input').attributes('disabled')).toBeUndefined() + + const form = { algo: 'ga', language: 'bin,ter-or' } + w = mountWith(form) + const item = byValue(w, 'ter-or') + expect(item.classes()).toContain('unavailable') + expect(item.find('input').attributes('disabled')).toBeUndefined() + await item.find('input').trigger('change') + expect(form.language).toBe('bin') + }) + + it('translates the new keys', () => { + const { t, te } = i18n.global + for (const key of ['params.general.language.opt.ter-or', 'params.beam.max_clause_size.label', 'paramErrors.onlyWith', 'parameters.beamOnly']) { + expect(te(key), key).toBe(true) + } + expect(t('paramErrors.onlyWith', { option: 'Ternary-OR', other: 'Algorithm', values: 'beam' })).toContain('Ternary-OR') + }) +}) + +describe('ModelFormula component (best model as a rule)', () => { + const BEST = { + k: 4, auc: 0.9, threshold: 1.5, language: 'Ternary-OR', data_type: 'prev', + features: { 3: 1, 8: 1, 21: 1, 30: -1 }, clauses: [[3, 8], [21], [30]], + } + const NAMES = Array.from({ length: 40 }, (_, i) => `f${i}`) + + it('shows positive and negative terms, the decision and the exact formula', async () => { + const { default: ModelFormula } = await import('../components/results/ModelFormula.vue') + const wrapper = mount(ModelFormula, { + global: { plugins: [i18n] }, + props: { model: BEST, featureNames: NAMES, classNameFor: c => (c === 1 ? 'Cirrhosis' : 'Healthy') }, + }) + expect(wrapper.findAll('.rule-side.positive .rule-chip').map(c => c.text())).toEqual(['f3 ∨ f8', 'f21']) + expect(wrapper.findAll('.rule-side.negative .rule-chip').map(c => c.text())).toEqual(['f30']) + expect(wrapper.find('.rule-op').text()).toBe('−') + expect(wrapper.find('.formula-text').text()).toBe('((f3⁰ ∨ f8⁰) + f21⁰) - f30⁰ ≥ 1.5') + const decision = wrapper.find('.rule-decision').text() + expect(decision).toContain('Cirrhosis') + expect(decision).toContain('score ≥ 1.5') + expect(decision).toContain('Healthy') + expect(wrapper.find('.rule-meta').text()).toBe('Ternary-OR · prev · 4 features in 3 terms') + expect(wrapper.findAll('.rule-legend li')).toHaveLength(3) + }) + + it('writes a ratio model as a fraction with ε and a binary model without a negative side', async () => { + const { default: ModelFormula } = await import('../components/results/ModelFormula.vue') + const ratio = mount(ModelFormula, { + global: { plugins: [i18n] }, + props: { model: { language: 'ratio', data_type: 'raw', threshold: 1, features: { 0: 1, 1: -1 } }, featureNames: ['a', 'b'] }, + }) + expect(ratio.find('.rule-visual').classes()).toContain('ratio') + expect(ratio.find('.rule-chip.epsilon').exists()).toBe(true) + expect(ratio.find('.formula-text').text()).toBe('a / (b + ε) ≥ 1') + + const binary = mount(ModelFormula, { + global: { plugins: [i18n] }, + props: { model: { language: 'bin', data_type: 'prev', threshold: 2, features: { 0: 1, 1: 1 } }, featureNames: ['a', 'b'], isRegression: true }, + }) + expect(binary.find('.rule-side.negative').exists()).toBe(false) + expect(binary.find('.rule-decision').exists()).toBe(false) + expect(binary.find('.formula-text').text()).toBe('a⁰ + b⁰') + }) +}) diff --git a/frontend/src/components/ParamField.vue b/frontend/src/components/ParamField.vue index a99ed8b..8616895 100644 --- a/frontend/src/components/ParamField.vue +++ b/frontend/src/components/ParamField.vue @@ -31,9 +31,16 @@ v-for="opt in def.options" :key="opt.value" class="checkbox-group-item" - :class="{ active: isChecked(opt.value) }" + :class="{ active: isChecked(opt.value), unavailable: optionUnavailable(opt) }" + :title="optionUnavailable(opt) && opt.onlyWith.hint ? $t(opt.onlyWith.hint) : undefined" > - + {{ optionLabel(def, opt) }} @@ -109,6 +116,14 @@ function toggle(value) { else cur.push(value) props.form[props.def.key] = cur.join(',') } +// An option tied to another field of the same section (`onlyWith`), e.g. the OR +// languages that only Beam Search produces. It stays clickable while checked so +// the user can clear it; validation reports it meanwhile. +function optionUnavailable(opt) { + const rule = opt.onlyWith + if (!rule) return false + return !rule.values.includes(props.form[rule.key]) +} // Number: keep '' → null (so "empty" is explicit and validated) instead of NaN, // and accept a decimal comma typed under a French locale. @@ -213,4 +228,6 @@ input[type="number"], input[type="text"], select { color: var(--text-body); } .checkbox-group-item.active { border-color: var(--info); background: var(--info-bg); color: var(--info); font-weight: 600; } +.checkbox-group-item.unavailable { opacity: 0.55; } +.checkbox-group-item.unavailable input { cursor: not-allowed; } diff --git a/frontend/src/components/results/ModelFormula.vue b/frontend/src/components/results/ModelFormula.vue new file mode 100644 index 0000000..36cebb4 --- /dev/null +++ b/frontend/src/components/results/ModelFormula.vue @@ -0,0 +1,235 @@ + + + + + diff --git a/frontend/src/components/results/ModelTerms.vue b/frontend/src/components/results/ModelTerms.vue new file mode 100644 index 0000000..dca7edf --- /dev/null +++ b/frontend/src/components/results/ModelTerms.vue @@ -0,0 +1,53 @@ + + + + + diff --git a/frontend/src/components/results/tabs/BasketTab.vue b/frontend/src/components/results/tabs/BasketTab.vue index 537a911..b773978 100644 --- a/frontend/src/components/results/tabs/BasketTab.vue +++ b/frontend/src/components/results/tabs/BasketTab.vue @@ -54,16 +54,7 @@ -
-
- {{ shortName(featureLabel(name)) }} ({{ coef > 0 ? '+' : '' }}{{ coef }}) -
-
+ @@ -103,6 +94,7 @@