# Developing-Heart-Local-Improved - Cell Annotation

**Pages:** 2

---

## Notebook

**URL:** http://127.0.0.1:9020/notebooks_html/Fig1_General_processing/VisiumHD/no8_collect_fine-grained-annotations.html

**Contents:**
- Variables¶
- Read in data¶
- Add fine-grained annotation¶
- Save¶
- Gene expression¶

**Examples:**

Example 1 (python):
```python
import matplotlib.pyplot as plt
import scanpy as sc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
```

Example 2 (python):
```python
# import session_info
# session_info.show()
```

Example 3 (python):
```python
sc.settings.set_figure_params(dpi=80)
```

Example 4 (python):
```python
adata_dir = '/lustre/scratch126/cellgen/team205/kk18/VisiumHD/objects'
sample_id = 'HEA_FOET14880396'
```

Example 5 (unknown):
```unknown
os.getcwd()
```

Example 6 (unknown):
```unknown
'/nfs/team205/kk18/notebooks/Foetal/VisiumHD/re-seq_mpp0p3'
```

Example 7 (python):
```python
adata= sc.read_h5ad(f'{adata_dir}/{sample_id}_b2c_cells_filtered_lognorm.h5ad')
adata
```

Example 8 (unknown):
```unknown
AnnData object with n_obs × n_vars = 129803 × 18047
    obs: 'object_id', 'bin_count', 'array_row', 'array_col', 'labels_joint_source', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes', 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes', 'total_counts_mt', 'log1p_total_counts_mt', 'pct_counts_mt', 'celltypist_coarse', 'conf_score_coarse', 'celltypist_coarse_fin', 'celltypist_coarse2midmod', 'conf_score_coarse2midmod', 'celltypist_mid_fin', 'celltypist_midmod2fine', 'conf_score_midmod2fine'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells', 'mt', 'n_cells_by_counts', 'mean_counts', 'log1p_mean_counts', 'pct_dropout_by_counts', 'total_counts', 'log1p_total_counts', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
    uns: 'celltypist_coarse2midmod_colors', 'celltypist_coarse_colors', 'celltypist_coarse_fin_colors', 'celltypist_mid_fin_colors', 'celltypist_midmod2fine_colors', 'hvg', 'log1p', 'neighbors', 'pca', 'spatial', 'umap'
    obsm: 'X_pca', 'X_umap', 'spatial', 'spatial_cropped_150_buffer'
    varm: 'PCs'
    obsp: 'connectivities', 'distances'
```

Example 9 (python):
```python
adata.X.data[:5]
```

Example 10 (unknown):
```unknown
array([1.27187559, 1.95641568, 1.75023687, 1.96760567, 2.7810601 ])
```

Example 11 (python):
```python
sc.pl.embedding(adata,
                    basis=f"X_umap",
                    color='celltypist_mid_fin',
                # groups='unassigned',
                   ncols=4
                   )
```

Example 12 (python):
```python
subset_adata_dir = '/lustre/scratch126/cellgen/team205/kk18/VisiumHD/objects/subsets'
fine_grain_colname = 'fine_grain_4Jan2025'
```

Example 13 (python):
```python
!ls {subset_adata_dir}
```

Example 14 (unknown):
```unknown
HEA_FOET14880396_AtrialCardiomyocytes_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_BloodVesselEndothelialCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_EndocardialCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_EpicardialCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_Fibroblasts_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_Glia_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_LymphaticEndothelialCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_LymphoidCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_MuralCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_MyeloidCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_Neurons_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_PericardialCells_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_VentricularCardiomyocytes_b2c_cells_filtered_lognorm.h5ad
```

Example 15 (python):
```python
adata.obs[fine_grain_colname] =  adata.obs['celltypist_mid_fin'].astype('str').copy()
```

Example 16 (python):
```python
file_list = os.listdir(subset_adata_dir)
celltypes_to_add = [x.split('_')[2] for x in file_list]
celltypes_to_add
```

