expression histograms#
[1]:
%load_ext autoreload
%autoreload 2
from astropathdb import AstroDB, load_astrosample
from astropathdb import analysis as al
[2]:
db = AstroDB(database = 'apmifwsi001_DR2')
Describe how to extract just the data for the histogram and plot it#
show how to plot by sample, different cell type combinations, and in different regions of the tissue
similarly describe how to do this using the spatialdata object
need to be able to pass spatialdata into ‘get_expression_histogram’ below and ensure that the arguments are the same
create the plotting API that allows for using either method
[3]:
hist = al.get_expression_histogram(
astrodb = db,
opal = 'cmembrane540',
# ptype = {'phenotype': 'CD8'},
epsilon = 0
)
hist.plot(x = 'midpoints', y = 'density')
[3]:
<Axes: xlabel='midpoints'>
[4]:
hist = al.get_expression_histogram(
astrodb = db,
opal = 'meanmembrane540',
# ptype = {'phenotype': 'CD8'},
epsilon = 0,
table_name = 'cell'
)
hist1 = al.get_expression_histogram(
astrodb = db,
opal = 'meanmembrane540',
ptype = 'CD8',
epsilon = 0,
table_name = 'cell'
)
ax = hist.plot(x = 'midpoints', y = 'counts', color = 'blue')
hist1.plot(x = 'midpoints', y = 'counts', ax = ax, color = 'orange')
[4]:
<Axes: xlabel='midpoints'>
[5]:
hist = al.get_expression_histogram(
astrodb = db,
opal = 'meanentirecell540',
# ptype = {'phenotype': 'CD8'},
epsilon = 0,
table_name = 'cell'
)
hist1 = al.get_expression_histogram(
astrodb = db,
opal = 'meanentirecell540',
ptype = 'CD8',
epsilon = 0,
table_name = 'cell'
)
ax = hist.plot(x = 'midpoints', y = 'counts', color = 'blue')
hist1.plot(x = 'midpoints', y = 'counts', ax = ax, color = 'orange')
[5]:
<Axes: xlabel='midpoints'>
[6]:
hist = al.get_expression_histogram(
astrodb = db,
opal = 'meancytoplasm540',
# ptype = {'phenotype': 'CD8'},
epsilon = 0,
table_name = 'cell'
)
hist1 = al.get_expression_histogram(
astrodb = db,
opal = 'meancytoplasm540',
ptype = {'phenotype': 'CD8'},
epsilon = 0,
table_name = 'cell'
)
ax = hist.plot(x = 'midpoints', y = 'counts', color = 'blue')
hist1.plot(x = 'midpoints', y = 'counts', ax = ax, color = 'orange')
[6]:
<Axes: xlabel='midpoints'>
load spatialdata object and run get_expression_histogram
ptype, exprphenotype, opal
[7]:
sdata = load_astrosample(sampleid = 19, astrodb=db, cells_table = True)
[8]:
hist = al.get_expression_histogram(
sdata = sdata,
opal = 'cmembrane540',
ptype = {'ptype': 1},
table_name = 'sampleid_19_mIF',
epsilon = 0
)
[9]:
hist.plot(x = 'midpoints', y='density')
[9]:
<Axes: xlabel='midpoints'>
[10]:
import holoviews as hv
import holoviews.operation.datashader as hd
from holoviews import opts
#hv.extension('bokeh','matplotlib', width=100)
hv.extension('bokeh', width=400)
[11]:
hv.Curve(hist, kdims=['midpoints']).opts(width=500)
[11]:
next steps
improve filter flexibility in get_expression_histograms
move to a plotting class for the plots below
improve colorby flexibility outside of just phenotype
improve options defaults (labels, colors, etc) and capabilities
store the histogram dataframe in sdata if it is supplied
enable functionality on sdata
future thoughts
could move the entire computation scheme to dask dataframes for the queries
would store the dask dataframe instead of the actual data - would need to use a key based cache, but need to do that to store in sdata anyway for it to be functional at all
for opal
allow a list of opal inputs
allow for ‘all’, which auto-generates this list – in the sdata will use the sdata.var names – in database use the expression columns list for colorby
also allow for a string, a mapping, a list of both, or ‘all’ (‘all’ only for database)
for ‘all’ in database use the expression targets
for list allow for:
a ptype or exprphenotype name if using a database
a column name in obs for the sdata
a mapping of column name to value
For the mappings, check if the value is a mapping. If it is not re-configure; if it is a single value or tuple then set to the val; if it is a list then map to the correct arguments
change opal variable to target
[12]:
import pandas as pd
import scanpy as sc
[13]:
def get_histogram_plots(db, opal, colorby= None, include_all = True, **hist_kwargs):
#
if opal == 'all':
hists = []
for opal_ids, colorby_ids in zip(db.cellmeta.expression_columns, db.cellmeta.expression_targets):
dat = get_histogram_plots(db, opal=opal_ids, colorby=colorby_ids, include_all=include_all, **hist_kwargs)
hists.append(dat)
return pd.concat(hists)
#
hist_kwargs = dict(hist_kwargs)
#
hist_data = []
#
if include_all:
df = al.get_expression_histogram(astrodb=db, opal=opal, **hist_kwargs)
df['label'] = 'all cells'
hist_data.append(df)
#
if colorby is not None:
# improve flexibility here
if any(db.cellmeta.exprmarkers['target'].str.contains(colorby)):
colorby_dict = {'exprphenotype': {'phenotype': colorby}}
else:
colorby_dict = {'ptype': {'phenotype': colorby}}
#
hist_kwargs.update(colorby_dict)
df = al.get_expression_histogram(astrodb=db, opal=opal, **hist_kwargs)
df['label'] = '(+) cells'
hist_data.append(df)
#
colorby_dict[next(iter(colorby_dict))]['include'] = False
df = al.get_expression_histogram(astrodb=db, opal=opal, **hist_kwargs)
df['label'] = '(-) cells'
hist_data.append(df)
#
hist_data = pd.concat(hist_data)
hist_data['group'] = opal
#
return hist_data
For sdata
could use a list of column names and plot all unique in different colors
could check if it’s boolean for +/-
could use a mapping (multiple mappings not allowed)
[14]:
sdata['sampleid_19_mIF']
[14]:
AnnData object with n_obs × n_vars = 962920 × 6
obs: 'sampleid', 'cellid', 'ptype', 'exprphenotype', 'tdist', 'region', 'batchid'
var: 'targets'
uns: 'spatialdata_attrs', 'astropath_keys', 'sidus_attrs'
obsm: 'spatial'
layers: None (.X)
[15]:
df = get_histogram_plots(db, opal='all', colorby='PDL1', epsilon=0)
[16]:
db.sql
[16]:
'\n CREATE TABLE #flux (\n c bigint,\n flux float\n )\n insert into #flux\n \nSELECT \n count (*) as c, floor(\n log(centirecell690 + 0) / 0.05\n ) * 0.05 as flux\n \nFROM celltag \nWHERE ptype != 4 AND centirecell690 is not null and centirecell690 > 0 GROUP BY \n floor(log(centirecell690 + 0) /\n 0.05) * 0.05\n \n\n DECLARE @min int, @max int, @st int\n DECLARE @ss float = cast(0.05 as float)\n SELECT @Min=-5 ,@Max=5, @st=1/@ss\n declare @t table(\n id int IDENTITY(1,1),\n cellid bigint\n )\n insert into @t\n SELECT top ((@Max-@Min+1)*@st) cellid\n from dbo.celltag\n declare @allcells bigint = (select sum(c) allcells from #flux)\n select t.mids midpoints, COALESCE(c, 0) counts,\n COALESCE(cast(c as float), 0) / @allcells as density\n from #flux f right outer join (\n select (@min+(id/cast(@st as float))-@ss) mids, cellid\n from @t\n ) t on round(t.mids,2) = round(f.flux,2)\n order by 1\n '
[17]:
layout = []
for group in df['group'].unique():
#
df_s1 = df.loc[df['group'] == group]
overlays = []
#
for label in df_s1['label'].unique():
#
dims = {'kdims':('midpoints', group), 'vdims': 'counts', 'group': group}
#
df_s2 = df_s1.loc[df_s1['label'] == label]
#
overlays.append(hv.Area(df_s2, label=label, **dims))
#
layout.append(hv.Overlay(overlays))
layout=hv.Layout(layout)
[18]:
def thing(**kwargs):
for k,v in kwargs.items():
print(type(k), len(v))
[19]:
thing(this = {'thing': {'thing': thing}})
<class 'str'> 1
[20]:
layout.opts(opts.Area(alpha = 0.5, width=400, height=200))
layout.opts(shared_axes= False).cols(6)
[20]:
Violin plots
Expression heatmaps