Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion backend/app/models/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -106,6 +106,8 @@
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):
Expand Down Expand Up @@ -257,6 +259,22 @@
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()
Expand All @@ -282,6 +300,24 @@
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
Expand All @@ -299,6 +335,7 @@
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):
Expand Down Expand Up @@ -636,7 +673,7 @@
counts: List[int]


class DistributionsResponse(ApiModel):

Check failure on line 676 in backend/app/models/schemas.py

View workflow job for this annotation

GitHub Actions / backend-test

ruff (F811)

app/models/schemas.py:676:7: F811 Redefinition of unused `DistributionsResponse` from line 510: `DistributionsResponse` redefined here app/models/schemas.py:510:7: previous definition of `DistributionsResponse` here help: Remove definition: `DistributionsResponse`
prevalence_histogram: Optional[Histogram] = None
sd_histogram: Optional[Histogram] = None
class_distribution: Optional[Dict[str, int]] = None
Expand Down
42 changes: 28 additions & 14 deletions backend/app/routers/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])

Expand Down Expand Up @@ -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"

Expand All @@ -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
Expand All @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
'<span class="feature-chip feature-' + cls + '">'
+ _esc(f["name"]) + " (" + sign + str(f["coef"]) + ")</span>"
+ _esc(" ∨ ".join(term["features"])) + " (" + sign + str(term["coef"]) + ")</span>"
)
chips_html = "".join(chips)
formula = format_model_formula(best, feature_names, with_threshold=True)
if formula:
chips_html += '<p class="model-formula"><code>' + _esc(formula) + "</code></p>"

# Population rows
pop_rows = ""
Expand Down
30 changes: 30 additions & 0 deletions backend/app/services/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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", {})
Expand Down Expand Up @@ -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,
Expand Down
135 changes: 135 additions & 0 deletions backend/app/services/model_format.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading