pase-framework 1.0.0__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.
pase/datasets.py ADDED
@@ -0,0 +1,49 @@
1
+ """Small real-data examples supplied with PASE."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from importlib.resources import files
7
+ from io import BytesIO, StringIO
8
+ import hashlib
9
+ import json
10
+
11
+ from anndata import AnnData
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+
16
+ def load_gse234933_demo() -> AnnData:
17
+ """Load a small real GSE234933 myeloid-cell subset without network access.
18
+
19
+ Returns
20
+ -------
21
+ AnnData
22
+ ``X`` is log1p(CP10K) based on each cell's FULL original gene library.
23
+ ``layers['counts']`` contains untransformed counts for the included genes;
24
+ these genes alone MUST NOT be used to recalculate library sizes.
25
+ ``obs`` retains original barcodes, donor/specimen labels, ``myeloid``,
26
+ ``full_library_size`` and ``log_depth``. ``uns['dataset']`` supplies the
27
+ source, extraction rules, source checksums and third-party data notice.
28
+
29
+ Notes
30
+ -----
31
+ This teaching subset does not reproduce the full-cohort manuscript analysis.
32
+ It is selected without consulting gene correlations. Each call returns an
33
+ independent in-memory object. Files are checked against their SHA-256 manifest.
34
+ """
35
+ root = files("pase").joinpath("data")
36
+ manifest = json.loads(root.joinpath("gse234933_demo_manifest.json").read_text(encoding="utf-8"))
37
+ content = {}
38
+ for name, expected in manifest["outputs_sha256"].items():
39
+ value = root.joinpath(name).read_bytes()
40
+ if hashlib.sha256(value).hexdigest() != expected:
41
+ raise RuntimeError(f"Packaged tutorial data checksum mismatch: {name}")
42
+ content[name] = value
43
+ with np.load(BytesIO(content["gse234933_demo.npz"]), allow_pickle=False) as stored:
44
+ x, counts, genes = stored["X"].copy(), stored["counts"].copy(), stored["genes"].astype(str)
45
+ obs = pd.read_csv(StringIO(content["gse234933_demo_obs.tsv"].decode("utf-8")), sep="\t", index_col="barcode")
46
+ obs["myeloid"] = obs["myeloid"].astype(bool)
47
+ var = pd.DataFrame(index=pd.Index(genes, name="gene"))
48
+ var["spp1_tam_signature"] = var.index.isin(manifest["spp1_tam_genes"])
49
+ return AnnData(X=x, obs=obs, var=var, layers={"counts": counts}, uns={"dataset": deepcopy(manifest)})
pase/result.py ADDED
@@ -0,0 +1,102 @@
1
+ """Inspectable results and a forest plot for a single association analysis."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+
10
+ class AssociationResult:
11
+ """Patient effects, cohort summary, and the settings used to obtain them.
12
+
13
+ ``patients`` includes excluded patients and their reasons. ``metadata``
14
+ describes preprocessing, the statistical target, and relevant limitations.
15
+ Individual raw correlations have no attached confidence interval. For
16
+ ``aggregate='eb'``, individual intervals condition on fitted population
17
+ parameters and do not include their estimation uncertainty.
18
+ """
19
+
20
+ def __init__(self, patients: pd.DataFrame, summary: dict, metadata: dict):
21
+ self.patients = patients.copy(deep=True)
22
+ self._summary = deepcopy(summary)
23
+ self.metadata = deepcopy(metadata)
24
+
25
+ def summary(self) -> pd.DataFrame:
26
+ """Return a one-row table; withheld inference is represented by NaN.
27
+
28
+ ``status`` and ``reason`` distinguish technical failure, a user-selected
29
+ patient threshold, and an available interval. An EB analysis has no
30
+ cohort estimate, confidence interval or P value in this table.
31
+ """
32
+ return pd.DataFrame([deepcopy(self._summary)])
33
+
34
+ def plot_forest(self, ax=None, *, title=None, include_excluded=True):
35
+ """Plot patient correlations and, when available, the cohort interval.
36
+
37
+ Parameters
38
+ ----------
39
+ ax : matplotlib.axes.Axes, optional
40
+ Axes to draw on. A new figure is created if omitted.
41
+ title : str, optional
42
+ Override the automatically generated title.
43
+ include_excluded : bool, default True
44
+ Show excluded patient names with their exclusion reasons.
45
+
46
+ Returns
47
+ -------
48
+ matplotlib.axes.Axes
49
+ The axes containing the forest plot.
50
+ """
51
+ import matplotlib.pyplot as plt
52
+
53
+ table = self.patients
54
+ if not include_excluded:
55
+ table = table.loc[table["eligible"]]
56
+ table = table.reset_index(drop=True)
57
+ is_eb = self._summary["method"] == "eb"
58
+ has_summary = self._summary["status"] == "reported" and not is_eb
59
+ total_rows = len(table) + int(has_summary)
60
+ if ax is None:
61
+ _, ax = plt.subplots(figsize=(7.0, max(3.0, 0.3 * total_rows + 1.5)))
62
+ labels = []
63
+ for position, row in table.iterrows():
64
+ label = str(row["patient_id"])
65
+ if not row["eligible"]:
66
+ label += " (" + str(row["reason"]).replace("_", " ") + ")"
67
+ labels.append(label)
68
+ if pd.notna(row["r"]):
69
+ ax.plot(row["r"], position, "o", color="#999999" if is_eb or not row["eligible"]
70
+ else "#176B91", markersize=4, zorder=3)
71
+ if is_eb and pd.notna(row["eb_estimate"]):
72
+ if pd.notna(row["eb_ci_low"]) and pd.notna(row["eb_ci_high"]):
73
+ ax.plot([row["eb_ci_low"], row["eb_ci_high"]], [position, position],
74
+ color="#B26419", linewidth=1.3)
75
+ ax.plot(row["eb_estimate"], position, "D", color="#B26419", markersize=4)
76
+ if has_summary:
77
+ row = self._summary
78
+ position = len(table)
79
+ ax.plot([row["ci_low"], row["ci_high"]], [position, position], color="#252525", lw=1.8)
80
+ ax.plot(row["estimate"], position, "D", color="#252525", markersize=6)
81
+ labels.append("Equal-patient mean" if row["method"] == "equal" else "REML + HKSJ")
82
+ ax.axvline(0, color="#777777", lw=0.8, ls="--", zorder=0)
83
+ ax.set_yticks(np.arange(len(labels)), labels=labels)
84
+ ax.set_ylim(len(labels) - 0.4, -0.8)
85
+ ax.set_xlabel("Patient-level correlation")
86
+ default_title = f"{self.metadata['anchor']} and {self.metadata['target_label']}"
87
+ if is_eb:
88
+ default_title += "\nEB diamonds; conditional intervals; grey observed effects"
89
+ elif not has_summary:
90
+ default_title += "\nCohort inference withheld: " + self._summary["reason"].replace("_", " ")
91
+ ax.set_title(title if title is not None else default_title)
92
+ for side in ("top", "right"):
93
+ ax.spines[side].set_visible(False)
94
+ ax.grid(axis="x", color="#dddddd", lw=0.5)
95
+ ax.figure.tight_layout()
96
+ return ax
97
+
98
+ def __repr__(self):
99
+ return (f"AssociationResult(method={self._summary['method']!r}, "
100
+ f"patients={len(self.patients)}, "
101
+ f"eligible={self._summary['n_patients_eligible']}, "
102
+ f"status={self._summary['status']!r})")
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: pase-framework
3
+ Version: 1.0.0
4
+ Summary: Patient-level association estimates for multi-patient single-cell studies
5
+ Author: Jinwei Tang, Yunfan Lin, Linrui Cai, Yali Wen, Guangyang Chen, Li Huang
6
+ License-Expression: MIT
7
+ Project-URL: Source, https://github.com/tjw0613-cell/pase-software
8
+ Project-URL: Issues, https://github.com/tjw0613-cell/pase-software/issues
9
+ Project-URL: Reproduction, https://github.com/tjw0613-cell/pase-reproducibility
10
+ Keywords: single-cell,association,patient,correlation,meta-analysis
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ License-File: src/pase/data/DATA_NOTICE.md
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: scipy>=1.10
26
+ Requires-Dist: pandas>=2.0
27
+ Requires-Dist: anndata>=0.10
28
+ Requires-Dist: matplotlib>=3.7
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest>=8; extra == "test"
31
+ Provides-Extra: tutorial
32
+ Requires-Dist: jupyterlab>=4; extra == "tutorial"
33
+ Requires-Dist: nbformat>=5; extra == "tutorial"
34
+ Requires-Dist: nbclient>=0.10; extra == "tutorial"
35
+ Requires-Dist: ipykernel>=6; extra == "tutorial"
36
+ Provides-Extra: docs
37
+ Requires-Dist: sphinx>=7; extra == "docs"
38
+ Requires-Dist: myst-parser>=3; extra == "docs"
39
+ Requires-Dist: sphinx-rtd-theme>=3; extra == "docs"
40
+ Provides-Extra: build
41
+ Requires-Dist: build>=1.2; extra == "build"
42
+ Requires-Dist: twine>=6; extra == "build"
43
+ Dynamic: license-file
44
+
45
+ # PASE
46
+
47
+ PASE estimates molecular associations within individual patients and summarizes them across a single-cell cohort.
48
+
49
+ ## Installation
50
+
51
+ Use Python 3.10 or later in a fresh environment. From this source checkout:
52
+
53
+ ```bash
54
+ git clone https://github.com/tjw0613-cell/pase-software.git
55
+ cd pase-software
56
+ python -m venv .venv
57
+ # Windows: .venv\Scripts\activate
58
+ # macOS/Linux: source .venv/bin/activate
59
+ python -m pip install .
60
+ ```
61
+
62
+ The distribution is named **pase-framework**, but the Python import is `pase`.
63
+ The unrelated audio package named `pase` on PyPI uses the same import name;
64
+ do not install both in one environment. This source release does not by itself
65
+ confirm availability on PyPI.
66
+
67
+ ## Five-line example
68
+
69
+ ```python
70
+ import pase
71
+ adata = pase.datasets.load_gse234933_demo()
72
+ res = pase.associate(adata, anchor="LILRB4", target=["MMP14", "MMP9", "SPP1", "APOE"], patient_key="donor", covariates=["log_depth"], cell_mask="myeloid", aggregate="equal", min_cells=30)
73
+ print(res.summary())
74
+ res.plot_forest()
75
+ ```
76
+
77
+ The bundled GSE234933 subset contains real cells and works without a download.
78
+ The four-gene target above illustrates the interface; it is not the current
79
+ manuscript's published 15-gene signature. The complete tutorial is
80
+ [examples/gse234933_quickstart.ipynb](examples/gse234933_quickstart.ipynb).
81
+ Install the notebook tools with `python -m pip install ".[tutorial]"`, then run
82
+ `jupyter lab examples/gse234933_quickstart.ipynb`.
83
+
84
+ ## Input format
85
+
86
+ Supply an AnnData object with cells in rows and unique gene names in
87
+ `adata.var_names`. `adata.X`, or the requested `layer`, must already contain
88
+ transformed expression. For count data, the tutorial uses
89
+ `log1p(10000 * count / total_counts)` with totals calculated **before** selecting
90
+ genes. `associate` does not normalize raw counts.
91
+
92
+ | Input | Meaning |
93
+ |---|---|
94
+ | `adata.obs["donor"]` | Independent patient ID, with no missing values. Repeated samples from one patient must share an ID. |
95
+ | `adata.obs["log_depth"]` | Numeric covariate; the tutorial uses `log1p(total_counts)` from the full matrix. |
96
+ | `adata.obs["myeloid"]` | Boolean cell-selection column. Patients with no selected cells remain in the output. |
97
+ | `anchor` | One gene name. |
98
+ | `target` | One gene name, or a list whose within-patient gene z scores are averaged. |
99
+
100
+ Covariates enter a separate least-squares model for each patient, with an
101
+ intercept. Numeric categorical encodings must be supplied explicitly.
102
+ Patients absent from the object can be retained using `patient_ids`.
103
+ See [the input guide](docs/inputs.md) for missing values and eligibility rules.
104
+
105
+ ## Outputs and choice of summary
106
+
107
+ `res.patients` reports every patient, cell counts, observed correlation,
108
+ eligibility, exclusion reasons and, where applicable, weights or shrunken effects.
109
+ `res.summary()` returns one row with the selected method, target, estimate,
110
+ interval, P value and status. `res.metadata` records the analysis settings and
111
+ warnings. `res.plot_forest()` returns a Matplotlib Axes.
112
+
113
+ | `aggregate` | What it reports |
114
+ |---|---|
115
+ | `"equal"` | Arithmetic mean of eligible patients' observed correlations, with a t interval. Each eligible patient has equal weight. |
116
+ | `"re_hksj"` | REML random-effects mean on the Fisher-z scale, back-transformed for display, with a classical HKSJ interval. It has a different target from the arithmetic mean. |
117
+ | `"eb"` | Individual patient effects shrunk toward the fitted Fisher-z population mean. Conditional intervals exclude uncertainty in fitted population parameters; no cohort P value is returned. |
118
+
119
+ `min_cells=30` is adjustable. `min_patients=2` is a technical minimum, **not a
120
+ validated recommendation for reliable inference**. Set a stricter reporting
121
+ threshold explicitly, for example `min_patients=6`. When that threshold is not
122
+ met, cohort estimates, intervals and P values are withheld, and the patient
123
+ records remain available. A configurable threshold does not establish its
124
+ statistical adequacy. See [statistical details](docs/statistics.md).
125
+
126
+ ## Citation
127
+
128
+ For this code, cite the authors, PASE software version **1.0.0**, and the release
129
+ URL or version DOI that accompanies the copy used. Machine-readable author
130
+ information is in [CITATION.cff](CITATION.cff). An earlier analysis archive is
131
+ available at [Zenodo v3](https://doi.org/10.5281/zenodo.23032874); that DOI does
132
+ not identify this 1.0.0 software release.
133
+
134
+ Code is distributed under the MIT License. The real-data example retains its
135
+ source attribution and third-party terms; see [THIRD_PARTY_DATA.md](THIRD_PARTY_DATA.md).
136
+
@@ -0,0 +1,15 @@
1
+ pase/__init__.py,sha256=uHzeKLoL7jm8mE9_KlSMZ6hbz_3JEZhUfr9_wgXum7c,273
2
+ pase/_statistics.py,sha256=zT7Nu2X_aXMgyExrPk5ZDDmjbVbKdOFtz-ktCvNyQWQ,11222
3
+ pase/association.py,sha256=Oq8QcX8hvbnrZZVlZW4udKt6jbhuF6U_4aXEbzt6ryg,20376
4
+ pase/datasets.py,sha256=4Ese6sjZCnJiFB5lyk5PORG04mkbBKdbYBmTsE4Sh6s,2217
5
+ pase/result.py,sha256=_pyB3XcCBWTkIdiMQqsEx8o343STjctds_UmQUBwgS8,4671
6
+ pase/data/DATA_NOTICE.md,sha256=fg0JVcUof2Q3yEtb-1bSG8gcKqKBE8buLeC7oDsBesA,2137
7
+ pase/data/gse234933_demo.npz,sha256=NBtQp9oRawh6vt6PKPQpvNY2GbS4S7I-NlcP-Y8G5fc,30506
8
+ pase/data/gse234933_demo_manifest.json,sha256=TUT8eIZibuGAUKyEkVGNAxRaYwOSYAFqQLFXXV1d4-I,5709
9
+ pase/data/gse234933_demo_obs.tsv,sha256=4Uh-U9Rnji_B0CRkEJpX5K2-2H6y2GQya8J4cNLbgZs,48174
10
+ pase_framework-1.0.0.dist-info/licenses/LICENSE,sha256=Abfz0U0qAwuSNPV4NqLC0LbsPcOkAxWaVe2UfTBBOCY,1133
11
+ pase_framework-1.0.0.dist-info/licenses/src/pase/data/DATA_NOTICE.md,sha256=fg0JVcUof2Q3yEtb-1bSG8gcKqKBE8buLeC7oDsBesA,2137
12
+ pase_framework-1.0.0.dist-info/METADATA,sha256=QTyKsk5jkiglT-zFmbp6CVX6tp1-1VqOtP3mj3BPs14,6387
13
+ pase_framework-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ pase_framework-1.0.0.dist-info/top_level.txt,sha256=b6JlLYt9DVSx7PIQXFUkOmdnqqip7CBtvBXW-CBTNB0,5
15
+ pase_framework-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jinwei Tang, Yunfan Lin, Linrui Cai, Yali Wen, Guangyang Chen, and Li Huang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,37 @@
1
+ # GSE234933 tutorial data
2
+
3
+ These small files contain selected, transformed observations from publicly
4
+ deposited third-party data. They are **not covered by PASE's MIT software license**,
5
+ and PASE's authors do not claim ownership of, or grant a new license to, the source
6
+ data. No patient names or inferred clinical attributes are included. The retained
7
+ specimen labels and cell barcodes are the identifiers deposited by the study.
8
+
9
+ Source: [GSE234933](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE234933),
10
+ public since 24 July 2023. Please cite:
11
+
12
+ Bill R, Wirapati P, Messemaker M, et al. CXCL9:SPP1 macrophage polarity identifies
13
+ a network of cellular programs that control human cancers. Science.
14
+ 2023;381:515-524. https://doi.org/10.1126/science.ade2292
15
+
16
+ GEO places no repository restrictions on use or distribution, while noting that
17
+ submitters may hold intellectual-property rights. See the
18
+ [GEO data-use terms](https://www.ncbi.nlm.nih.gov/geo/info/disclaimer.html).
19
+ Respect any applicable source-holder terms and acknowledge the source study in
20
+ subsequent use. Inclusion here does not imply endorsement by the source authors.
21
+
22
+ `gse234933_demo_manifest.json` lists the original input checksums, extraction
23
+ rules, dimensions and output checksums. `examples/build_gse234933_subset.py`
24
+ reconstructs these files from the deposited count archive and annotation table.
25
+ The sample uses only the author's broad myeloid annotation, positive library size
26
+ and deterministic cell sampling; it is not selected for a favorable association.
27
+
28
+ `X` is log1p(CP10K), with the denominator calculated from **all original genes**
29
+ before retaining the tutorial's genes. The reduced `counts` layer cannot recover
30
+ the full library by summing its columns. Use the supplied full library sizes.
31
+
32
+ The 15-gene SPP1-positive macrophage list is recorded in the manifest and can be
33
+ traced to https://doi.org/10.3389/fimmu.2021.694801. Using it in this software
34
+ tutorial does not recreate the source publication's scoring procedure.
35
+
36
+ This is a compact teaching dataset, not a replication of the full PASE paper or
37
+ an independent external validation cohort.
@@ -0,0 +1 @@
1
+ pase