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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## New functionality


* Add `methods/observer_algebra` (Observer Algebra / `multiobserver`): Unsupervised two-level Laird-Ware `MultiObserverCalculus` batch integration (`method_types: [embedding]`, Fisher + PoE Bures-aligned `obsm['X_emb']`).

* Added `metrics/kbet_pg` and `metrics/kbet_pg_label` components (PR #52).
* Add `methods/ss_stacas` new method (PR #59).
- Add semi-supervised version of STACAS tool for integration of single-cell transcriptomics data. This functionality leverages partial or imperfect knowledge of cell identity to improve integration quality by preserving biological variation while correcting for batch effects.
Expand Down
78 changes: 78 additions & 0 deletions src/methods/observer_algebra/config.vsh.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
__merge__: /src/api/comp_method.yaml

name: observer_algebra
label: Observer Algebra (MultiObserver)
summary: Pure unsupervised Two-Level Laird-Ware MultiObserverCalculus across all raw count genes (zero sklearn, max_dim=None).
description: |
Enforces the Raw-Data Axiom: drops all normalized/PCA/HVG-filtered variants (`layers['normalized']`,
`obsm['X_pca']`, `batch_hvg` gene dropping, count denoising) and reads 100% unmodified raw
`layers['counts']` across ALL genes directly (`max_dim=None`, zero HVG filtering, zero `1/std`
per-gene standardization, zero `sklearn`).
Partitions all raw genes into M=3 disjoint observers (`0::3`, `1::3`, `2::3`) via declarative
`project.toml` / `project.strict.toml` `Log1p('counts')` sensor units, fits closed-form Two-Level
Laird-Ware `MultiObserverCalculus(max_dim=None, groups=batch)` strictly unsupervised, and outputs
the Fisher + PoE Bures-Wasserstein aligned biological consensus state `obsm['X_emb']` (`calc.infer_aligned`, `method_types: [embedding]`).
links:
repository: https://github.com/robertdbak/multiview
documentation: https://github.com/robertdbak/multiview/tree/main/code/packages/multiobserver
references:
bibtex: |
@misc{bak2026imperfectviews,
title = {Algebra for Imperfect Views},
author = {B{\k{a}}k, Robert},
year = {2026},
url = {https://github.com/robertdbak/multiview}
}
info:
method_types: [embedding]
preferred_normalization: counts
arguments:
- name: "--n_panels"
type: integer
default: 3
description: Number of disjoint non-overlapping raw gene observers (every raw gene used once).
- name: "--k_candidates"
type: integer
multiple: true
description: Optional candidate shared latent ranks K (empty selects K automatically via unbounded held-out LOO-R^2).
- name: "--n_iter"
type: integer
default: 35
description: Number of closed-form Two-Level Laird-Ware EM iterations.
info:
test_default: 5
- name: "--output_model"
type: string
default: ""
description: Optional path to save pure raw-unit `.npz` MultiObserverCalculus archive.
- name: "--profile"
type: string
choices: [best, strict]
default: best
description: Sensor-physics profile ('best' uses project.toml; 'strict' uses universal zero-peeking & strictly inductive project.strict.toml).
- name: "--device"
type: string
default: auto
description: Execution backend ('auto' dispatches to CUDA when available, pure NumPy on CPU).
resources:
- type: python_script
path: script.py
- path: project.toml
- path: project.strict.toml
engines:
- type: docker
image: openproblems/base_python:1
setup:
- type: apt
packages:
- git
- type: python
upgrade: false
packages:
- "multiobserver @ git+https://github.com/robertdbak/multiview.git@main#subdirectory=code/packages/multiobserver"
- type: native
runners:
- type: executable
- type: nextflow
directives:
label: [midtime, midmem, midcpu]
15 changes: 15 additions & 0 deletions src/methods/observer_algebra/project.strict.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name = "openproblems_batch_integration_strict"
profile = "strict"
mode = "calibrate"
enforce_raw_data = true

[observer_specs.GenePanel]
unit = "log1p"
scale_policy = "isotropic"
exposure = "none"
description = "Universal untouched raw count gene panel (Log1p, isotropic, exposure='none', max_dim=None)"

[openproblems]
n_panels = 3
n_iter = 35
use_batch = true
14 changes: 14 additions & 0 deletions src/methods/observer_algebra/project.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
name = "openproblems_batch_integration"
mode = "calibrate"
enforce_raw_data = true

[observer_specs.GenePanel]
unit = "log1p"
scale_policy = "isotropic"
exposure = "cp10k"
description = "Disjoint raw count gene panel (layers['counts'], max_dim=None)"

[openproblems]
n_panels = 3
n_iter = 35
use_batch = true
171 changes: 171 additions & 0 deletions src/methods/observer_algebra/script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
"""OpenProblems.bio `task_batch_integration` method: Strictly Pure Raw-Counts Observer Algebra (`multiobserver`).

Enforces the Raw-Data Axiom (WE CANNOT CHANGE THE DATA, WE DO NOT KNOW WHAT IS NOISE):
1. Drops all normalized/PCA/HVG-filtered variants (`layers["normalized"]`, `obsm["X_pca"]`, `batch_hvg`
column subsetting, count denoising) and reads 100% unmodified raw `layers["counts"]` across ALL
genes directly (`max_dim=None`, zero `sklearn`).
2. Partitions ALL raw genes into M = 3 disjoint non-overlapping gene observers (`0::3`, `1::3`, `2::3`)
wrapped in explicit `Log1p` sensor units from `project.toml` (`--profile best`) or `project.strict.toml`
(`--profile strict`) via one-time O(nnz) CSR ingest with `max_dim=None`.
3. Fits Two-Level Laird-Ware `MultiObserverCalculus(max_dim=None, groups=batch)` (strictly unsupervised,
zero access to `cell_type` labels) and outputs the Fisher + PoE Bures-aligned consensus state
(`calc.infer_aligned`) as `obsm["X_emb"]` (`method_types: [embedding]`, never altering counts).
"""

from __future__ import annotations

import argparse
import sys
import tomllib
from pathlib import Path

import anndata as ad
import numpy as np
import scipy.sparse as sp
from multiobserver import Linear, Log1p, MultiObserverCalculus, Observer

## VIASH START
par = {
"input": "resources_test/task_batch_integration/cxg_immune_cell_atlas/dataset.h5ad",
"output": "output.h5ad",
"output_model": "",
"n_panels": 3,
"k_candidates": None,
"n_iter": 35,
"profile": "best",
"device": "auto",
}
meta = {"name": "observer_algebra", "resources_dir": str(Path(__file__).resolve().parent)}
## VIASH END

RES_DIR = Path(meta.get("resources_dir", Path(__file__).resolve().parent))


def _load_project_toml(profile: str = "best") -> dict:
fname = "project.strict.toml" if str(profile).strip().lower() == "strict" else "project.toml"
p = RES_DIR / fname
if not p.is_file():
p = RES_DIR / "project.toml"
return tomllib.loads(p.read_text(encoding="utf-8")) if p.is_file() else {}


def _build_unit_from_spec(ospec: dict, default_label: str = "counts") -> Linear | Log1p:
u = str(ospec.get("unit", "log1p")).strip().lower()
sp_pol = str(ospec.get("scale_policy", "per_channel"))
ep_pol = str(ospec.get("exposure", "row_sum"))
return Log1p(default_label, scale_policy=sp_pol, exposure=ep_pol) if u == "log1p" else Linear(default_label, scale_policy=sp_pol, exposure=ep_pol)


def _override_par_from_cli(defaults: dict) -> dict:
if len(sys.argv) <= 1:
return defaults
p = argparse.ArgumentParser(description="OpenProblems task_batch_integration: Pure Raw-Counts Observer Algebra")
p.add_argument("--input", default=defaults["input"])
p.add_argument("--output", default=defaults["output"])
p.add_argument("--seed", type=int, default=int(defaults.get("seed") or 0))
p.add_argument("--output_model", default=str(defaults.get("output_model") or ""))
p.add_argument("--n_panels", type=int, default=int(defaults["n_panels"]))
p.add_argument("--k_candidates", type=int, nargs="*", default=list(defaults.get("k_candidates") or []))
p.add_argument("--n_iter", type=int, default=int(defaults["n_iter"]))
p.add_argument("--profile", choices=["best", "strict"], default=str(defaults.get("profile", "best")))
p.add_argument("--device", default=str(defaults.get("device", "auto")))
args = p.parse_args()
out = dict(defaults)
out.update(
{
"input": args.input,
"output": args.output,
"output_model": args.output_model,
"n_panels": args.n_panels,
"k_candidates": args.k_candidates,
"n_iter": args.n_iter,
"profile": args.profile,
"device": args.device,
}
)
return out


def _get_raw_counts(adata: ad.AnnData) -> sp.csr_matrix:
if "counts" in adata.layers:
mat = adata.layers["counts"]
elif adata.raw is not None and adata.raw.X is not None and adata.raw.shape == adata.shape:
mat = adata.raw.X
elif adata.X is not None:
mat = adata.X
else:
raise KeyError("Expected raw `layers['counts']` in input AnnData.")
return mat.tocsr().astype(np.float64) if sp.issparse(mat) else sp.csr_matrix(np.asarray(mat, dtype=np.float64))


def run(cfg: dict, method_name: str) -> None:
print(
">> Reading input dataset.h5ad (strictly unsupervised, dropping normalized/PCA/HVG variants, "
"100% unmodified raw layers['counts'], max_dim=None)...",
flush=True,
)
adata = ad.read_h5ad(cfg["input"])
x_csr = _get_raw_counts(adata)
batches = adata.obs["batch"].astype(str).to_numpy()
use_groups = len(np.unique(batches)) >= 2
n_cells, n_genes = int(x_csr.shape[0]), int(x_csr.shape[1])
n_panels = max(2, min(int(cfg["n_panels"]), n_genes))

profile = str(cfg.get("profile", "best")).strip().lower()
proj = _load_project_toml(profile)
unit_spec = _build_unit_from_spec((proj.get("observer_specs") or {}).get("GenePanel", {}), "counts")
views = {
f"GenePanel_{p_idx + 1}": Observer(x_csr[:, p_idx::n_panels], unit_spec)
for p_idx in range(n_panels)
}
sum_d = sum(int(v.data.shape[1]) for v in views.values())
max_d = max(int(v.data.shape[1]) for v in views.values())
max_k = min(sum_d - max_d, n_cells - 5)
raw_cands = cfg.get("k_candidates") or (proj.get("openproblems") or {}).get("k_candidates") or []
k_cands = ([int(k) for k in raw_cands if 1 <= int(k) <= max_k] or None) if raw_cands else None
dev_req = str(cfg.get("device", "auto"))

print(
f">> Fitting Two-Level Laird-Ware MultiObserverCalculus(profile={profile!r}, unit={unit_spec!r}, max_dim=None, groups={use_groups}, "
f"N={n_cells}, G_raw={n_genes}, panels={n_panels}, k_candidates={k_cands})...",
flush=True,
)
calc = MultiObserverCalculus(
k=None,
k_candidates=k_cands,
max_dim=None,
n_iter=int(cfg["n_iter"]),
device=dev_req,
).fit(views, groups=batches if use_groups else None, allow_monotonic=True)
print(f">> Selected latent k_={calc.k_} (LOO-R^2={calc.k_cv_scores_.get(calc.k_, float('nan')):.4f})", flush=True)

out_model = str(cfg.get("output_model") or "").strip()
if out_model:
mdl_p = Path(out_model)
mdl_p.parent.mkdir(parents=True, exist_ok=True)
calc.save_npz(mdl_p)
print(f">> Saved pure raw-unit MultiObserverCalculus .npz -> {mdl_p}", flush=True)

s_aligned = np.asarray(calc.infer_aligned(views, groups=batches if use_groups else None).latent, dtype=np.float64)
z_emb = np.nan_to_num(s_aligned, nan=0.0, posinf=0.0, neginf=0.0).astype(np.float32)

uns_out = {
"dataset_id": str(adata.uns.get("dataset_id", "unknown")),
"normalization_id": str(adata.uns.get("normalization_id", "counts")),
"method_id": str(method_name),
}
if "dataset_organism" in adata.uns:
uns_out["dataset_organism"] = adata.uns["dataset_organism"]

output = ad.AnnData(
obs=adata.obs[[]].copy(),
var=adata.var[[]].copy(),
obsm={"X_emb": z_emb},
uns=uns_out,
)
print(f">> Writing integrated AnnData (X_emb={z_emb.shape}, zero count alteration) -> {cfg['output']}", flush=True)
output.write_h5ad(cfg["output"], compression="gzip")


if __name__ == "__main__":
run(_override_par_from_cli(par), meta["name"])
1 change: 1 addition & 0 deletions src/workflows/run_benchmark/config.vsh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ dependencies:
- name: methods/ss_stacas
- name: methods/stacas
- name: methods/uce
- name: methods/observer_algebra
# metrics
- name: metrics/asw_batch
- name: metrics/asw_label
Expand Down
3 changes: 2 additions & 1 deletion src/workflows/run_benchmark/main.nf
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ methods = [
stacas,
uce.run(
args: [model: file("s3://openproblems-work/cache/uce-model-v5.zip")]
)
),
observer_algebra
]

// construct list of metrics
Expand Down