Skip to content

Python client and API for accessing PIASOmarkerDB

Python client and API for accessing PIASOmarkerDB

import piaso
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()
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)
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]}...")
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}")
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()
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())
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
)
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",
)
print("\nCell Type Predictions:")
for cluster, cell_type in top_hits.items():
print(f" {cluster}: {cell_type}")
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)
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)
piaso.pl.plotConfusionMatrix(adata, 'Tophits_piasomarkerdb', 'CellTypes', figsize=(10, 8))
%%time
results, top_hits = piaso.tl.analyzeMarkers(
cosg_marker_df,
n_top_genes=50,
min_genes=5,
studies=['AllenWholeMouseBrain_isocortex'],
species="mouse"
)
top_hits
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)
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)
piaso.pl.plotConfusionMatrix(adata, 'Tophits_piasomarkerdb_AllenWholeMouseBrain_isocortex', 'CellTypes', figsize=(10, 8))
client = piaso.tl.PIASOmarkerDB()
print(f"\nClient: {client}")
# 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 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}")