icellpy 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
icellpy/__init__.py ADDED
@@ -0,0 +1,156 @@
1
+ """iCellPy — single-cell analysis with SODA archives (iCellR2 companion)."""
2
+
3
+ from .aggregation import data_aggregation
4
+ from .cluster import (
5
+ change_clust,
6
+ clust_ord,
7
+ clust_rm,
8
+ gate_to_clust,
9
+ iclust,
10
+ run_clustering,
11
+ )
12
+ from .cycle import cc
13
+ from .dimred import iba, run_cgpca, run_cgumap, run_knetl, run_pca, run_pseudotime, run_tsne, run_umap
14
+ from .spatial import (
15
+ add_10x_image,
16
+ add_visium,
17
+ add_xenium,
18
+ capture_image_10x,
19
+ spatial_genes,
20
+ spatial_graph,
21
+ spatial_plot,
22
+ spatial_transcripts,
23
+ )
24
+ from .doublets import i_doublets, run_doublets
25
+ from .extra import (
26
+ Rphenograph,
27
+ add_adt,
28
+ adt_rna_merge,
29
+ cell_cycle,
30
+ hto_anno,
31
+ hto_demux,
32
+ norm_adt,
33
+ run_impute,
34
+ run_sketch,
35
+ )
36
+ from .atac import add_atac, add_multiome, atac_rna_merge, gene_activity, norm_atac
37
+ from .peaks import merge_peaks
38
+ from .vdj import add_vdj, clono_plot, prep_vdj, vdj_stats
39
+ from .features import data_scale, gene_stats, make_gene_model
40
+ from .load10x import load10x
41
+ from .make_obj import make_obj
42
+ from .markers import clust_avg_exp, find_markers, i_score, run_diff_exp, top_markers
43
+ from .norm_data import norm_data
44
+ from .plots import (
45
+ arrange_cluster_plots,
46
+ benchmark_plot,
47
+ bubble_gg_plot,
48
+ cluster_plot,
49
+ clust_cond_info,
50
+ clust_stats_plot,
51
+ doublets_plot,
52
+ gene_plot,
53
+ gg_cor,
54
+ heatmap_gg_plot,
55
+ opt_pcs_plot,
56
+ pseudotime_arrows,
57
+ stats_plot,
58
+ qc_dashboard,
59
+ volcano_ma_plot,
60
+ )
61
+ from .qc import cell_filter, down_sample, qc_stats
62
+ from .soda import SodaObject, open_soda
63
+ from .soda_utils import install_cli, refresh_soda, validate_soda
64
+
65
+ __version__ = "0.3.1"
66
+
67
+ __all__ = [
68
+ # core
69
+ "open_soda",
70
+ "validate_soda",
71
+ "refresh_soda",
72
+ "install_cli",
73
+ "SodaObject",
74
+ "load10x",
75
+ "data_aggregation",
76
+ "make_obj",
77
+ "norm_data",
78
+ # qc / filter
79
+ "qc_stats",
80
+ "cell_filter",
81
+ "down_sample",
82
+ "run_doublets",
83
+ "i_doublets",
84
+ "doublets_plot",
85
+ # features
86
+ "gene_stats",
87
+ "make_gene_model",
88
+ "data_scale",
89
+ # dimred
90
+ "run_pca",
91
+ "iba",
92
+ "run_umap",
93
+ "run_tsne",
94
+ "cc",
95
+ "capture_image_10x",
96
+ "add_10x_image",
97
+ "add_visium",
98
+ "add_xenium",
99
+ "spatial_plot",
100
+ "spatial_graph",
101
+ "spatial_genes",
102
+ "spatial_transcripts",
103
+ "run_knetl",
104
+ "run_pseudotime",
105
+ "run_cgpca",
106
+ "run_cgumap",
107
+ # cluster
108
+ "run_clustering",
109
+ "change_clust",
110
+ "clust_rm",
111
+ "gate_to_clust",
112
+ "clust_ord",
113
+ "iclust",
114
+ "Rphenograph",
115
+ # markers / DE
116
+ "find_markers",
117
+ "i_score",
118
+ "top_markers",
119
+ "run_diff_exp",
120
+ "clust_avg_exp",
121
+ # plots
122
+ "cluster_plot",
123
+ "arrange_cluster_plots",
124
+ "gene_plot",
125
+ "stats_plot",
126
+ "qc_dashboard",
127
+ "opt_pcs_plot",
128
+ "volcano_ma_plot",
129
+ "heatmap_gg_plot",
130
+ "bubble_gg_plot",
131
+ "gg_cor",
132
+ "clust_cond_info",
133
+ "clust_stats_plot",
134
+ "pseudotime_arrows",
135
+ "benchmark_plot",
136
+ # extras
137
+ "run_sketch",
138
+ "run_impute",
139
+ "add_adt",
140
+ "norm_adt",
141
+ "adt_rna_merge",
142
+ "prep_vdj",
143
+ "add_vdj",
144
+ "vdj_stats",
145
+ "clono_plot",
146
+ "merge_peaks",
147
+ "add_atac",
148
+ "norm_atac",
149
+ "gene_activity",
150
+ "add_multiome",
151
+ "atac_rna_merge",
152
+ "cell_cycle",
153
+ "hto_anno",
154
+ "hto_demux",
155
+ "__version__",
156
+ ]
icellpy/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Allow ``python -m icellpy <command> [options]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .cli import main
8
+
9
+ if __name__ == "__main__":
10
+ raise SystemExit(main())
@@ -0,0 +1,3 @@
1
+ """Embedded QC dashboard HTML template (synced with iCellR2 F0061)."""
2
+
3
+ QC_DASH_HTML_TEMPLATE = '<!DOCTYPE html>\n<html lang="en" data-theme="light">\n<head>\n<meta charset="utf-8"/>\n<meta name="viewport" content="width=device-width, initial-scale=1"/>\n<title>QC filter explorer</title>\n<script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>\n<style>\n:root, [data-theme="light"]{\n --ink:#14242a; --mute:#5a6b72; --line:#d7e0e3; --paper:#eef3f4; --card:#ffffff;\n --accent:#0f766e; --pass:#0f766e; --fail:#c5cdd1; --cut:#be123c;\n --chip:#ccfbf1; --shadow:0 10px 30px rgba(15,55,60,.08);\n}\n[data-theme="dark"]{\n --ink:#e8f1f2; --mute:#9bb0b6; --line:#2a3f44; --paper:#0b1619; --card:#122226;\n --accent:#2dd4bf; --pass:#2dd4bf; --fail:#3a4a4e; --cut:#fb7185;\n --chip:#134e4a; --shadow:0 10px 30px rgba(0,0,0,.35);\n}\n*{box-sizing:border-box}\nbody{margin:0;background:var(--paper);color:var(--ink);\n font-family:"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif}\n.wrap{max-width:1280px;margin:0 auto;padding:22px 18px 56px}\n.top{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:10px}\nh1{margin:0;font-size:26px;letter-spacing:-.03em}\n.lede{color:var(--mute);font-size:14px;margin:6px 0 0;max-width:72ch;line-height:1.5}\n.btn{appearance:none;border:1px solid var(--line);background:var(--card);color:var(--ink);\n border-radius:10px;padding:8px 12px;font:inherit;font-size:12.5px;cursor:pointer;font-weight:600}\n.btn:hover{border-color:var(--accent);color:var(--accent)}\n.controls{position:sticky;top:10px;z-index:5;background:color-mix(in srgb, var(--card) 92%, transparent);\n backdrop-filter:blur(10px);border:1px solid var(--line);border-radius:16px;padding:14px 16px;\n margin:14px 0 16px;display:grid;gap:12px;box-shadow:var(--shadow)}\n.keep{font-weight:600;color:var(--pass);background:var(--chip);border-radius:999px;padding:7px 12px;display:inline-block}\n.sliders{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}\nlabel{display:flex;justify-content:space-between;font-size:12px;color:var(--mute)}\nlabel b{color:var(--ink)}\ninput[type=range]{width:100%;accent-color:var(--accent)}\n.cmd{font-family:ui-monospace,Menlo,monospace;font-size:12px;background:color-mix(in srgb,var(--accent) 8%, var(--card));\n border:1px solid var(--line);padding:9px 11px;border-radius:10px;overflow:auto;color:var(--ink)}\n.grid2{display:grid;grid-template-columns:1.4fr .9fr;gap:14px;margin-bottom:14px}\n.grid3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}\n.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:12px;box-shadow:var(--shadow)}\n.card-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:6px}\n.card-head .title{font-size:12px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--mute)}\n.dl-group{display:flex;gap:6px}\n.dl{appearance:none;border:1px solid var(--line);background:var(--paper);color:var(--ink);\n border-radius:8px;padding:5px 9px;font:inherit;font-size:11.5px;cursor:pointer;font-weight:600}\n.dl:hover{border-color:var(--accent);color:var(--accent)}\n.fig-legend{margin:8px 2px 0;padding:0;color:var(--mute);font-size:12px;line-height:1.45;font-style:italic}\n.plot{width:100%;height:380px}\n.plot.box{height:340px}\nh2{margin:20px 0 10px;font-size:15px;letter-spacing:.08em;text-transform:uppercase;color:var(--mute)}\ntable{width:100%;border-collapse:collapse;font-size:13px}\nth,td{padding:8px 8px;border-bottom:1px solid var(--line);text-align:left}\nth{color:var(--mute);font-size:11px;text-transform:uppercase;letter-spacing:.04em}\ntd.num{text-align:right;font-variant-numeric:tabular-nums}\n@media(max-width:960px){.sliders,.grid2,.grid3{grid-template-columns:1fr}}\n</style>\n</head>\n<body>\n<div class="wrap">\n <div class="top">\n <div>\n <h1>QC filter explorer</h1>\n <p class="lede">\n Inspect QC before filtering. Sliders preview proposed cell.filter() cuts\n (pass/fail + keep table). Download PNG/SVG for any plot at the current settings.\n </p>\n </div>\n <button class="btn" id="theme-btn" type="button">Theme</button>\n </div>\n\n <div class="controls">\n <div><span class="keep" id="keep-pill">—</span>\n <button class="dl" id="reset" type="button" style="margin-left:8px">Reset defaults</button></div>\n <div class="sliders">\n <div><label>min.genes <b id="v-g">200</b></label><input id="min-genes" type="range"/></div>\n <div><label>min.umis <b id="v-u">500</b></label><input id="min-umis" type="range"/></div>\n <div><label>max.mito <b id="v-m">0.10</b></label><input id="max-mito" type="range"/></div>\n </div>\n <div class="cmd" id="cmd"></div>\n </div>\n\n <h2>Core QC</h2>\n <div class="grid2">\n <div class="card">\n <div class="card-head"><span class="title">UMI × genes</span>\n <div class="dl-group">\n <button class="dl" type="button" data-dl="sc-mito" data-fmt="png">PNG</button>\n <button class="dl" type="button" data-dl="sc-mito" data-fmt="svg">SVG</button>\n </div>\n </div>\n <div class="plot" id="sc-mito"></div>\n <p class="fig-legend">UMI × genes coloured by mitochondrial fraction — joint view of complexity, depth, and mito load.</p>\n </div>\n <div class="card" id="sample-card">\n <div class="card-head"><span class="title" id="sample-title">Pass by sample</span></div>\n <div style="max-height:380px;overflow:auto">\n <table id="tbl"><thead><tr><th id="th-sample">Sample</th><th class="num">Cells</th><th class="num">Pass preview</th><th class="num">% pass</th></tr></thead><tbody></tbody></table>\n </div>\n <p class="fig-legend" id="sample-why">Cells and preview-pass counts by sample under the current slider cuts (data still unfiltered).</p>\n </div>\n </div>\n <div class="grid3">\n <div class="card">\n <div class="card-head"><span class="title">Genes</span>\n <div class="dl-group">\n <button class="dl" type="button" data-dl="box-g" data-fmt="png">PNG</button>\n <button class="dl" type="button" data-dl="box-g" data-fmt="svg">SVG</button>\n </div>\n </div>\n <div class="plot box" id="box-g"></div>\n </div>\n <div class="card">\n <div class="card-head"><span class="title">UMIs</span>\n <div class="dl-group">\n <button class="dl" type="button" data-dl="box-u" data-fmt="png">PNG</button>\n <button class="dl" type="button" data-dl="box-u" data-fmt="svg">SVG</button>\n </div>\n </div>\n <div class="plot box" id="box-u"></div>\n </div>\n <div class="card">\n <div class="card-head"><span class="title">Mito %</span>\n <div class="dl-group">\n <button class="dl" type="button" data-dl="box-m" data-fmt="png">PNG</button>\n <button class="dl" type="button" data-dl="box-m" data-fmt="svg">SVG</button>\n </div>\n </div>\n <div class="plot box" id="box-m"></div>\n </div>\n </div>\n\n <h2>Filter preview</h2>\n <div class="card">\n <div class="card-head"><span class="title">Pass / fail preview</span>\n <div class="dl-group">\n <button class="dl" type="button" data-dl="sc-pass" data-fmt="png">PNG</button>\n <button class="dl" type="button" data-dl="sc-pass" data-fmt="svg">SVG</button>\n </div>\n </div>\n <div class="plot" id="sc-pass"></div>\n <p class="fig-legend">UMI × genes coloured by pass/fail under the current slider cuts. Dotted lines: min.genes and min.umis.</p>\n </div>\n</div>\n<script>\nwindow.SODA_DASH = __JSON__;\n</script>\n<script>\n(function(){\n const D=window.SODA_DASH, F=D.qc_filters, qc=D.qc;\n const root=document.documentElement;\n const saved=localStorage.getItem("ic2-qc-theme");\n if(saved) root.setAttribute("data-theme", saved);\n document.getElementById("theme-btn").onclick=()=>{\n const next=root.getAttribute("data-theme")==="dark"?"light":"dark";\n root.setAttribute("data-theme", next);\n localStorage.setItem("ic2-qc-theme", next);\n update();\n };\n\n function theme(){\n const dark=root.getAttribute("data-theme")==="dark";\n return {\n ink: dark?"#e8f1f2":"#14242a",\n mute: dark?"#9bb0b6":"#5a6b72",\n card: dark?"#122226":"#ffffff",\n pass: dark?"#2dd4bf":"#0f766e",\n fail: dark?"#3a4a4e":"#c5cdd1",\n cut: dark?"#fb7185":"#be123c",\n grid: dark?"rgba(255,255,255,.06)":"rgba(20,36,42,.05)"\n };\n }\n const cols=["#4C78A8","#F58518","#54A24B","#E45756","#72B7B2","#B279A2","#FF9DA6","#9D755D","#BAB0AC","#1F7A6C","#6B5B95","#D4A373"];\n // Always at least one group (single-sample / missing labels → "all")\n let order = (D.condition_order||[]).map(String).filter(s=>s && s!=="null" && s!=="undefined");\n if(!order.length){\n const seen={};\n qc.forEach(r=>{ const c=String(r.condition_id||"all"); if(c) seen[c]=1; });\n order=Object.keys(seen);\n }\n if(!order.length) order=["all"];\n const nCond=order.length;\n const single=nCond===1;\n\n if(single){\n document.getElementById("sample-title").textContent="Pass summary";\n document.getElementById("th-sample").textContent="Group";\n document.getElementById("sample-why").textContent="Cells and preview-pass counts under the current slider cuts (data still unfiltered).";\n }\n\n function baseLayout(){\n const t=theme();\n return {paper_bgcolor:t.card, plot_bgcolor:t.card,\n font:{family:"Avenir Next, Segoe UI, Helvetica Neue, Arial, sans-serif", color:t.ink, size:12},\n margin:{l:52,r:14,t:36,b:44}, hovermode:"closest"};\n }\n const cfg={responsive:true, displayModeBar:true, displaylogo:false,\n modeBarButtonsToRemove:["lasso2d","select2d"],\n toImageButtonOptions:{format:"png", height:800, width:1200, scale:2}};\n\n function setup(id,key,def){const el=document.getElementById(id),r=F.ranges[key];el.min=r.min;el.max=r.max;el.step=r.step;el.value=def;return el;}\n const sG=setup("min-genes","min_genes",F.defaults.min_genes);\n const sU=setup("min-umis","min_umis",F.defaults.min_umis);\n const sM=setup("max-mito","max_mito",F.defaults.max_mito);\n function filt(){return{min_genes:+sG.value,min_umis:+sU.value,max_mito:+sM.value};}\n function ok(r,f){return r.nGenes>=f.min_genes&&r.UMIs>=f.min_umis&&r["mito.percent"]<=f.max_mito;}\n function ax(){const t=theme(); return {tickfont:{color:t.mute,size:10},showgrid:true,gridcolor:t.grid,zeroline:false,linecolor:t.ink,ticks:"outside"};}\n function axOpen(){const t=theme(); return {tickfont:{color:t.mute,size:10},showgrid:false,zeroline:false,linecolor:t.ink,ticks:"outside", mirror:false};}\n function hexAlpha(hex,a){\n const h=String(hex).replace("#","");\n const r=parseInt(h.slice(0,2),16), g=parseInt(h.slice(2,4),16), b=parseInt(h.slice(4,6),16);\n return "rgba("+r+","+g+","+b+","+a+")";\n }\n function mean(vals){return vals.length?vals.reduce((s,v)=>s+v,0)/vals.length:null;}\n\n // Match PDF: violin + white box + jitter + mean diamond (ggplot .ic2_qc_dash_box)\n function boxTraces(metric){\n const t=theme();\n const jit=Math.max(0.03, Math.min(0.14, 0.45/nCond));\n const boxW=Math.max(0.18, Math.min(0.42, 1.15/nCond));\n const pt=nCond>8?2.8:nCond>4?3.2:3.8;\n const boxFill=root.getAttribute("data-theme")==="dark"?"#1a2e32":"#ffffff";\n const violins=order.map((cond,i)=>{\n const vals=qc.filter(r=>String(r.condition_id)===String(cond)).map(r=>r[metric]);\n const col=cols[i%cols.length];\n return {\n type:"violin", name:cond,\n x:vals.map(()=>cond), y:vals,\n points:"all", jitter:jit, pointpos:0,\n scalemode:"width", spanmode:"hard", width:0.9,\n fillcolor:hexAlpha(col,0.35),\n line:{color:t.ink,width:0.9},\n marker:{size:pt, opacity:0.45, color:col, line:{width:0}},\n box:{visible:true, width:boxW, fillcolor:boxFill, line:{color:t.ink,width:1}},\n meanline:{visible:false},\n hoverinfo:"y+name",\n side:"both"\n };\n });\n const means={\n type:"scatter", mode:"markers", name:"mean",\n x:order,\n y:order.map(cond=>{\n const vals=qc.filter(r=>String(r.condition_id)===String(cond)).map(r=>r[metric]);\n return mean(vals);\n }),\n marker:{symbol:"diamond", size:9, color:t.ink, line:{width:0}},\n hovertemplate:"mean %{y:.3g}<extra></extra>",\n showlegend:false\n };\n return violins.concat([means]);\n }\n function drawBoxes(f){\n const t=theme();\n const xAngle=nCond>8?60:nCond>5?35:0;\n [["box-g","nGenes","Genes / cell",f.min_genes],\n ["box-u","UMIs","UMIs / cell",f.min_umis],\n ["box-m","mito.percent","Mito % / cell",f.max_mito]].forEach(([el,metric,title,cut])=>{\n Plotly.react(el, boxTraces(metric), Object.assign({}, baseLayout(), {\n title:{text:title+(single?" · single sample":" · by sample"), font:{size:14}, x:0, xanchor:"left"},\n showlegend:false,\n violingap:0.15,\n violinmode:"group",\n yaxis:Object.assign({title:metric}, axOpen()),\n xaxis:Object.assign({\n type:"category", categoryorder:"array", categoryarray:order,\n tickangle:xAngle\n }, axOpen()),\n shapes:[{type:"line", y0:cut, y1:cut, x0:0, x1:1, xref:"paper", line:{color:t.cut, width:1.3, dash:"dot"}}],\n margin:{l:52,r:12,t:40,b:xAngle?70:48}\n }), Object.assign({}, cfg, {toImageButtonOptions:{format:"png",filename:"QC_"+el,height:800,width:1000,scale:2}}));\n });\n }\n\n function update(){\n const f=filt(), t=theme();\n document.getElementById("v-g").textContent=Math.round(f.min_genes);\n document.getElementById("v-u").textContent=Math.round(f.min_umis);\n document.getElementById("v-m").textContent=f.max_mito.toFixed(3);\n document.getElementById("cmd").textContent="cell.filter(obj, min.genes="+Math.round(f.min_genes)+", min.umis="+Math.round(f.min_umis)+", max.mito="+(+f.max_mito.toFixed(3))+")";\n const keep=[], fail=[]; qc.forEach(r=>(ok(r,f)?keep:fail).push(r));\n document.getElementById("keep-pill").innerHTML="Preview pass <b>"+keep.length.toLocaleString()+"</b> / "+qc.length.toLocaleString()+" ("+((100*keep.length)/qc.length).toFixed(1)+"%)";\n const tb=document.querySelector("#tbl tbody"); tb.innerHTML="";\n order.forEach(cond=>{\n const all=qc.filter(r=>String(r.condition_id)===String(cond)), k=all.filter(r=>ok(r,f));\n const tr=document.createElement("tr");\n const label=single?(cond==="all"?"all cells":cond):cond;\n tr.innerHTML="<td>"+label+"</td><td class=\'num\'>"+all.length+"</td><td class=\'num\'>"+k.length+"</td><td class=\'num\'>"+(all.length?((100*k.length)/all.length).toFixed(1):"—")+"%</td>";\n tb.appendChild(tr);\n });\n\n Plotly.react("sc-mito",[{\n type:"scattergl", mode:"markers",\n x:qc.map(r=>r.nGenes), y:qc.map(r=>r.UMIs),\n customdata:qc.map(r=>r["mito.percent"]),\n text:qc.map(r=>r.condition_id),\n marker:{size:4, opacity:.8, color:qc.map(r=>r["mito.percent"]),\n colorscale: (root.getAttribute("data-theme")==="dark") ?\n [[0,"#334155"],[0.5,"#fb923c"],[1,"#f43f5e"]] :\n [[0,"#e2e8f0"],[0.5,"#fb923c"],[1,"#be123c"]],\n cmin:0, cmax:Math.max(0.05, ...qc.map(r=>r["mito.percent"])),\n colorbar:{title:"mito%", thickness:12, len:.55}},\n hovertemplate:"%{text}<br>genes=%{x}<br>UMIs=%{y}<br>mito=%{customdata:.3f}<extra></extra>"\n }], Object.assign({}, baseLayout(), {\n title:{text:"UMI × genes · mito colour", font:{size:14}, x:0, xanchor:"left"},\n xaxis:Object.assign({title:"nGenes"}, ax()),\n yaxis:Object.assign({title:"UMIs"}, ax()),\n shapes:[\n {type:"line", x0:f.min_genes, x1:f.min_genes, y0:0, y1:1, yref:"paper", line:{color:t.cut, width:1.2, dash:"dot"}},\n {type:"line", y0:f.min_umis, y1:f.min_umis, x0:0, x1:1, xref:"paper", line:{color:t.cut, width:1.2, dash:"dot"}}\n ]\n }), Object.assign({}, cfg, {toImageButtonOptions:{format:"png",filename:"QC_sc-mito",height:800,width:1200,scale:2}}));\n\n Plotly.react("sc-pass",[\n {type:"scattergl", mode:"markers", name:"fail preview", x:fail.map(r=>r.nGenes), y:fail.map(r=>r.UMIs), marker:{size:4, color:t.fail, opacity:.7}},\n {type:"scattergl", mode:"markers", name:"pass preview", x:keep.map(r=>r.nGenes), y:keep.map(r=>r.UMIs), marker:{size:4, color:t.pass, opacity:.75}}\n ], Object.assign({}, baseLayout(), {\n title:{text:"UMI × genes · filter preview", font:{size:14}, x:0, xanchor:"left"},\n xaxis:Object.assign({title:"nGenes"}, ax()),\n yaxis:Object.assign({title:"UMIs"}, ax()),\n legend:{orientation:"h", y:1.12},\n shapes:[\n {type:"line", x0:f.min_genes, x1:f.min_genes, y0:0, y1:1, yref:"paper", line:{color:t.cut, width:1.3, dash:"dot"}},\n {type:"line", y0:f.min_umis, y1:f.min_umis, x0:0, x1:1, xref:"paper", line:{color:t.cut, width:1.3, dash:"dot"}}\n ]\n }), Object.assign({}, cfg, {toImageButtonOptions:{format:"png",filename:"QC_sc-pass",height:800,width:1200,scale:2}}));\n\n drawBoxes(f);\n }\n\n document.querySelectorAll("[data-dl]").forEach(btn=>{\n btn.addEventListener("click", ()=>{\n const id=btn.getAttribute("data-dl");\n const fmt=btn.getAttribute("data-fmt")||"png";\n Plotly.downloadImage(id, {\n format:fmt, width:1200, height:800, scale:2,\n filename:"QC_"+id\n });\n });\n });\n\n ["min-genes","min-umis","max-mito"].forEach(id=>document.getElementById(id).addEventListener("input", update));\n document.getElementById("reset").onclick=()=>{sG.value=F.defaults.min_genes; sU.value=F.defaults.min_umis; sM.value=F.defaults.max_mito; update();};\n update();\n})();\n</script>\n</body>\n</html>'
icellpy/aggregation.py ADDED
@@ -0,0 +1,175 @@
1
+ """Aggregate multiple samples into a virtual project descriptor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import pandas as pd
9
+ from scipy import sparse
10
+
11
+ from .io_h5 import read_csc_hdf5, write_tenx_hdf5
12
+ from .types import Aggregation, AssayHandle, Sample, as_csc_float32, clean_name
13
+
14
+
15
+ def _matrix_dimnames(obj: Any) -> tuple[sparse.csc_matrix, list[str], list[str]]:
16
+ if isinstance(obj, Sample):
17
+ if obj.matrix is not None:
18
+ mat = as_csc_float32(obj.matrix)
19
+ feats = obj.feature_ids or list(getattr(mat, "feature_ids", []))
20
+ cells = obj.cell_ids or list(getattr(mat, "cell_ids", []))
21
+ if not feats:
22
+ feats = [f"f{i}" for i in range(mat.shape[0])]
23
+ if not cells:
24
+ cells = [f"c{i}" for i in range(mat.shape[1])]
25
+ return mat, feats, cells
26
+ if obj.handle is not None:
27
+ mat, feats, cells = read_csc_hdf5(obj.handle.path, group=obj.handle.group)
28
+ return mat, list(feats), list(cells)
29
+ raise ValueError(f"Sample {obj.sample_id!r} has no matrix/handle")
30
+
31
+ if isinstance(obj, AssayHandle):
32
+ return read_csc_hdf5(obj.path, group=obj.group)
33
+
34
+ if isinstance(obj, pd.DataFrame):
35
+ mat = as_csc_float32(obj)
36
+ return (
37
+ mat,
38
+ [clean_name(x) for x in obj.index.astype(str)],
39
+ [clean_name(x) for x in obj.columns.astype(str)],
40
+ )
41
+
42
+ if sparse.issparse(obj):
43
+ mat = as_csc_float32(obj)
44
+ feats = list(getattr(obj, "feature_ids", None) or [f"f{i}" for i in range(mat.shape[0])])
45
+ cells = list(getattr(obj, "cell_ids", None) or [f"c{i}" for i in range(mat.shape[1])])
46
+ return mat, [clean_name(x) for x in feats], [clean_name(x) for x in cells]
47
+
48
+ raise TypeError(f"Unsupported sample type: {type(obj)}")
49
+
50
+
51
+ def data_aggregation(
52
+ samples: list[Any] | dict[str, Any],
53
+ *,
54
+ sample_ids: list[str] | None = None,
55
+ condition_names: list[str] | None = None,
56
+ modality: str = "rna",
57
+ output: str = "virtual",
58
+ out_dir: str | Path = "iCellPy_agg_tmp",
59
+ overwrite: bool = True,
60
+ ) -> Aggregation:
61
+ """Aggregate samples. Default ``output='virtual'`` (no mega-matrix)."""
62
+ if isinstance(samples, dict):
63
+ if sample_ids is None:
64
+ sample_ids = [clean_name(k) for k in samples.keys()]
65
+ samples = list(samples.values())
66
+
67
+ if samples is None or len(samples) < 2:
68
+ raise ValueError("'samples' must be a list with at least two elements.")
69
+ if output != "virtual":
70
+ raise NotImplementedError("Only output='virtual' is supported so far.")
71
+
72
+ if sample_ids is None:
73
+ sample_ids = []
74
+ for i, s in enumerate(samples):
75
+ sid = None
76
+ if isinstance(s, Sample):
77
+ sid = s.sample_id
78
+ elif isinstance(s, AssayHandle):
79
+ sid = s.sample_id
80
+ if not sid:
81
+ raise ValueError(
82
+ f"Sample {i} has no sample_id. "
83
+ "Pass sample_ids= or use Sample objects from load10x()."
84
+ )
85
+ sample_ids.append(clean_name(sid))
86
+ else:
87
+ sample_ids = [clean_name(x) for x in sample_ids]
88
+
89
+ if len(sample_ids) != len(samples):
90
+ raise ValueError("sample_ids length must match samples.")
91
+ if len(set(sample_ids)) != len(sample_ids):
92
+ raise ValueError(f"Duplicate sample_ids: {sample_ids}")
93
+
94
+ if condition_names is None:
95
+ condition_names = list(sample_ids)
96
+ else:
97
+ condition_names = [clean_name(x) for x in condition_names]
98
+ if len(condition_names) != len(samples):
99
+ raise ValueError("condition_names length must match samples.")
100
+
101
+ out_dir = Path(out_dir)
102
+ handles: list[AssayHandle] = []
103
+ feature_maps = []
104
+ cell_maps = []
105
+ all_features: list[str] = []
106
+
107
+ for i, s in enumerate(samples):
108
+ if isinstance(s, Sample) and s.handle is not None and s.matrix is None:
109
+ h = s.handle
110
+ h.sample_id = sample_ids[i]
111
+ feats = list(h.feature_ids or [])
112
+ cells = list(h.cell_ids or [])
113
+ if not feats or not cells:
114
+ _, feats, cells = read_csc_hdf5(h.path, group=h.group)
115
+ h.feature_ids = feats
116
+ h.cell_ids = cells
117
+ h.n_features = len(feats)
118
+ h.n_cells = len(cells)
119
+ handles.append(h)
120
+ else:
121
+ mat, feats, cells = _matrix_dimnames(s)
122
+ out_dir.mkdir(parents=True, exist_ok=True)
123
+ dest = out_dir / f"{sample_ids[i]}_tenx.h5"
124
+ h = write_tenx_hdf5(
125
+ mat, dest, feature_ids=feats, cell_ids=cells, overwrite=overwrite
126
+ )
127
+ h.sample_id = sample_ids[i]
128
+ handles.append(h)
129
+
130
+ prefixed = [f"{sample_ids[i]}_{c}" for c in cells]
131
+ feature_maps.append(
132
+ pd.DataFrame(
133
+ {
134
+ "sample_id": sample_ids[i],
135
+ "condition_id": condition_names[i],
136
+ "local_feature": feats,
137
+ "global_feature": feats,
138
+ }
139
+ )
140
+ )
141
+ cell_maps.append(
142
+ pd.DataFrame(
143
+ {
144
+ "sample_id": sample_ids[i],
145
+ "condition_id": condition_names[i],
146
+ "local_cell": cells,
147
+ "global_cell": prefixed,
148
+ }
149
+ )
150
+ )
151
+ for f in feats:
152
+ if f not in all_features:
153
+ all_features.append(f)
154
+
155
+ sample_data = pd.DataFrame(
156
+ {
157
+ "sample_id": sample_ids,
158
+ "condition_id": condition_names,
159
+ "modality": modality,
160
+ "assay_path": [h.path for h in handles],
161
+ "assay_backend": [h.backend for h in handles],
162
+ }
163
+ )
164
+
165
+ return Aggregation(
166
+ modality=modality,
167
+ samples=list(samples),
168
+ sample_ids=sample_ids,
169
+ condition_names=condition_names,
170
+ handles=handles,
171
+ feature_universe=all_features,
172
+ cell_maps=cell_maps,
173
+ feature_maps=feature_maps,
174
+ sample_data=sample_data,
175
+ )
@@ -0,0 +1,239 @@
1
+ # SODA architecture — Single Omics Data Archive (iCellR2)
2
+ #
3
+ # This file documents the on-disk layout of a `*.soda` directory and how it
4
+ # maps to iCellR2 S4 slots. Matrices stay on disk (HDF5 CSC); the S4 object
5
+ # is handle-only.
6
+ #
7
+ # Legend
8
+ # [impl] written by current iCellR2 tools
9
+ # [planned] reserved / schema-ready, not yet populated by default tools
10
+ # .json nested metadata (language-neutral)
11
+ # .tsv portable tables (Python / R / Excel) — text tables
12
+ # .info small key–value twin of soda.json (human skim)
13
+ # .h5 HDF5 sparse CSC assay or dense embeddings
14
+ # .parquet optional tabular interchange (when arrow is available)
15
+ # .txt/.log plain-text logs / benchmarks
16
+ # .uwot UMAP models via uwot::save_uwot
17
+ # .html/.png optional plots (often written next to the archive, or plots/)
18
+ #
19
+ # ALLOWED formats in a SODA archive:
20
+ # .json .h5 .hdf5 .parquet .tsv .txt .log .info .uwot
21
+ # (+ optional plot exports .html/.png under plots/)
22
+ # FORBIDDEN: .rds (legacy readable once, then removed)
23
+ #
24
+ # Copy shipped with the package: inst/soda/architecture.txt
25
+ # Also copied into each archive root as architecture.txt
26
+
27
+ ================================================================================
28
+ ON-DISK TREE (<project>.soda/)
29
+ ================================================================================
30
+
31
+ <project>.soda/ [impl]
32
+ │
33
+ ├── soda.json [impl] archive manifest (JSON)
34
+ ├── soda.info [impl] key–value twin of soda.json
35
+ ├── architecture.txt [impl] this file
36
+ ├── benchmark.txt [impl] wall / CPU / RAM KPIs
37
+ ├── iCellR2.log [impl] tool run log
38
+ │
39
+ ├── metadata/ [impl]
40
+ │ ├── project_info.json [impl] → slot project_info
41
+ │ │ fields: project_id, project_name, description,
42
+ │ │ organism, genome_build, technologies,
43
+ │ │ date_created, package_version, …
44
+ │ ├── sample_data.tsv [impl] → slot samples / sample_data
45
+ │ │ columns: sample_id, donor_id, batch_id,
46
+ │ │ condition_id, tissue, platform,
47
+ │ │ modality, misc, …
48
+ │ ├── cell_data.tsv [impl] → slot cell_data
49
+ │ │ columns: cell_id, barcode, sample_id, donor_id,
50
+ │ │ batch_id, condition_id, entity_type,
51
+ │ │ nGenes, UMIs, mito.percent,
52
+ │ │ S.phase.probability, g2m.phase.probability,
53
+ │ │ cluster_id, annotations…, misc…
54
+ │ ├── cell_maps.tsv [impl] cell ↔ sample mapping
55
+ │ ├── feature_maps.tsv [impl] feature ↔ modality mapping
56
+ │ ├── <modality>_feature_data.tsv [impl] e.g. rna_feature_data.tsv
57
+ │ │ columns: feature_id, feature_name, feature_type,
58
+ │ │ chromosome, start, end, strand, misc…
59
+ │ ├── <modality>_gene_stats.tsv [impl] gene.stats() output
60
+ │ ├── <modality>_gene_model.tsv [impl] make.gene.model() HVG list
61
+ │ ├── params.json [impl] → slot params
62
+ │ │ import, qc, normalization, feature_selection,
63
+ │ │ dimensionality_reduction, graph_construction,
64
+ │ │ clustering, integration, visualization, misc
65
+ │ ├── commands.json [impl] → slot commands
66
+ │ │ command_log, timestamps, arguments, outputs
67
+ │ ├── version.json [impl] → slot version
68
+ │ │ object_version, schema_version, package_version
69
+ │ ├── session_stats.json [impl] progress / RAM session
70
+ │ └── clustering/ [impl]
71
+ │ ├── clustering.json
72
+ │ ├── <modality>_cluster_id.tsv
73
+ │ └── <modality>_clust_avg.tsv [impl] optional clust.avg.exp()
74
+ │
75
+ ├── modalities/ [impl]
76
+ │ └── <modality>/ [impl] e.g. rna / atac / adt …
77
+ │ ├── assays/
78
+ │ │ ├── counts/ [impl]
79
+ │ │ │ ├── <sample_id>/<sample_id>.h5 [impl] CSC HDF5 (virtual multi-sample)
80
+ │ │ │ ├── <sample_id>/tenx_meta.json [impl] optional 10x pointer meta
81
+ │ │ │ ├── <sample_id>/tenx_pointer.json [impl] external 10x pointer (copy.raw=FALSE)
82
+ │ │ │ └── assay_source.h5 [impl] single-file / merged assay
83
+ │ │ ├── data/ [impl] normalized (norm.data)
84
+ │ │ │ ├── assay_source.h5 [impl]
85
+ │ │ │ └── size_factors.tsv [impl]
86
+ │ │ ├── scale.data/ [impl] optional data.scale()
87
+ │ │ └── <layer>/ [planned] custom layers
88
+ │ ├── filters/
89
+ │ │ └── kept_cell_ids.tsv [impl] cell.filter()
90
+ │ ├── sketches/ [impl] run.sketch() outputs
91
+ │ ├── graphs/ [planned] knn / snn / cluster_graphs
92
+ │ ├── markers/ [planned] findMarkers tables
93
+ │ ├── models/ [planned]
94
+ │ ├── params/ [planned] modality-local params
95
+ │ └── misc/ [planned]
96
+ │
97
+ ├── reductions/ [impl] → slots reductions /
98
+ │ │ modalities[[mod]]$reductions
99
+ │ └── <name>/ [impl] pca, umap, cgpca, cgumap, …
100
+ │ ├── reduction.json [impl] dims, method, modality, …
101
+ │ ├── cell_embeddings.h5 [impl] cells × dims
102
+ │ ├── feature_loadings.h5 [impl] optional (PCA)
103
+ │ └── stdev.tsv [impl] optional
104
+ │
105
+ ├── graphs/ [planned] integrated / global graphs
106
+ │ ├── integrated_knn, integrated_snn, wnn, …
107
+ │
108
+ ├── multimodal/ [impl] RNA+ADT / RNA+ATAC joint results
109
+ │ ├── rna_atac/, rna_adt/, multiome/, …
110
+ │ │ multimodal.json, joint_pca/, …
111
+ │
112
+ ├── images/ [planned] spatial / visium / xenium
113
+ ├── molecules/ [planned]
114
+ ├── segments/ [planned]
115
+ ├── indexes/ [planned] chunk / feature indexes
116
+ ├── cache/ [impl] scratch (safe to delete)
117
+ └── plots/ [impl] optional tool exports
118
+
119
+ ================================================================================
120
+ ASSAY HDF5 LAYOUT (backend = hdf5_sparse / CSC)
121
+ ================================================================================
122
+
123
+ <assay>.h5
124
+ └── counts/ (or configured group name)
125
+ ├── data numeric non-zeros
126
+ ├── indices 0-based row indices
127
+ ├── indptr CSC column pointers
128
+ ├── shape [n_features, n_cells]
129
+ ├── feature_ids (optional) gene / peak ids
130
+ └── cell_ids (optional) cell barcodes
131
+
132
+ Virtual multi-sample assays keep one H5 per sample under
133
+ modalities/<mod>/assays/<assay>/<sample_id>/<sample_id>.h5
134
+ and a virtual handle in the S4 object (no mega-merge by default).
135
+
136
+ ================================================================================
137
+ S4 OBJECT (handle-only) ↔ SODA
138
+ ================================================================================
139
+
140
+ iCellR2
141
+ ├── project_info ← metadata/project_info.json
142
+ ├── samples ← metadata/sample_data.tsv
143
+ ├── cell_data ← metadata/cell_data.tsv
144
+ ├── modalities
145
+ │ └── <mod>
146
+ │ ├── assays$* ← modalities/<mod>/assays/<name>/*.h5 (handles only)
147
+ │ ├── active_assay
148
+ │ ├── feature_data← metadata/<mod>_feature_data.tsv
149
+ │ ├── reductions ← reductions/<name>/ (paths + light metadata)
150
+ │ ├── gene.data ← metadata/<mod>_gene_stats.*
151
+ │ ├── gene.model ← metadata/<mod>_gene_model.*
152
+ │ ├── sketches ← modalities/<mod>/sketches/
153
+ │ ├── graphs ← [planned]
154
+ │ ├── markers ← [planned]
155
+ │ └── misc
156
+ ├── multimodal ← multimodal/ [impl]
157
+ ├── reductions ← often mirrored under modalities; top-level paths in storage
158
+ ├── graphs ← graphs/ [planned]
159
+ ├── storage
160
+ │ ├── root_dir ← path to this *.soda
161
+ │ ├── backend ← "hdf5_sparse" (default)
162
+ │ ├── modality_paths
163
+ │ ├── metadata_paths
164
+ │ ├── reduction_paths
165
+ │ ├── graph_paths
166
+ │ ├── image_paths
167
+ │ ├── molecule_paths
168
+ │ ├── segment_paths
169
+ │ ├── chunk_index
170
+ │ ├── cache
171
+ │ └── compression
172
+ ├── commands ← metadata/commands.json
173
+ ├── params ← metadata/params.json
174
+ ├── version ← metadata/version.json
175
+ ├── misc ← in-memory / optional RDS under metadata/
176
+ └── validity ← [planned] valid / checked / messages / schema_notes
177
+
178
+ ================================================================================
179
+ MODALITY SCHEMAS (conceptual; folders under modalities/)
180
+ ================================================================================
181
+
182
+ rna/ [impl]
183
+ assays: counts, data (normalized), scale.data, layers…
184
+ feature_data: feature_id, feature_name, feature_type, chromosome, start, end, strand
185
+ reductions: pca, umap, tsne, cgmap/cgpca/cgumap, knetl, projected_umap…
186
+ graphs / sketches / markers / models / params / misc
187
+
188
+ atac/ [impl]
189
+ assays: counts, tfidf, gene.activity
190
+ merge.peaks first: one chr_start_end set when samples disagree
191
+ add.atac, norm.atac, gene.activity, add.multiome, atac.rna.merge
192
+ reductions: pca (modalities/atac/reductions/pca), umap
193
+ RNA reductions/pca is never replaced. Joint map is multimodal/rna_atac.
194
+ motifs: motif_matrix, motif_annotations, chromvar_scores
195
+ peaks / sketches / params / misc
196
+
197
+ adt/ [impl]
198
+ assays: counts, data (per-cell CLR), layers…
199
+ feature_data: feature_id, feature_name, feature_type
200
+
201
+ vdj/ [planned]
202
+ contigs, clonotypes, chains, repertoire, feature_data
203
+
204
+ spatial/ | visium/ | xenium/ [planned]
205
+ assays + coordinates, images, scalefactors, segments / spots / polygons, molecules
206
+
207
+ proteomics/ [planned]
208
+ assays: intensities, normalized, layers…
209
+ feature_data: protein_id, protein_name, peptide_count
210
+
211
+ misc_modalities/ [planned]
212
+
213
+ ================================================================================
214
+ MULTIMODAL / GLOBAL REDUCTIONS / GRAPHS
215
+ ================================================================================
216
+
217
+ multimodal/
218
+ rna_atac, rna_adt, rna_spatial, rna_visium, rna_xenium, multiome, misc
219
+ └── multimodal.json, joint_pca/cell_embeddings.h5
220
+ Batch alignment is reductions/aligned_pca, not this folder.
221
+
222
+ reductions/ (also used for modality-local today)
223
+ integrated_pca, integrated_umap, integrated_tsne, integrated_knetl, misc
224
+
225
+ graphs/
226
+ integrated_knn, integrated_snn, wnn, misc
227
+
228
+ ================================================================================
229
+ NOTES
230
+ ================================================================================
231
+
232
+ 1. No .rds in SODA. Write .json / .tsv / .h5 / .parquet / .txt|.log|.info (.uwot for UMAP).
233
+ Legacy .rds is readable once for migration, then removed.
234
+ 2. Assays are never densified into the S4 object; stream via assay handles.
235
+ 3. `soda.info` replaced legacy `soda.tsv` (open.soda still reads .tsv if present).
236
+ 4. Plot tools may write HTML/PNG beside the working directory or under plots/;
237
+ they do not densify assays.
238
+ 5. Empty reserved folders (images/, molecules/, segments/, graphs/, …) may exist
239
+ as placeholders created at make.obj time.