Example 17 (unknown):
```unknown
['PericardialCells',
 'LymphaticEndothelialCells',
 'AtrialCardiomyocytes',
 'MuralCells',
 'BloodVesselEndothelialCells',
 'MyeloidCells',
 'EpicardialCells',
 'Fibroblasts',
 'LymphoidCells',
 'VentricularCardiomyocytes',
 'Glia',
 'Neurons',
 'EndocardialCells']
```

Example 18 (python):
```python
for celltype in celltypes_to_add:
    print(celltype)
    if celltype=='LymphaticEndothelialCells':
        print('skip since the label of mid-grain and fine-grain are same')
        continue
    ad = sc.read_h5ad(f'{subset_adata_dir}/{sample_id}_{celltype}_b2c_cells_filtered_lognorm.h5ad',backed='r')
    print(ad.shape)
    # add cell type labels
    adata.obs.loc[ad.obs_names,fine_grain_colname] = ad.obs['fine_grain_manual']
adata.obs[fine_grain_colname].value_counts()
```

Example 19 (unknown):
```unknown
PericardialCells
(3061, 15212)
LymphaticEndothelialCells
skip since the label of mid-grain and fine-grain are same
AtrialCardiomyocytes
(13904, 17650)
MuralCells
(10785, 17693)
BloodVesselEndothelialCells
(1765, 15377)
MyeloidCells
(526, 13502)
EpicardialCells
(603, 13050)
Fibroblasts
(20318, 17926)
LymphoidCells
(87, 10288)
VentricularCardiomyocytes
(61075, 17994)
Glia
(588, 13981)
Neurons
(589, 14494)
EndocardialCells
(1526, 14451)
```

Example 20 (unknown):
```unknown
fine_grain_4Jan2025
unassigned                                            35539
VentricularCardiomyocytesCompact                      32970
Fibroblasts                                            7849
VentricularCardiomyocytesTrabeculated                  6349
VentricularConductionSystemProximal                    5902
ValveInterstitialCells                                 5186
AtrialCardiomyocytesRight                              5060
GreatVesselSmoothMuscleCells                           4843
AtrialCardiomyocytesLeft                               3107
PericardialCellsFibrous                                2231
DuctusArteriosusSmoothMuscleCells                      2145
VentricularCardiomyocytes_DoubletsWithErythrocytes     1723
FibroblastsCOL2A1pos                                   1648
AtrioventricularNodePacemakerCells                     1602
GreatVesselSmoothMuscleCellsTFPI2pos                   1519
VentricularConductionSystemDistal                      1342
LymphaticEndothelialCells                              1025
CoronaryCapillaryEndothelialCells                       848
CoronaryPericytes                                       753
PericardialCellsIntermediate                            730
SinoatrialNodePacemakerCellsHead                        636
ValveEndothelialCells                                   585
EndocardialCushionCells                                 531
SinoatrialNodePacemakerCellsHorn                        501
MesothelialEpicardialCells                              491
CoronarySmoothMuscleCells                               424
EndocardialCells                                        399
SinoatrialNodePacemakerCellsTail                        373
SchwannCells                                            354
GreatVesselVenousEndothelialCells                       313
GreatVesselArterialEndothelialCells                     308
MacrophagesLYVE1pos                                     299
GreatVesselSmoothMuscleCellsPTGER4pos                   285
ChromaffinCells                                         265
Fibroblasts_DoubletsWithCMs                             255
CoronaryArterialEndothelialCells                        219
SchwannCellPrecursors                                   163
ParasympatheticNeurons                                  153
EpicardiumDerivedCells                                  112
SympatheticNeurons                                      110
PericardialCells_DoubletsWithCMs                        100
MacrophagesCX3CR1pos                                     90
CoronaryVenousEndothelialCells                           77
SchwannCells_and_Neurons                                 71
InnateLymphoidCells                                      69
NeuronPrecursors                                         61
Monocytes                                                47
MonocyteDerivedCells                                     40
Erythrocytes                                             37
Megakaryocytes                                           24
VentricularCardiomyocytes_Doublets                       22
BCells                                                   18
Name: count, dtype: int64
```

