Skip to content

Python client and API for accessing PIASOmarkerDB

Python client and API for accessing PIASOmarkerDB

import piaso
stderr
.../site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm
import numpy as np
import pandas as pd
import scanpy as sc
sc.set_figure_params(dpi=80,dpi_save=300, color_map='viridis',facecolor='white')
from matplotlib import rcParams
# To modify the default figure size, use rcParams.
rcParams['figure.figsize'] = 4, 4
rcParams['font.sans-serif'] = "Arial"
rcParams['font.family'] = "Arial"
sc.settings.verbosity = 3
sc.logging.print_header()
stderr
/tmp/ipykernel_4126893/1353975569.py:11: RuntimeWarning: Failed to import dependencies for application/vnd.jupyter.widget-view+json representation. (ModuleNotFoundError: No module named 'ipywidgets')
sc.logging.print_header()
| Dependency | Version |
| ------------------ | --------------------- |
| h5py | 3.15.1 |
| tqdm | 4.67.1 |
| stack_data | 0.6.3 |
| wcwidth | 0.2.13 |
| pillow | 12.0.0 |
| joblib | 1.5.3 |
| requests | 2.32.5 |
| debugpy | 1.8.16 |
| texttable | 1.7.0 |
| kiwisolver | 1.4.9 |
| asttokens | 3.0.0 |
| six | 1.17.0 |
| natsort | 8.4.0 |
| pure_eval | 0.2.3 |
| charset-normalizer | 3.4.4 |
| python-dateutil | 2.9.0.post0 |
| torch | 2.9.1 (2.9.1+cu128) |
| tornado | 6.5.4 |
| parso | 0.8.5 |
| pytz | 2025.2 |
| leidenalg | 0.10.2 |
| jedi | 0.19.2 |
| networkx | 3.4.2 |
... [21 more lines]
path = '.../Analysis/Jupyter/Python/Longitudinal/Integration'
import sys
sys.path.append(path)
from env_settings import *
sc.set_figure_params(dpi=80,dpi_save=300, color_map='viridis',facecolor='white')
rcParams['figure.figsize'] = 4, 4
save_dir='.../Result/single-cell/Methods/COSG/Database'
### Create the save_dir if not existed
!mkdir -p {save_dir}
adata=sc.read('.../Result/single-cell/Enhancer/AdultCortexMultiome/AdultCortexMultiomeRNA_integrated_anno.h5ad')
sc.pl.umap(adata,
color=['CellTypes'],
palette=self_palette2,
# legend_loc='on data',
legend_fontoutline=2,
legend_fontweight=5,
cmap='Spectral_r',
ncols=3,
size=10,
frameon=False)
output
marker_df = piaso.tl.queryPIASOmarkerDB(gene="Fezf2")
marker_df.head(10)
marker_df = piaso.tl.queryPIASOmarkerDB(gene=["Fezf2", "Satb2", "Tbr1"])
marker_df.head(10)
marker_df = piaso.tl.queryPIASOmarkerDB(
study="AllenWholeMouseBrain_isocortex",
species="mouse",
# limit=10
)
marker_df
marker_df = piaso.tl.queryPIASOmarkerDB(
species="Human",
min_score=8.0,
limit=100
)
marker_df.head(20)
marker_df, marker_dict = piaso.tl.queryPIASOmarkerDB(
study='AllenWholeMouseBrain_isocortex',
# species="Human",
# min_score=3.0,
# limit=500,
as_dict=True
)
print(f"DataFrame shape: {marker_df.shape}")
print(f"Cell types in dict: {len(marker_dict)}")
# Show sample
for ct, genes in list(marker_dict.items())[:3]:
print(f"\n {ct}:")
print(f" Markers: {genes[:5]}...")
DataFrame shape: (1300, 7)
Cell types in dict: 26
056 Sst Chodl Gaba:
Markers: ['Chodl', 'Krt18', 'P2rx2', '4930545L08Rik', 'Tacr1']...
051 Pvalb chandelier Gaba:
Markers: ['Vmn1r209', 'Vmn1r207-ps', 'Dbhos', 'Nkx2-1', 'Sfta3-ps']...
330 VLMC NN:
Markers: ['Slc22a6', 'Aldh1a2', 'Slc13a4', 'Fam180a', 'Lum']...
studies = piaso.tl.queryPIASOmarkerDB(list_studies=True)
print(f"Total studies: {len(studies)}")
print("First 10 studies:")
for study in studies[:10]:
print(f" - {study}")
Total studies: 36
First 10 studies:
- AllenAgeingBrainAtlas2025_supertype
- AllenDevVisualCortex2025_RNA
- AllenHumanImmuneHealthAtlas_L2
- AllenHumanImmuneHealthAtlas_L3
- AllenWholeMouseBrain_GABA
- AllenWholeMouseBrain_Neuron
- AllenWholeMouseBrain_NonNeuron
- AllenWholeMouseBrain_isocortex
- AsianImmuneDiversityAtlasPhase1v2_5prime
- DiBellaArlotta2021
def example_analyze_single_list():
"""Demonstrate single gene list analysis."""
print("\n" + "="*60)
print("Example 4: Analyze Single Gene List")
print("="*60)
# T-cell marker genes
t_cell_genes = ["CD3E", "CD3D", "CD8A", "GZMK", "PRF1", "IFNG"]
print(f"\n--- Analyzing genes: {t_cell_genes} ---")
df = piaso.tl.analyzeMarkers(t_cell_genes, species="Human")
print(f"Found {len(df)} cell type matches")
if len(df) > 0:
print("\nTop 5 matches:")
print(df[['cell_type', 'matched_gene_count', 'avg_specificity']].head())
query_genes = ["Syt6", "Tle4", "Hs3st4", "Col6a1", "Zfpm2", "Sema5a", "Bcl11b", "Fezf2", "Foxp2", "Col12a1"]
print(f"\n--- Analyzing genes: {query_genes} ---")
marker_df = piaso.tl.analyzeMarkers(query_genes)
marker_df.head()
--- Analyzing genes: ['Syt6', 'Tle4', 'Hs3st4', 'Col6a1', 'Zfpm2', 'Sema5a', 'Bcl11b', 'Fezf2', 'Foxp2', 'Col12a1'] ---
gene_sets = {
'Cluster_0': ['Cx3cr1', 'P2ry12', 'Teme119', 'Csf1r', 'Itgam', 'Aif1', 'Trem2'],
'Cluster_1': ["Syt6", "Tle4", "Hs3st4", "Col6a1", "Zfpm2", "Sema5a", "Bcl11b", "Fezf2", "Foxp2", "Col12a1"],
}
print("\n--- Input Gene Sets ---")
for name, genes in gene_sets.items():
print(f" {name}: {genes}")
print("\n--- Analyzing... ---")
# results, top_hits = piaso.tl.analyzeMarkers(gene_sets, species="Mouse")
results, top_hits = piaso.tl.analyzeMarkers(gene_sets)
print("\nCell Type Predictions:")
for cluster, cell_type in top_hits.items():
print(f" {cluster}: {cell_type}")
# Show detailed results
print(f"\n--- Detailed results for Cluster_0 ---")
if 'Cluster_0' in results and len(results['Cluster_0']) > 0:
print(results['Cluster_0'][['cell_type', 'matched_gene_count', 'avg_specificity', 'study_publication']].head())
print(f"\n--- Detailed results for Cluster_1 ---")
if 'Cluster_0' in results and len(results['Cluster_1']) > 0:
print(results['Cluster_1'][['cell_type', 'matched_gene_count', 'avg_specificity', 'study_publication']].head())
--- Input Gene Sets ---
Cluster_0: ['Cx3cr1', 'P2ry12', 'Teme119', 'Csf1r', 'Itgam', 'Aif1', 'Trem2']
Cluster_1: ['Syt6', 'Tle4', 'Hs3st4', 'Col6a1', 'Zfpm2', 'Sema5a', 'Bcl11b', 'Fezf2', 'Foxp2', 'Col12a1']
--- Analyzing... ---
Cell Type Predictions:
Cluster_0: Microglia
Cluster_1: EN-L6-CT
--- Detailed results for Cluster_0 ---
cell_type matched_gene_count avg_specificity \
0 Microglia 5 13.000120
1 Mgl_9 5 7.875872
2 5312_Microglia NN_1 4 8.265331
3 P2RY12+ microglia 4 7.782557
4 Mgl_11 4 7.375123
study_publication
0 DiBellaArlotta2021
1 SilettiLinnarssonWholeHumanBrain2023_subtype
2 AllenDevVisualCortex2025_RNA
3 XuTeichmann2023_HippocampalFormation
4 SilettiLinnarssonWholeHumanBrain2023_subtype
... [14 more lines]
import cosg
%%time
groupby='CellTypes'
cosg.cosg(adata,
key_added='cosg',
use_raw=False, layer='log1p', ## e.g., if you want to use the log1p layer in adata
mu=100,
expressed_pct=0.1,
remove_lowly_expressed=True,
n_genes_user=adata.n_vars, ### Use all the genes, to enable the calculation of transformed COSG scores
# n_genes_user=100,
groupby=groupby,
return_by_group=True,
verbosity=1
)
Finished identifying marker genes by COSG, and the results are in adata.uns['cosg'].
CPU times: user 2.54 s, sys: 366 ms, total: 2.9 s
Wall time: 2.91 s
cosg_marker_df=pd.DataFrame(adata.uns['cosg']['names']).head(50)
cosg_marker_df.head()
%%time
results, top_hits = piaso.tl.analyzeMarkers(
cosg_marker_df,
n_top_genes=50,
species="mouse",
)
CPU times: user 576 ms, sys: 19.5 ms, total: 596 ms
Wall time: 3.56 s
print("\nCell Type Predictions:")
for cluster, cell_type in top_hits.items():
print(f" {cluster}: {cell_type}")
Cell Type Predictions:
L2-3 IT: 007 L2/3 IT CTX Glut
L4 IT: 100_L4/5 IT CTX Glut_6
L4-5 IT: L4/5 IT CTX Glut_4
L5 IT: 005 L5 IT CTX Glut
L5 NP: 032 L5 NP CTX Glut
L5 PT: 022 L5 ET CTX Glut
L6 IT: 004 L6 IT CTX Glut
L6 IT Car3: 001 CLA-EPd-CTX Car3 Glut
L6 CT: 437_L6 CT CTX Glut_1
L6b: 029 L6b CTX Glut
PV: 052 Pvalb Gaba
SST: Sst Gaba_7
VIP: 046 Vip Gaba
LAMP5: 049 Lamp5 Gaba
Astrocyte: 319 Astro-TE NN
OPC: OPC NN_1
Oligodendrocyte: 327 Oligo NN
Microglia: 334 Microglia NN
Macrophage: 335 BAM NN
Endothelial: Endo_Flt1
results['L2-3 IT'].head(5)
adata.obs['Tophits_piasomarkerdb']=adata.obs['CellTypes'].map(top_hits)
sc.pl.umap(adata,
color=['Tophits_piasomarkerdb'],
palette=piaso.pl.color.d_color10,
# legend_loc='on data',
legend_fontoutline=2,
legend_fontweight=5,
cmap='Spectral_r',
ncols=3,
size=10,
frameon=False)
output
sc.pl.umap(adata,
color=['CellTypes'],
palette=piaso.pl.color.d_color4,
# legend_loc='on data',
legend_fontoutline=2,
legend_fontweight=5,
cmap='Spectral_r',
ncols=3,
size=10,
frameon=False)
output
piaso.pl.plotConfusionMatrix(adata, 'Tophits_piasomarkerdb', 'CellTypes', figsize=(10, 8))
output
%%time
results, top_hits = piaso.tl.analyzeMarkers(
cosg_marker_df,
n_top_genes=50,
min_genes=5,
studies=['AllenWholeMouseBrain_isocortex'],
species="mouse"
)
CPU times: user 461 ms, sys: 7.07 ms, total: 469 ms
Wall time: 3.58 s
top_hits
{'L2-3 IT': '007 L2/3 IT CTX Glut',
'L4 IT': '006 L4/5 IT CTX Glut',
'L4-5 IT': '006 L4/5 IT CTX Glut',
'L5 IT': '005 L5 IT CTX Glut',
'L5 NP': '032 L5 NP CTX Glut',
'L5 PT': '022 L5 ET CTX Glut',
'L6 IT': '004 L6 IT CTX Glut',
'L6 IT Car3': '001 CLA-EPd-CTX Car3 Glut',
'L6 CT': '030 L6 CT CTX Glut',
'L6b': '029 L6b CTX Glut',
'PV': '052 Pvalb Gaba',
'SST': '053 Sst Gaba',
'VIP': '046 Vip Gaba',
'LAMP5': '049 Lamp5 Gaba',
'Astrocyte': '319 Astro-TE NN',
'OPC': '326 OPC NN',
'Oligodendrocyte': '327 Oligo NN',
'Microglia': '334 Microglia NN',
'Macrophage': '335 BAM NN',
'Endothelial': '333 Endo NN'}
adata.obs['Tophits_piasomarkerdb_AllenWholeMouseBrain_isocortex']=adata.obs['CellTypes'].map(top_hits)
sc.pl.umap(adata,
color=[
'Tophits_piasomarkerdb_AllenWholeMouseBrain_isocortex',
'Tophits_piasomarkerdb'
],
palette=piaso.pl.color.d_color10,
# legend_loc='on data',
legend_fontoutline=2,
legend_fontweight=5,
cmap='Spectral_r',
ncols=1,
size=10,
frameon=False)
output
sc.pl.umap(adata,
color=['CellTypes'],
palette=piaso.pl.color.d_color4,
# legend_loc='on data',
legend_fontoutline=2,
legend_fontweight=5,
cmap='Spectral_r',
ncols=3,
size=10,
frameon=False)
output
piaso.pl.plotConfusionMatrix(adata, 'Tophits_piasomarkerdb_AllenWholeMouseBrain_isocortex', 'CellTypes', figsize=(10, 8))
output
client = piaso.tl.PIASOmarkerDB()
print(f"\nClient: {client}")
Client: PIASOmarkerDB(base_url='https://piaso.org/piasomarkerdb')
# Get all markers with pagination
print("\n--- Get all markers for a gene (with pagination) ---")
df = client.getAllMarkers(gene="Chrna2", verbose=True)
print(f"Total Chrna2 entries: {len(df)}")
df.head(10)
--- Get all markers for a gene (with pagination) ---
Fetching markers... batch 1 (32 records)
Total: 32 markers
Total Chrna2 entries: 32
# Get recommended study
print("\n--- Recommended Studies ---")
for species, tissue in [("human", "blood"), ("human", "brain"), ("human", "spleen")]:
study = client.getRecommendedStudy(species, tissue)
print(f" {species}/{tissue}: {study}")
--- Recommended Studies ---
human/blood: AllenHumanImmuneHealthAtlas_L2
human/brain: SilettiLinnarssonWholeHumanBrain2023_class
human/spleen: XuTeichmann2023_Spleen