Quantized Grid#
[1]:
%load_ext autoreload
%autoreload 2
#
from astropathdb import AstroDB, load_astrosample
from astropathdb import plotting as pl
from astropathdb import analysis as al
from astropathdb import tools as tl
import numpy
e:\immune_receptor_project\envs\astropath_test\lib\site-packages\numba\core\decorators.py:246: RuntimeWarning: nopython is set for njit and is ignored
warnings.warn('nopython is set for njit and is ignored', RuntimeWarning)
[2]:
sampleid = 4
s = load_astrosample(sampleid = sampleid)
# s.cellmeta.mixing_matrix = 'default'
[3]:
# s.load_image(x = (24000, 44000), y = (14300, 32600), coords_type = 'pixels')
# s.load_annotations()
Get the hotspots for a sample and plot them#
[4]:
sql = f"""
select 'hotspots' lname, h.sampleid, ganno.STAsText() wkt, p
from dbo.HotspotCD8 h, dbo.FieldGeometry f
where h.sampleid = {sampleid}
and h.hpfid = f.hpfid
and p between 0 and .3
"""
hotspots = s.gquery(sql)
hotspots.head()
[4]:
| lname | sampleid | p | geometry | |
|---|---|---|---|---|
| 0 | hotspots | 4 | 0.00 | POLYGON ((28838.000 27820.000, 29909.000 27820... |
| 1 | hotspots | 4 | 0.01 | POLYGON ((36342.000 17410.000, 37415.000 17410... |
| 2 | hotspots | 4 | 0.01 | POLYGON ((27765.000 28623.000, 28838.000 28623... |
| 3 | hotspots | 4 | 0.02 | POLYGON ((28838.000 28623.000, 29909.000 28623... |
| 4 | hotspots | 4 | 0.02 | POLYGON ((31392.870 15005.000, 32054.000 15005... |
[5]:
s.add_astro_shape(hotspots, f'sampleid_{sampleid}_annotations_hotspots')
[10]:
#
_0_to_10 = numpy.append(numpy.linspace(0.01, 0.1, 10), numpy.nan)
_0_to_20 = numpy.append(numpy.linspace(0.01, 0.2, 20), numpy.nan)
#
plot_settings = {'cmap': ['tab:green', 'tab:orange']}
#
pl.SubPlots(
pl.ShowAnno(s, title = "10% of Hotspots with Tumor", column_filter = {'lname':['tumor', 'hotspots'], 'p':_0_to_10}, annos_kwargs = plot_settings),
pl.ShowAnno(s, title = "20% of Hotspots with Tumor", column_filter = {'lname':['tumor', 'hotspots'], 'p':_0_to_20}, annos_kwargs = plot_settings),
pl.ShowAnno(s, title = "30% of Hotspots with Tumor", column_filter = {'lname':['tumor', 'hotspots']}, annos_kwargs = plot_settings),
pl.ShowAnno(s, title = "10% of Hotspots", column_filter = {'lname': 'hotspots', 'p':_0_to_10}, annos_kwargs = plot_settings),
pl.ShowAnno(s, title = "20% of Hotspots", column_filter = {'lname': 'hotspots', 'p':_0_to_20}, annos_kwargs = plot_settings),
pl.ShowAnno(s, title = "30% of Hotspots", column_filter = {'lname':'hotspots'}, annos_kwargs = plot_settings),
columns = 3,
figsize = (6,6),
);
[11]:
pl.SubPlots(
pl.ShowImage(s),
pl.ShowAnno(s, column_filter = {'lname':['tumor', 'hotspots']}, annos_kwargs={'cmap':['tab:olive', 'tab:orange']}),
pl.ShowAnno(s, annotation_element_id=f'sampleid_{sampleid}_annotations_hotspots', annos_kwargs={'cmap':['tab:olive']}),
columns = 3,
figsize = (6, 4)
);
[12]:
s.load_cell_table()
tl.get_spatial_heatmap(s, column = 'cmembrane540', alpha = .8)
[13]:
#
_0_to_10 = numpy.append(numpy.linspace(0.01, 0.1, 10), numpy.nan)
_0_to_20 = numpy.append(numpy.linspace(0.01, 0.2, 20), numpy.nan)
#
plot_settings = {'cmap': ['tab:olive'], 'lw':1}
#
pl.SubPlots(
pl.ShowAnno(s, image_element_id = f'sampleid_{sampleid}_hmap_256_cmembrane540_4', column_filter = {'lname': 'hotspots', 'p':_0_to_10}, annos_kwargs = plot_settings, title = " "),
pl.ShowAnno(s, image_element_id = f'sampleid_{sampleid}_hmap_256_cmembrane540_4', column_filter = {'lname': 'hotspots', 'p':_0_to_20}, annos_kwargs = plot_settings, title = " "),
pl.ShowAnno(s, image_element_id = f'sampleid_{sampleid}_hmap_256_cmembrane540_4', column_filter = {'lname':'hotspots'}, annos_kwargs = plot_settings, title = " "),
columns = 3,
figsize = (6,6),
);
collect the density data for the heatmap#
[2]:
db = AstroDB(database='wsi05')
[4]:
sql = f"""
select * from
dbo.DensityTableCD8
order by sampleid, mrank
"""
hotspot_data = db.query(sql)
hotspot_data.shape
[4]:
(68400, 7)
[15]:
hotspot_data.head()
hotspot_data['dens'] = hotspot_data.groupby(['sampleid', 'mytype', 'mrank', 'run', 'expression']).cumsum()['dens']
[23]:
csd = db.query("select * from dbo.extendedclinical where Pre_On_Tx = 'OnTreatment' and OS_Censor = 1")
len(csd.index)
[23]:
7
[24]:
16-7
[24]:
9
[25]:
db.query("select * from dbo.mergeconfig")
[25]:
| Project | Cohort | BatchID | layer | Opal | Target | Compartment | TargetType | CoexpressionStatus | SegmentationStatus | SegmentationHierarchy | NumberofSegmentations | ImageQA | Color | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 5 | 4 | 1 | 1 | DAPI | DNA | Nucleus | NA | NA | 0 | 0 | 1 | NA | #0000FF |
| 1 | 5 | 4 | 1 | 2 | 520 | CD79a | Membrane | Lineage | NA | 1 | 2 | 1 | NA | #7BC043 |
| 2 | 5 | 4 | 1 | 3 | 540 | ERG | Membrane | Lineage | NA | 2 | 3 | 1 | NA | #F4E76F |
| 3 | 5 | 4 | 1 | 4 | 570 | CD3 | Nucleus | Lineage | NA | 1 | 1 | 1 | Immune | #EE4035 |
| 4 | 5 | 4 | 1 | 5 | 620 | NSE | Membrane | Lineage | NA | 3 | 5 | 1 | Tumor | #F37736 |
| 5 | 5 | 4 | 1 | 6 | 650 | PD1 | Membrane | Expression | 520,540,570,650 | 1 | 0 | 1 | NA | #5EC1F5 |
| 6 | 5 | 4 | 1 | 7 | 690 | CD163 | Membrane | Lineage | NA | 4 | 4 | 1 | NA | #B361B4 |
| 7 | 5 | 4 | 1 | 8 | AF | NA | Nucleus | NA | NA | 0 | 0 | 0 | NA | #000000 |
| 8 | 5 | 4 | 2 | 1 | DAPI | DNA | Nucleus | NA | NA | 0 | 0 | 1 | NA | #0000FF |
| 9 | 5 | 4 | 2 | 2 | 520 | CD79a | Membrane | Lineage | NA | 1 | 2 | 1 | NA | #7BC043 |
| 10 | 5 | 4 | 2 | 3 | 540 | ERG | Membrane | Lineage | NA | 2 | 3 | 1 | NA | #F4E76F |
| 11 | 5 | 4 | 2 | 4 | 570 | CD3 | Nucleus | Lineage | NA | 1 | 1 | 1 | Immune | #EE4035 |
| 12 | 5 | 4 | 2 | 5 | 620 | NSE | Membrane | Lineage | NA | 3 | 5 | 1 | Tumor | #F37736 |
| 13 | 5 | 4 | 2 | 6 | 650 | PD1 | Membrane | Expression | 520,540,570,650 | 1 | 0 | 1 | NA | #5EC1F5 |
| 14 | 5 | 4 | 2 | 7 | 690 | CD163 | Membrane | Lineage | NA | 4 | 4 | 1 | NA | #B361B4 |
| 15 | 5 | 4 | 2 | 8 | AF | NA | Nucleus | NA | NA | 0 | 0 | 0 | NA | #000000 |
| 16 | 5 | 4 | 3 | 1 | DAPI | DNA | Nucleus | NA | NA | 0 | 0 | 1 | NA | #0000FF |
| 17 | 5 | 4 | 3 | 2 | 520 | CD79a | Membrane | Lineage | NA | 1 | 2 | 1 | NA | #7BC043 |
| 18 | 5 | 4 | 3 | 3 | 540 | ERG | Membrane | Lineage | NA | 2 | 3 | 1 | NA | #F4E76F |
| 19 | 5 | 4 | 3 | 4 | 570 | CD3 | Nucleus | Lineage | NA | 1 | 1 | 1 | Immune | #EE4035 |
| 20 | 5 | 4 | 3 | 5 | 620 | NSE | Membrane | Lineage | NA | 3 | 5 | 1 | Tumor | #F37736 |
| 21 | 5 | 4 | 3 | 6 | 650 | PD1 | Membrane | Expression | 520,540,570,650 | 1 | 0 | 1 | NA | #5EC1F5 |
| 22 | 5 | 4 | 3 | 7 | 690 | CD163 | Membrane | Lineage | NA | 4 | 4 | 1 | NA | #B361B4 |
| 23 | 5 | 4 | 3 | 8 | AF | NA | Nucleus | NA | NA | 0 | 0 | 0 | NA | #000000 |
| 24 | 5 | 4 | 4 | 1 | DAPI | DNA | Nucleus | NA | NA | 0 | 0 | 1 | NA | #0000FF |
| 25 | 5 | 4 | 4 | 2 | 520 | CD79a | Membrane | Lineage | NA | 1 | 2 | 1 | NA | #7BC043 |
| 26 | 5 | 4 | 4 | 3 | 540 | ERG | Membrane | Lineage | NA | 2 | 3 | 1 | NA | #F4E76F |
| 27 | 5 | 4 | 4 | 4 | 570 | CD3 | Nucleus | Lineage | NA | 1 | 1 | 1 | Immune | #EE4035 |
| 28 | 5 | 4 | 4 | 5 | 620 | NSE | Membrane | Lineage | NA | 3 | 5 | 1 | Tumor | #F37736 |
| 29 | 5 | 4 | 4 | 6 | 650 | PD1 | Membrane | Expression | 520,540,570,650 | 1 | 0 | 1 | NA | #5EC1F5 |
| 30 | 5 | 4 | 4 | 7 | 690 | CD163 | Membrane | Lineage | NA | 4 | 4 | 1 | NA | #B361B4 |
| 31 | 5 | 4 | 4 | 8 | AF | NA | Nucleus | NA | NA | 0 | 0 | 0 | NA | #000000 |
[13]:
groups_df = db.query("select sampleid, OS_Censor as groups from dbo.extendedclinical")
groups_df.head()
[13]:
| sampleid | groups | |
|---|---|---|
| 0 | 830 | 1 |
| 1 | 799 | 0 |
| 2 | 800 | 0 |
| 3 | 801 | 1 |
| 4 | 803 | 1 |
[20]:
sum(groups_df['groups'] == 0)
[20]:
6
[14]:
pd1_auc_data = al.estimate_density_table_auc(hotspot_data, groups_df, expression_marker = 'pd1')
pd1_auc_data.head()
[14]:
| mrank | 0.01 | 0.02 | 0.03 | 0.04 | 0.05 | 0.06 | 0.07 | 0.08 | 0.09 | 0.10 | ... | 0.91 | 0.92 | 0.93 | 0.94 | 0.95 | 0.96 | 0.97 | 0.98 | 0.99 | 1.00 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| mytype | |||||||||||||||||||||
| CD3;PD1+;PD1:1of3 | 0.602564 | 0.589744 | 0.589744 | 0.589744 | 0.602564 | 0.615385 | 0.615385 | 0.602564 | 0.602564 | 0.602564 | ... | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 |
| CD3;PD1+;PD1:2of3 | 0.615385 | 0.615385 | 0.628205 | 0.615385 | 0.602564 | 0.589744 | 0.602564 | 0.602564 | 0.615385 | 0.602564 | ... | 0.589744 | 0.589744 | 0.589744 | 0.589744 | 0.589744 | 0.589744 | 0.589744 | 0.589744 | 0.589744 | 0.589744 |
| CD3;PD1+;PD1:3of3 | 0.653846 | 0.653846 | 0.666667 | 0.666667 | 0.666667 | 0.666667 | 0.692308 | 0.679487 | 0.666667 | 0.666667 | ... | 0.653846 | 0.653846 | 0.653846 | 0.653846 | 0.653846 | 0.653846 | 0.653846 | 0.653846 | 0.653846 | 0.653846 |
| CD3;PD1- | 0.525641 | 0.525641 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.512821 | 0.525641 | 0.525641 | ... | 0.500000 | 0.500000 | 0.500000 | 0.500000 | 0.500000 | 0.500000 | 0.500000 | 0.500000 | 0.500000 | 0.500000 |
| CD79a;PD1+;PD1:1of3 | 0.775641 | 0.775641 | 0.775641 | 0.820513 | 0.820513 | 0.820513 | 0.820513 | 0.820513 | 0.820513 | 0.820513 | ... | 0.782051 | 0.782051 | 0.782051 | 0.782051 | 0.782051 | 0.782051 | 0.782051 | 0.782051 | 0.782051 | 0.782051 |
5 rows × 100 columns
Plot AUC Heatmap#
[16]:
plt = pl.HotspotAUCHeatmap(pd1_auc_data, group_mapping={})
plt.show()
[19]:
pdl1_auc_data = al.estimate_density_table_auc(hotspot_data, groups_df, expression_marker = 'pdl1')
pdl1_auc_data.head()
[19]:
| mrank | 0.01 | 0.02 | 0.03 | 0.04 | 0.05 | 0.06 | 0.07 | 0.08 | 0.09 | 0.10 | ... | 0.91 | 0.92 | 0.93 | 0.94 | 0.95 | 0.96 | 0.97 | 0.98 | 0.99 | 1.00 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| mytype | |||||||||||||||||||||
| CD163;PDL1+;PDL1:1of3 | 0.468954 | 0.447712 | 0.439542 | 0.454248 | 0.452614 | 0.457516 | 0.457516 | 0.423203 | 0.428105 | 0.436275 | ... | 0.467320 | 0.468954 | 0.465686 | 0.464052 | 0.464052 | 0.465686 | 0.464052 | 0.459150 | 0.459150 | 0.459150 |
| CD163;PDL1+;PDL1:2of3 | 0.475490 | 0.495098 | 0.457516 | 0.459150 | 0.447712 | 0.446078 | 0.447712 | 0.457516 | 0.462418 | 0.472222 | ... | 0.526144 | 0.522876 | 0.524510 | 0.524510 | 0.524510 | 0.526144 | 0.526144 | 0.526144 | 0.526144 | 0.529412 |
| CD163;PDL1+;PDL1:3of3 | 0.504902 | 0.526961 | 0.526961 | 0.522059 | 0.505719 | 0.515523 | 0.526961 | 0.543301 | 0.530229 | 0.533497 | ... | 0.576797 | 0.575163 | 0.578431 | 0.576797 | 0.578431 | 0.576797 | 0.576797 | 0.576797 | 0.576797 | 0.576797 |
| CD163;PDL1- | 0.772876 | 0.745098 | 0.738562 | 0.745098 | 0.740196 | 0.738562 | 0.743464 | 0.736928 | 0.746732 | 0.750000 | ... | 0.753268 | 0.758170 | 0.756536 | 0.756536 | 0.756536 | 0.756536 | 0.754902 | 0.753268 | 0.754902 | 0.754902 |
| CD8;PDL1+;PDL1:1of3 | 0.705882 | 0.665850 | 0.660948 | 0.665850 | 0.660948 | 0.667484 | 0.678922 | 0.672386 | 0.682190 | 0.680556 | ... | 0.695261 | 0.695261 | 0.695261 | 0.695261 | 0.695261 | 0.695261 | 0.695261 | 0.695261 | 0.693627 | 0.693627 |
5 rows × 100 columns
[49]:
pl.SubPlots(
pl.HotspotAUCHeatmap(pd1_auc_data, expression_marker = 'pd1'),
pl.HotspotAUCHeatmap(pdl1_auc_data, expression_marker = 'pdl1'),
figsize = (6, 4),
facecolor = 'white',
columns = 2,
set_aspect = False,
)
[49]:
<astropathdb.plotting.vizbase.SubPlots at 0x1960596f8b0>
Compute the Neighbor Densities#
[126]:
sql = f"""
select * from
dbo.DensityTableCD8_dist
where mrank = 0.3
"""
dist_hotspot_data = s.query(sql)
dist_hotspot_data.head()
[126]:
| id | sampleid | mytype | dens | cnt | area | mrank | run | |
|---|---|---|---|---|---|---|---|---|
| 0 | 14296 | 1 | Tumor;PD1+;PD1:2of3-TO-Tumor;PDL1+;PDL1:2of3 | 0.0 | 0 | 0.853911 | 0.3 | 1 |
| 1 | 14297 | 1 | Tumor;PD1+;PD1:2of3-TO-Tumor;PDL1+;PDL1:3of3 | 0.0 | 0 | 0.853911 | 0.3 | 1 |
| 2 | 14298 | 1 | Tumor;PD1+;PD1:3of3-TO-Tumor;PDL1+;PDL1:1of3 | 0.0 | 0 | 0.853911 | 0.3 | 1 |
| 3 | 14299 | 1 | Tumor;PD1+;PD1:3of3-TO-Tumor;PDL1+;PDL1:2of3 | 0.0 | 0 | 0.853911 | 0.3 | 1 |
| 4 | 14300 | 1 | Tumor;PD1+;PD1:3of3-TO-Tumor;PDL1+;PDL1:3of3 | 0.0 | 0 | 0.853911 | 0.3 | 1 |
[16]:
dist_auc_data = al.estimate_density_table_auc(dist_hotspot_data, groups_df, expression_marker = ['pd1','pdl1'])
dist_auc_data.head()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[16], line 1
----> 1 dist_auc_data = al.estimate_density_table_auc(dist_hotspot_data, groups_df, expression_marker = ['pd1','pdl1'])
2 dist_auc_data.head()
File E:\astropath\pkg_dev\test\astropathpy-db\src\astropathdb\analysis\quantized_tiles\density_auc.py:267, in estimate_density_table_auc(hotspot_data, groups_df, negative_correlations, expression_marker, metric, group_filters)
256 def estimate_density_table_auc(
257 hotspot_data: pandas.DataFrame,
258 groups_df: pandas.DataFrame,
(...)
262 group_filters: Optional[str] = "axis_defaults",
263 ):
264 """
265 Estimate the AUC for parameters in a density table.
266 """
--> 267 auc_class = HotSpotAUC(
268 hotspot_data=hotspot_data,
269 groups_df=groups_df,
270 negative_correlations=negative_correlations,
271 expression_marker=expression_marker,
272 metric=metric,
273 group_filters=group_filters,
274 )
275 return auc_class.auc_data
File E:\astropath\pkg_dev\test\astropathpy-db\src\astropathdb\analysis\quantized_tiles\density_auc.py:33, in HotSpotAUC.__init__(self, hotspot_data, groups_df, negative_correlations, expression_marker, metric, group_filters)
31 self.__groups_df = groups_df
32 hotspot_data = self.__parse_columns(hotspot_data, expression_marker)
---> 33 self.auc_data = self.__compute_hotspot_auc(hotspot_data)
File E:\astropath\pkg_dev\test\astropathpy-db\src\astropathdb\analysis\quantized_tiles\density_auc.py:220, in HotSpotAUC.__compute_hotspot_auc(self, hotspot_data)
218 filtered_hotspot_data = self.__filter_hotspot_data(hotspot_data)
219 #
--> 220 auc_data_formatted = self.__compute_auc(filtered_hotspot_data)
221 #
222 auc_pivot_data = self.__pivot_auc_data(auc_data_formatted)
File E:\astropath\pkg_dev\test\astropathpy-db\src\astropathdb\analysis\quantized_tiles\density_auc.py:189, in HotSpotAUC.__compute_auc(self, filtered_hotspot_data)
184 hdata_with_groups.loc[
185 hdata_with_groups["mytype"].isin(self.__negative_correlations),
186 "alternative",
187 ] = "less"
188 # set groups and get auc
--> 189 auc_data = hdata_with_groups.groupby([self.__x, "run", "mytype"]).apply(
190 estimate_auc, include_groups=False
191 )
192 # format and sort
193 auc_data_formatted = auc_data.apply(pandas.Series).reset_index()
File e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\pandas\core\frame.py:9183, in DataFrame.groupby(self, by, axis, level, as_index, sort, group_keys, observed, dropna)
9180 if level is None and by is None:
9181 raise TypeError("You have to supply one of 'by' and 'level'")
-> 9183 return DataFrameGroupBy(
9184 obj=self,
9185 keys=by,
9186 axis=axis,
9187 level=level,
9188 as_index=as_index,
9189 sort=sort,
9190 group_keys=group_keys,
9191 observed=observed,
9192 dropna=dropna,
9193 )
File e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\pandas\core\groupby\groupby.py:1329, in GroupBy.__init__(self, obj, keys, axis, level, grouper, exclusions, selection, as_index, sort, group_keys, observed, dropna)
1326 self.dropna = dropna
1328 if grouper is None:
-> 1329 grouper, exclusions, obj = get_grouper(
1330 obj,
1331 keys,
1332 axis=axis,
1333 level=level,
1334 sort=sort,
1335 observed=False if observed is lib.no_default else observed,
1336 dropna=self.dropna,
1337 )
1339 if observed is lib.no_default:
1340 if any(ping._passed_categorical for ping in grouper.groupings):
File e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\pandas\core\groupby\grouper.py:1043, in get_grouper(obj, key, axis, level, sort, observed, validate, dropna)
1041 in_axis, level, gpr = False, gpr, None
1042 else:
-> 1043 raise KeyError(gpr)
1044 elif isinstance(gpr, Grouper) and gpr.key is not None:
1045 # Add key to exclusions
1046 exclusions.add(gpr.key)
KeyError: 'distance'
[ ]:
cd8_data = hotspot_data.merge(groups_df, on = 'sampleid')
sample_cd8_data = cd8_data.groupby(['groups', 'mrank']).agg({'dens':'sum'})
cum_sample_cd8_data = sample_cd8_data.cumsum().reset_index()
import matplotlib.pyplot as plt # Graphics
nr = cum_sample_cd8_data[cum_sample_cd8_data['groups'] == 0].copy()
r = cum_sample_cd8_data[cum_sample_cd8_data['groups'] == 1].copy()
r.loc[-1] = [1, 0, 0]
nr.loc[-1] = [0, 0, 0]
r = r.reset_index().sort_values('mrank')
nr = nr.reset_index().sort_values('mrank')
import seaborn as sns
f, axs = plt.subplots(nrows=1, ncols=1, figsize=(3, 2), facecolor = 'white')
sns.lineplot(x = nr['mrank'] * 100, y = nr['dens'], color = 'tab:red', ax = axs)
sns.lineplot(x = r['mrank'] * 100, y = r['dens'], color = 'tab:blue', ax = axs)