Views
No views yet
app/pipeline/inference.py. Specifically, the following code snippet shows how to use it:1from stpath.app.pipeline.inference import STPathInference
2
3agent = STPathInference(
4 gene_voc_path='STPath_dir/utils_data/symbol2ensembl.json',
5 model_weight_path='your_dir/stpath.pkl',
6 device=0
7)
8
9pred_adata = agent.inference(
10 coords=coords, # [number_of_spots, 2]
11 img_features=embeddings, # [number_of_spots, 1536], the image features extracted using Gigapath
12 organ_type="Kidney", # Default is None
13 tech_type="Visium", # Default is None
14 save_gene_names=hvg_list # a list of gene names to save in the adata, e.g., ['GATA3', 'UBLE2C', ...]. None will save all genes in the model.
15)
16
17# save adata
18pred_adata.write_h5ad(f"your_dir/pred_{sample_id}.h5ad")None in the inference function. Besides, the predicted gene expression values are log1p-transformed (log(1 + x)), consistent with the transformation applied during the training of STPath.1from scipy.stats import pearsonr
2from stpath.hest_utils.st_dataset import load_adata
3from stpath.hest_utils.file_utils import read_assets_from_h5
4
5sample_id = "INT2"
6source_dataroot = "STPath_dir" # the root directory of the STPath repository
7with open(os.path.join(source_dataroot, "example_data/var_50genes.json")) as f:
8 hvg_list = json.load(f)['genes']
9
10data_dict, _ = read_assets_from_h5(os.path.join(source_dataroot, f"{sample_id}.h5")) # load the data from the h5 file
11coords = data_dict["coords"]
12embeddings = data_dict["embeddings"]
13barcodes = data_dict["barcodes"].flatten().astype(str).tolist()
14adata = sc.read_h5ad(os.path.join(source_dataroot, f"{sample_id}.h5ad"))[barcodes, :]
15
16# The return pred_adata includes the expressions of the genes in hvg_list, which is a list of highly variable genes.
17pred_adata = agent.inference(
18 coords=coords,
19 img_features=embeddings,
20 organ_type="Kidney",
21 tech_type="Visium",
22 save_gene_names=hvg_list # we only need the highly variable genes for evaluation
23)
24
25# calculate the Pearson correlation coefficient between the predicted and ground truth gene expression
26all_pearson_list = []
27gt = np.log1p(adata[:, hvg_list].X.toarray()) # sparse -> dense
28# go through each gene in the highly variable genes list
29for i in range(len(hvg_list)):
30 pearson_corr, _ = pearsonr(gt[:, i], pred_adata.X[:, i])
31 all_pearson_list.append(pearson_corr.item())
32print(f"Pearson correlation for {sample_id}: {np.mean(all_pearson_list)}") # 0.15621from stpath.data.sampling_utils import PatchSampler
2
3rightest_coord = np.where(coords[:, 0] == coords[:, 0].max())[0][0]
4masked_ids = PatchSampler.sample_nearest_patch(coords, int(len(coords) * 0.95), rightest_coord) # predict the expression of the 95% spots
5context_ids = np.setdiff1d(np.arange(len(coords)), masked_ids) # the index not in masked_ids will be used as context
6context_gene_exps = adata.X.toarray()[context_ids]
7context_gene_names = adata.var_names.tolist()
8
9pred_adata = agent.inference(
10 coords=coords,
11 img_features=embeddings,
12 context_ids=context_ids, # the index of the context spots
13 context_gene_exps=context_gene_exps, # the expression of the context spots
14 context_gene_names=context_gene_names, # the gene names of the context spots
15 organ_type="Kidney",
16 tech_type="Visium",
17 save_gene_names=hvg_list,
18)
19
20all_pearson_list = []
21gt = np.log1p(adata[:, hvg_list].X.toarray())[masked_ids, :] # groundtruth expression of the spots in masked_ids
22pred = pred_adata.X[masked_ids, :] # predicted expression of the spots in masked_ids
23for i in range(len(hvg_list)):
24 pearson_corr, _ = pearsonr(gt[:, i], pred[:, i])
25 all_pearson_list.append(pearson_corr.item())
26print(f"Pearson correlation for {sample_id}: {np.mean(all_pearson_list)}") # 0.2449@inproceedings{huang2025stflow,
title={Scalable Generation of Spatial Transcriptomics from Histology Images via Whole-Slide Flow Matching},
author={Huang, Tinglin and Liu, Tianyu and Babadi, Mehrtash and Jin, Wengong and Ying, Rex},
booktitle={International Conference on Machine Learning},
year={2025}
}
@article{huang2025stpath,
title={STPath: A Generative Foundation Model for Integrating Spatial Transcriptomics and Whole Slide Images},
author={Huang, Tinglin and Liu, Tianyu and Babadi, Mehrtash and Ying, Rex and Jin, Wengong},
journal={bioRxiv},
pages={2025--04},
year={2025},
publisher={Cold Spring Harbor Laboratory}
}