Example 21 (python):
```python
sc.pl.embedding(adata,basis='X_umap',color=[fine_grain_colname],wspace=0.2,cmap='RdPu')
```

Example 22 (python):
```python
adata.write(f'{adata_dir}/{sample_id}_b2c_cells_filtered_lognorm.h5ad')
f'{adata_dir}/{sample_id}_b2c_cells_filtered_lognorm.h5ad'
```

Example 23 (unknown):
```unknown
'/lustre/scratch126/cellgen/team205/kk18/VisiumHD/objects/HEA_FOET14880396_b2c_cells_filtered_lognorm.h5ad'
```

Example 24 (unknown):
```unknown
AnnData object with n_obs × n_vars = 129803 × 18047
    obs: 'object_id', 'bin_count', 'array_row', 'array_col', 'labels_joint_source', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes', 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes', 'total_counts_mt', 'log1p_total_counts_mt', 'pct_counts_mt', 'celltypist_coarse', 'conf_score_coarse', 'celltypist_coarse_fin', 'celltypist_coarse2midmod', 'conf_score_coarse2midmod', 'celltypist_mid_fin', 'celltypist_midmod2fine', 'conf_score_midmod2fine', 'fine_grain_4Jan2025'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells', 'mt', 'n_cells_by_counts', 'mean_counts', 'log1p_mean_counts', 'pct_dropout_by_counts', 'total_counts', 'log1p_total_counts', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
    uns: 'celltypist_coarse2midmod_colors', 'celltypist_coarse_colors', 'celltypist_coarse_fin_colors', 'celltypist_mid_fin_colors', 'celltypist_midmod2fine_colors', 'hvg', 'log1p', 'neighbors', 'pca', 'spatial', 'umap', 'fine_grain_4Jan2025_colors'
    obsm: 'X_pca', 'X_umap', 'spatial', 'spatial_cropped_150_buffer'
    varm: 'PCs'
    obsp: 'connectivities', 'distances'
```

Example 25 (python):
```python
adata= sc.read_h5ad(f'{adata_dir}/{sample_id}_b2c_cells_filtered_lognorm.h5ad')
adata
```

Example 26 (python):
```python
cells = [
    'SinoatrialNodePacemakerCellsHorn',
    'SinoatrialNodePacemakerCellsHead',
    'SinoatrialNodePacemakerCellsTail',
    'AtrioventricularNodePacemakerCells',
    # 'VentricularConductionSystem'
    
    # 'MacrophagesCX3CR1pos',
    # 'ParasympatheticNeurons'
]

celltype_key = 'fine_grain_8Dec2024'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHorn')]='magenta'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHead')]='deepskyblue'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsTail',)]='darkcyan'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('AtrioventricularNodePacemakerCells')]='orange'
# adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('VentricularConductionSystem')]='mediumpurple'

sc.pl.spatial(adata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=10,legend_fontsize=30,spot_size=10,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 27 (python):
```python
cells = [
  'MacrophagesCX3CR1pos',
  'MacrophagesLYVE1pos',
    'MacrophagesTREM2pos',
]

celltype_key = 'fine_grain_8Dec2024'
'''
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHorn')]='magenta'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHead')]='deepskyblue'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsTail',)]='darkcyan'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('AtrioventricularNodePacemakerCells')]='orange'
# adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('VentricularConductionSystem')]='mediumpurple'
'''

sc.pl.spatial(adata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=10,legend_fontsize=30,spot_size=10,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 28 (python):
```python
cells = [
  'ParasympatheticNeurons',
  'SympatheticNeurons',
]

celltype_key = 'fine_grain_8Dec2024'
'''
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHorn')]='magenta'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHead')]='deepskyblue'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsTail',)]='darkcyan'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('AtrioventricularNodePacemakerCells')]='orange'
# adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('VentricularConductionSystem')]='mediumpurple'
'''

sc.pl.spatial(adata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=10,legend_fontsize=30,spot_size=10,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 29 (python):
```python
cells = [
     'SinoatrialNodePacemakerCellsHorn',
    'SinoatrialNodePacemakerCellsHead',
    'SinoatrialNodePacemakerCellsTail',
    'AtrioventricularNodePacemakerCells',
    # 'VentricularConductionSystem'
]
celltype_key = 'fine_grain_8Dec2024'

mask = ((adata.obs['array_row'] >= 1700) & 
        (adata.obs['array_row'] <= 2300) & 
        (adata.obs['array_col'] >= 600) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]
n_celltype = len(bdata.obs[celltype_key].cat.categories)
bdata.uns[celltype_key] = list(np.repeat('#ffff00',n_celltype))

# update colors
for c in cells:
    # get color in adata
    ind = list(adata.obs[celltype_key].cat.categories).index(c)
    color = adata.uns[f'{celltype_key}_colors'][ind]
    # update color in bdata
    ind = list(bdata.obs[celltype_key].cat.categories).index(c)
    bdata.uns[f'{celltype_key}_colors'][ind] = color

sc.pl.spatial(bdata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=2,legend_fontsize=30,# spot_size=10,
                  frameon=False,) # save=f'_{c}_b2c',
```

Example 30 (python):
```python
cells = [
     'MacrophagesCX3CR1pos',
  'MacrophagesLYVE1pos',
]
celltype_key = 'fine_grain_8Dec2024'

mask = ((adata.obs['array_row'] >= 1700) & 
        (adata.obs['array_row'] <= 2300) & 
        (adata.obs['array_col'] >= 600) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]
n_celltype = len(bdata.obs[celltype_key].cat.categories)
bdata.uns[celltype_key] = list(np.repeat('#ffff00',n_celltype))

# update colors
for c in cells:
    # get color in adata
    ind = list(adata.obs[celltype_key].cat.categories).index(c)
    color = adata.uns[f'{celltype_key}_colors'][ind]
    # update color in bdata
    ind = list(bdata.obs[celltype_key].cat.categories).index(c)
    bdata.uns[f'{celltype_key}_colors'][ind] = color

sc.pl.spatial(bdata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=2,legend_fontsize=30,# spot_size=10,
                  frameon=False,) # save=f'_{c}_b2c',
```

Example 31 (python):
```python
cells = [
    'ParasympatheticNeurons',
  # 'SympatheticNeurons',
]
celltype_key = 'fine_grain_8Dec2024'

mask = ((adata.obs['array_row'] >= 1700) & 
        (adata.obs['array_row'] <= 2300) & 
        (adata.obs['array_col'] >= 600) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]
n_celltype = len(bdata.obs[celltype_key].cat.categories)
bdata.uns[celltype_key] = list(np.repeat('#ffff00',n_celltype))

# update colors
for c in cells:
    # get color in adata
    ind = list(adata.obs[celltype_key].cat.categories).index(c)
    color = adata.uns[f'{celltype_key}_colors'][ind]
    # update color in bdata
    ind = list(bdata.obs[celltype_key].cat.categories).index(c)
    bdata.uns[f'{celltype_key}_colors'][ind] = color

sc.pl.spatial(bdata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=2,legend_fontsize=30,# spot_size=10,
                  frameon=False,) # save=f'_{c}_b2c',
```

Example 32 (python):
```python
cells = [
    'ParasympatheticNeurons',
  'SchwannCellPrecursors',
    'SchwannCells',
   'SchwannCells_and_Neurons'
]

sc.pl.spatial(bdata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=2,legend_fontsize=30,# spot_size=10,
                  frameon=False,) # save=f'_{c}_b2c',
```

Example 33 (python):
```python
cells = [
    'ParasympatheticNeurons',
  'SchwannCellPrecursors',
    'SchwannCells',
   'SchwannCells_and_Neurons'
]

celltype_key = 'fine_grain_8Dec2024'
mask = ((adata.obs['array_row'] >= 1700) & 
        (adata.obs['array_row'] <= 2300) & 
        (adata.obs['array_col'] >= 600) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]

sc.pl.spatial(bdata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=2,legend_fontsize=30,# spot_size=10,
                  frameon=False,) # save=f'_{c}_b2c',
```

Example 34 (python):
```python
cells = [
   'ParasympatheticNeurons',
  'SchwannCellPrecursors',
    'SchwannCells',
   'SchwannCells_and_Neurons'
]

celltype_key = 'fine_grain_8Dec2024'
'''
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHorn')]='magenta'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHead')]='deepskyblue'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsTail',)]='darkcyan'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('AtrioventricularNodePacemakerCells')]='orange'
# adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('VentricularConductionSystem')]='mediumpurple'
'''

sc.pl.spatial(adata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=30,legend_fontsize=30,spot_size=10,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 35 (python):
```python
genes = ['SEMA3A', 'SLIT2', 'SLIT3', 'EFNB2', 'CXCL12', 'FGF10', 'VEGFC', 'NELL1']
genes = [x for x in genes if x in adata.var_names]
genes
```

Example 36 (python):
```python
sc.pl.spatial(adata, color=genes,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=30,legend_fontsize=0,spot_size=5,ncols=5,wspace=0.15,
                  frameon=False,cmap='viridis')
```

Example 37 (python):
```python
mask = ((adata.obs['array_row'] >= 1700) & 
        (adata.obs['array_row'] <= 2300) & 
        (adata.obs['array_col'] >= 600) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]

sc.pl.spatial(bdata, color=genes,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=30,legend_fontsize=0,spot_size=5,ncols=5,wspace=0.15,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 38 (python):
```python
mask = ((adata.obs['array_row'] >= 1500) & 
        (adata.obs['array_row'] <= 2500) & 
        (adata.obs['array_col'] >= 400) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]

sc.pl.spatial(bdata, color=genes,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=30,legend_fontsize=0,spot_size=5,ncols=5,wspace=0.15,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 39 (python):
```python
cells = [
     'MacrophagesCX3CR1pos',
    'SinoatrialNodePacemakerCellsHorn',
  'SinoatrialNodePacemakerCellsHead',
    'ParasympatheticNeurons',
]
celltype_key = 'fine_grain_8Dec2024'

mask = ((adata.obs['array_row'] >= 2000) & 
        (adata.obs['array_row'] <= 2200) & 
        (adata.obs['array_col'] >= 600) & 
        (adata.obs['array_col'] <= 800)
       )
bdata = adata[mask]
bdata.uns[f"{celltype_key}_colors"][list(bdata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHorn')]='magenta'
bdata.uns[f"{celltype_key}_colors"][list(bdata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHead')]='deepskyblue'
bdata.uns[f"{celltype_key}_colors"][list(bdata.obs[celltype_key].cat.categories).index('MacrophagesCX3CR1pos',)]='red'
bdata.uns[f"{celltype_key}_colors"][list(bdata.obs[celltype_key].cat.categories).index('ParasympatheticNeurons')]='purple'

sc.pl.spatial(bdata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=4,legend_fontsize=30,spot_size=10,alpha_img=0.3,
                  frameon=False,) # save=f'_{c}_b2c',
```

Example 40 (python):
```python
cells = [
  'MacrophagesCX3CR1pos',
  'MacrophagesLYVE1pos',
    'MacrophagesTREM2pos',
]

celltype_key = 'fine_grain_8Dec2024'
'''
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHorn')]='magenta'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsHead')]='deepskyblue'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('SinoatrialNodePacemakerCellsTail',)]='darkcyan'
adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('AtrioventricularNodePacemakerCells')]='orange'
# adata.uns[f"{celltype_key}_colors"][list(adata.obs[celltype_key].cat.categories).index('VentricularConductionSystem')]='mediumpurple'
'''

sc.pl.spatial(adata, color=celltype_key, groups=cells,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=10,legend_fontsize=30,spot_size=10,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 41 (python):
```python
genes = ['SHOX2', 'TBX3', 
         'GJA1', # CX43
         'GJA5', # CX40
         'RSPO3'
        ]
genes = [x for x in genes if x in adata.var_names]
genes
```

Example 42 (python):
```python
mask = ((adata.obs['array_row'] >= 1700) & 
        (adata.obs['array_row'] <= 2300) & 
        (adata.obs['array_col'] >= 600) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]

sc.pl.spatial(bdata, color=genes,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=30,legend_fontsize=0,spot_size=5,ncols=5,wspace=0.15,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

Example 43 (python):
```python
mask = ((adata.obs['array_row'] >= 1500) & 
        (adata.obs['array_row'] <= 2500) & 
        (adata.obs['array_col'] >= 400) & 
        (adata.obs['array_col'] <= 1200)
       )
bdata = adata[mask]

sc.pl.spatial(bdata, color=genes,
              img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
              size=30,legend_fontsize=0,spot_size=5,ncols=5,wspace=0.15,
                  frameon=False,cmap='viridis') # save=f'_{c}_b2c',
```

---

## Notebook

**URL:** http://127.0.0.1:9020/notebooks_html/Fig1_General_processing/VisiumHD/no9_map_loupe-annotations.html

**Contents:**
- Read the objects¶
- Import annotations from loupe browser¶
- Plot¶
- Save cdata¶

**Examples:**

Example 1 (python):
```python
import matplotlib.pyplot as plt
import scanpy as sc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import bin2cell as b2c
print(b2c.__version__)
```

Example 2 (python):
```python
# import session_info
# session_info.show()
```

Example 3 (python):
```python
sc.settings.set_figure_params(dpi=80)
```

Example 4 (unknown):
```unknown
os.getcwd()
```

Example 5 (unknown):
```unknown
'/nfs/team205/kk18/notebooks/Foetal/VisiumHD/re-seq_mpp0p3'
```

Example 6 (python):
```python
adata_dir = '/lustre/scratch126/cellgen/team205/kk18/VisiumHD/objects'
sample_id = 'HEA_FOET14880396'
```

Example 7 (python):
```python
!ls {adata_dir}
```

Example 8 (unknown):
```unknown
archived-Dec2024_HEA_FOET14880396_b2c.h5ad
cellcharter
HEA_AD14880301_b2c.h5ad
HEA_FOET14880396_8um-bins_filtered.h5ad
HEA_FOET14880396_8um-bins_filtered_lognorm.h5ad
HEA_FOET14880396_b2c_cells_filtered_celltype-selected_lognorm.h5ad
HEA_FOET14880396_b2c_cells_filtered.h5ad
HEA_FOET14880396_b2c_cells_filtered_lognorm.h5ad
HEA_FOET14880396_b2c_cells_filtered_lognorm_morpho_obs.csv
HEA_FOET14880396_b2c_cells.h5ad
HEA_FOET14880396_b2c.h5ad
HEA_FOET14880397_b2c.h5ad
subsets
```

Example 9 (python):
```python
adata = sc.read_h5ad(f'{adata_dir}/{sample_id}_b2c.h5ad') # read 2um object which has b2c cell grouping - see tutorial - https://nbviewer.org/github/Teichlab/bin2cell/blob/main/notebooks/demo.ipynb 
cdata = sc.read_h5ad(f'{adata_dir}/{sample_id}_b2c_cells_filtered_lognorm.h5ad') # read b2c object
anno_df = pd.read_csv(f'/nfs/team205/kk18/notebooks/Foetal/VisiumHD/re-seq_mpp0p3/loupe_annotation/{sample_id}_HistologicalAnnotation.csv',index_col=0)
anno = 'HistologicalAnnotation'
cell_grouping = 'labels_joint'
```

Example 10 (unknown):
```unknown
AnnData object with n_obs × n_vars = 5001851 × 18051
    obs: 'in_tissue', 'array_row', 'array_col', 'n_counts', 'destripe_factor', 'n_counts_adjusted', 'labels_he_0p01', 'labels_he_0p03', 'labels_he_0p05', 'labels_he_0p1', 'labels_he_default', 'labels_he_sel', 'labels_he_expanded_1', 'labels_he_expanded_2', 'labels_he_expanded_3', 'labels_he_expanded_4', 'labels_he_expanded_sel', 'labels_gex_0p005', 'labels_gex_0p01', 'labels_gex_0p03', 'labels_gex_0p05', 'labels_gex_sel', 'labels_joint', 'labels_joint_source'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells'
    uns: 'bin2cell', 'spatial'
    obsm: 'spatial', 'spatial_cropped_150_buffer'
```

Example 11 (python):
```python
def map_loupe_to_b2c(
        adata,
        cdata,
        anno_df,
        anno,
        cell_grouping = 'labels_he_expanded', 
        ):
     

    # Calculate the binned row and column indices in adata
    adata.obs['binned_8_row'] = adata.obs['array_row'] // 4
    adata.obs['binned_8_col'] = adata.obs['array_col'] // 4

    # Create a combined index in adata and set it as the index
    adata.obs['mapping_index_08'] = 's_008um_' + adata.obs['binned_8_row'].astype(str).str.zfill(5) + '_' + adata.obs['binned_8_col'].astype(str).str.zfill(5) + '-1'
    adata.obs['mapping_index_08'].value_counts() # most should have 16 but there are some on the tissue edge that actually have less due to partial overlap 

    # read annotations from df and map to the 2um object 
    print('annotations to map:')
    print(anno_df.head(5))
    mapping_dict = pd.Series(anno_df[anno].values,index=anno_df.index).to_dict()
    adata.obs[anno] = adata.obs['mapping_index_08'].map(mapping_dict) # update 2um object 

    # assign annotation to cells by pandas.Series.mode(). The mode is the value that appears most often which captures the most frequent annotation for that cell from 2um data
    filtered_data = adata.obs[(adata.obs[cell_grouping] != 0) & adata.obs[anno].notna()]
    cell_annotation = (
        filtered_data.groupby(cell_grouping)[anno]
        .apply(lambda x: x.mode().iloc[0] if not x.mode().empty else None)
    )
    cell_annotation.index = cell_annotation.index.astype('str')
    cdata.obs[anno] = cdata.obs.index.map(cell_annotation).astype('category') # label cells 
    print('Annotations in b2c object:')
    print(cdata.obs[anno].value_counts())

map_loupe_to_b2c(adata,
                 cdata,
                 anno_df,
                 anno,
                 cell_grouping)
```

Example 12 (unknown):
```unknown
annotations to map:
                                      HistologicalAnnotation
Barcode                                                     
s_008um_00301_00321-1                                 Valves
s_008um_00602_00290-1  Great vessel - Pulmonary artery Right
s_008um_00377_00750-1                              Ventricle
s_008um_00383_00696-1                              Ventricle
s_008um_00526_00291-1                   Great vessel - Aorta
Annotations in b2c object:
HistologicalAnnotation
Ventricle                                                     64624
Atrium                                                        17355
Valves                                                         6435
Great vessel - Pulmonary artery Left and Ductus arteriosus     4746
Great vessel - Pulmonary artery Right                          2838
Coronary vessel                                                2752
Great vessel - Aorta                                           2564
Name: count, dtype: int64
```

Example 13 (unknown):
```unknown
annotations_to_plot = list(set(anno_df['HistologicalAnnotation'].dropna()))
group_col = 'HistologicalAnnotation'
len(annotations_to_plot)
```

Example 14 (python):
```python
sc.settings.set_figure_params(dpi=120)
sc.pl.spatial(cdata, 
                  color=group_col, 
                  img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
                  size=1.5,alpha_img=0.3,
                  frameon=False,
                 )
```

Example 15 (python):
```python
fig,axs=plt.subplots(nrows=1,ncols=6,figsize=(24,4))
# Flatten the axs array for easier iteration in case of multiple rows and columns
axs_flat = axs.flatten()

for i,annotation in enumerate(annotations_to_plot):
    ad = cdata.copy()
    # update colors
    # get color in cdata
    ind = list(ad.obs[group_col].cat.categories).index(annotation)
    ad.uns[f'{group_col}_colors'][ind] = 'greenyellow'
    # plot
    sc.pl.spatial(ad, 
                  color=group_col, groups=annotation,
                  img_key="0.3_mpp_150_buffer", basis="spatial_cropped_150_buffer",
                  size=7,legend_loc=None,
                  frameon=False,title=annotation,
                  show=False, ax=axs_flat[i],
                 )
# Turn off any remaining subplots
for j in range(len(annotations_to_plot), len(axs_flat)):
    fig.delaxes(axs_flat[j])

# fig.suptitle('Main Title for the Figure')
fig.tight_layout()
```

Example 16 (unknown):
```unknown
AnnData object with n_obs × n_vars = 129803 × 18047
    obs: 'object_id', 'bin_count', 'array_row', 'array_col', 'labels_joint_source', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes', 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes', 'total_counts_mt', 'log1p_total_counts_mt', 'pct_counts_mt', 'celltypist_coarse', 'conf_score_coarse', 'celltypist_coarse_fin', 'celltypist_coarse2midmod', 'conf_score_coarse2midmod', 'celltypist_mid_fin', 'celltypist_midmod2fine', 'conf_score_midmod2fine', 'fine_grain_4Jan2025', 'HistologicalAnnotation'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells', 'mt', 'n_cells_by_counts', 'mean_counts', 'log1p_mean_counts', 'pct_dropout_by_counts', 'total_counts', 'log1p_total_counts', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
    uns: 'HistologicalAnnotation_colors', 'celltypist_coarse2midmod_colors', 'celltypist_coarse_colors', 'celltypist_coarse_fin_colors', 'celltypist_mid_fin_colors', 'celltypist_midmod2fine_colors', 'fine_grain_4Jan2025_colors', 'hvg', 'log1p', 'neighbors', 'pca', 'spatial', 'umap'
    obsm: 'X_pca', 'X_umap', 'spatial', 'spatial_cropped_150_buffer'
    varm: 'PCs'
    obsp: 'connectivities', 'distances'
```

Example 17 (python):
```python
cdata.write(f'{adata_dir}/{sample_id}_b2c_cells_filtered_lognorm.h5ad')
cdata
```

Example 18 (unknown):
```unknown
AnnData object with n_obs × n_vars = 129803 × 18047
    obs: 'object_id', 'bin_count', 'array_row', 'array_col', 'labels_joint_source', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes', 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes', 'total_counts_mt', 'log1p_total_counts_mt', 'pct_counts_mt', 'celltypist_coarse', 'conf_score_coarse', 'celltypist_coarse_fin', 'celltypist_coarse2midmod', 'conf_score_coarse2midmod', 'celltypist_mid_fin', 'celltypist_midmod2fine', 'conf_score_midmod2fine', 'fine_grain_4Jan2025', 'HistologicalAnnotation'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells', 'mt', 'n_cells_by_counts', 'mean_counts', 'log1p_mean_counts', 'pct_dropout_by_counts', 'total_counts', 'log1p_total_counts', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
    uns: 'HistologicalAnnotation_colors', 'celltypist_coarse2midmod_colors', 'celltypist_coarse_colors', 'celltypist_coarse_fin_colors', 'celltypist_mid_fin_colors', 'celltypist_midmod2fine_colors', 'fine_grain_4Jan2025_colors', 'hvg', 'log1p', 'neighbors', 'pca', 'spatial', 'umap'
    obsm: 'X_pca', 'X_umap', 'spatial', 'spatial_cropped_150_buffer'
    varm: 'PCs'
    obsp: 'connectivities', 'distances'
```

---
