Skip to content

Commit

Permalink
adding plot tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ajitjohnson committed Apr 26, 2024
1 parent 6d0423d commit cb5937a
Show file tree
Hide file tree
Showing 18 changed files with 148 additions and 32 deletions.
3 changes: 2 additions & 1 deletion scimap/plotting/cluster_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ def cluster_plots (adata,
subsample=100000,
palette ='viridis',
use_raw=False,
size=None, output_dir=None):
size=None,
output_dir=None):
"""
Parameters:
adata (anndata.AnnData):
Expand Down
22 changes: 15 additions & 7 deletions scimap/plotting/densityPlot2D.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import copy
from matplotlib import cm
from matplotlib.colors import LogNorm
import os

mpl.rcParams['pdf.fonttype'] = 42


Expand All @@ -38,8 +40,8 @@ def densityPlot2D (adata,
dpi=100,
xticks=None,
yticks=None,
outputDir=None,
outputFileName='densityPlot2D.pdf'):
saveDir=None,
fileName='densityPlot2D.pdf'):

"""
Parameters:
Expand Down Expand Up @@ -92,10 +94,10 @@ def densityPlot2D (adata,
yticks (list of float, optional):
Custom y-axis tick values.
outputDir (str, optional):
saveDir (str, optional):
The directory to save the output plot.
outputFileName (str, optional):
fileName (str, optional):
The name of the output file. Use desired file format as suffix (e.g. `.png` or `.pdf`).
Returns:
Expand Down Expand Up @@ -226,9 +228,15 @@ def calculate_grid_dimensions(num_items, num_columns=None):
plt.tight_layout()

# Save the figure to a file
# save figure
if outputDir is not None:
plt.savefig(pathlib.Path(outputDir) / outputFileName)
if saveDir:
if not os.path.exists(saveDir):
os.makedirs(saveDir)
full_path = os.path.join(saveDir, fileName)
plt.savefig(full_path, dpi=300)
plt.close(fig)
print(f"Saved heatmap to {full_path}")
else:
plt.show()



Expand Down
26 changes: 18 additions & 8 deletions scimap/plotting/distPlot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import itertools
import pathlib
import matplotlib as mpl
import os

mpl.rcParams['pdf.fonttype'] = 42

def distPlot(adata,
Expand All @@ -32,8 +34,8 @@ def distPlot(adata,
figsize=(5, 5),
fontsize=None,
dpi=200,
outputDir=None,
outputFileName='scimapDistPlot.png'):
saveDir=None,
fileName='scimapDistPlot.png'):

"""
Parameters:
Expand Down Expand Up @@ -79,10 +81,10 @@ def distPlot(adata,
dpi (int, optional):
The DPI of the figure. Use this to control the point size. Lower the dpi, larger the point size.
outputDir (str, optional):
saveDir (str, optional):
The directory to save the output plot.
outputFileName (str, optional):
fileName (str, optional):
The name of the output file. Use desired file format as suffix (e.g. `.png` or `.pdf`).
Returns:
Expand Down Expand Up @@ -233,8 +235,16 @@ def calculate_grid_dimensions(num_items, num_columns=None):
plt.tight_layout()

# Save the figure to a file
# save figure
if outputDir is not None:
plt.savefig(pathlib.Path(outputDir) / outputFileName)

if saveDir:
if not os.path.exists(saveDir):
os.makedirs(saveDir)
full_path = os.path.join(saveDir, fileName)
plt.savefig(full_path, dpi=300)
plt.close()
print(f"Saved heatmap to {full_path}")
else:
plt.show()




19 changes: 17 additions & 2 deletions scimap/plotting/foldchange.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import matplotlib.pyplot as plt
import numpy as np
from pandas.plotting import parallel_coordinates
import os

sns.set_style("white")

import matplotlib as mpl
Expand All @@ -42,6 +44,8 @@ def foldchange (adata,
matplotlib_legend_loc='upper left',
xticks_rotation=90,
return_data = False,
fileName='foldchange.pdf',
saveDir=None,
**kwargs):
"""
Parameters:
Expand Down Expand Up @@ -165,9 +169,9 @@ def foldchange (adata,
if method == 'heatmap':
# heatmap of the foldchange
#g= sns.clustermap(fold, cmap=cmap, mask=mask, center=center, col_cluster=False, row_cluster=False)
g= sns.clustermap(fold, cmap=cmap, mask=mask, center=center, **kwargs)
fig= sns.clustermap(fold, cmap=cmap, mask=mask, center=center, **kwargs)
plt.suptitle('reference: '+ str(ref))
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=xticks_rotation)
plt.setp(fig.ax_heatmap.get_xticklabels(), rotation=xticks_rotation)
plt.tight_layout()


Expand All @@ -186,6 +190,17 @@ def foldchange (adata,
plt.xticks(rotation = xticks_rotation)
plt.suptitle('reference: '+ str(ref))
fig.tight_layout()

# save
if saveDir:
if not os.path.exists(saveDir):
os.makedirs(saveDir)
full_path = os.path.join(saveDir, fileName)
plt.savefig(full_path, dpi=300)
plt.close()
print(f"Saved plot to {full_path}")
else:
plt.show()

# return data
if return_data is True:
Expand Down
7 changes: 3 additions & 4 deletions scimap/plotting/groupCorrelation.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def groupCorrelation(adata,
adata = ad.read_h5ad(adata)

# Calculate group counts
group_counts = adata.obs.groupby([condition, groupBy]).size().unstack(fill_value=0)
group_counts = adata.obs.groupby([condition, groupBy], observed=False).size().unstack(fill_value=0)

# Subset groups if needed
if subsetGroups:
Expand Down Expand Up @@ -190,13 +190,12 @@ def groupCorrelation(adata,
plt.tight_layout()

# Save or show the figure
if saveDir and fileName:
if saveDir:
if not os.path.exists(saveDir):
os.makedirs(saveDir)
full_path = os.path.join(saveDir, fileName)
plt.savefig(full_path, dpi=300)
if not os.path.exists(saveDir):
os.makedirs(saveDir)
plt.close()
print(f"Saved heatmap to {full_path}")
else:
plt.show()
Expand Down
4 changes: 2 additions & 2 deletions scimap/plotting/heatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def heatmap (adata,
cmap='vlag',
figsize=None,
saveDir=None,
fileName=None,
fileName='heatmap.pdf',
verbose=True,
**kwargs
):
Expand Down Expand Up @@ -312,7 +312,7 @@ def plot_category_heatmap_vectorized(data,
plt.tight_layout(rect=[0, 0, 0.9, 0.9]) # Adjust the layout

# Saving the figure if saveDir and fileName are provided
if saveDir and fileName:
if saveDir:
if not os.path.exists(saveDir):
os.makedirs(saveDir)
full_path = os.path.join(saveDir, fileName)
Expand Down
5 changes: 3 additions & 2 deletions scimap/plotting/markerCorrelation.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,13 @@ def markerCorrelation (adata,
plt.tight_layout()

# Saving the figure if saveDir and fileName are provided
if saveDir and fileName:
if saveDir:
if not os.path.exists(saveDir):
os.makedirs(saveDir)
full_path = os.path.join(saveDir, fileName)
plt.savefig(full_path, dpi=300)
print(f"Saved heatmap to {full_path}")
plt.close()
print(f"Saved plot to {full_path}")
else:
plt.show()

Expand Down
18 changes: 14 additions & 4 deletions scimap/plotting/umap.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import matplotlib.colors as colors
import seaborn as sns
import matplotlib.patches as mpatches
import os

plt.rcParams['figure.dpi'] = 100
plt.rcParams['savefig.dpi']=300
Expand All @@ -50,7 +51,9 @@ def umap (adata,
ncols=None,
tight_layout=False,
return_data=False,
save_figure=None, **kwargs):
saveDir=None,
fileName = 'umap.pdf',
**kwargs):
"""
Parameters:
adata (anndata.AnnData):
Expand Down Expand Up @@ -96,7 +99,7 @@ def umap (adata,
return_data (bool, optional):
If True, returns the DataFrame containing data used for plotting instead of displaying the plot.
save_figure (str, optional):
saveDir (str, optional):
Path and filename to save the figure. File extension determines the format (e.g., `.pdf`, `.png`).
**kwargs:
Expand Down Expand Up @@ -311,8 +314,15 @@ def umap (adata,
k = k+1 # iterator

# if save figure is requested
if save_figure is not None:
plt.savefig(save_figure)
if saveDir:
if not os.path.exists(saveDir):
os.makedirs(saveDir)
full_path = os.path.join(saveDir, fileName)
plt.savefig(full_path, dpi=300)
plt.close(fig)
print(f"Saved heatmap to {full_path}")
else:
plt.show()

# return data if needed
if return_data is True:
Expand Down
76 changes: 74 additions & 2 deletions scimap/tests/test_pl.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,89 @@ def test_heatmap (adata):
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"

# markerCorrelation
def test_markerCorrelation (adata):
from scimap.plotting.markerCorrelation import markerCorrelation
saveDir = os.getcwd() + '/testFigures'
fileName = 'markerCorrelation.png'
markerCorrelation(adata, saveDir=saveDir, fileName=fileName)
# check the file exist
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"


# groupCorrelation
def test_groupCorrelation (adata):
from scimap.plotting.groupCorrelation import groupCorrelation
saveDir = os.getcwd() + '/testFigures'
fileName = 'groupCorrelation.png'
groupCorrelation(adata, groupBy='ROI', condition='phenotype', saveDir=saveDir, fileName=fileName)
# check the file exist
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"


# markerCorrelation
# groupCorrelation
# distPlot
def test_distPlot (adata):
from scimap.plotting.distPlot import distPlot
saveDir = os.getcwd() + '/testFigures'
fileName = 'distPlot.png'
distPlot(adata, markers=['ECAD','FOXP3'], plotGrid=True, ncols=2, saveDir=saveDir, fileName=fileName)
# check the file exist
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"


# densityPlot2D
def test_densityPlot2D (adata):
from scimap.plotting.densityPlot2D import densityPlot2D
saveDir = os.getcwd() + '/testFigures'
fileName = 'densityPlot2D.png'
densityPlot2D(adata, markerA='ECAD', markerB='FOXP3',saveDir=saveDir, fileName=fileName)
# check the file exist
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"


# cluster_plots
def test_cluster_plots (adata):
from scimap.plotting.cluster_plots import cluster_plots
output_dir = os.getcwd() + '/testFigures'
fileName = '_matrixplot.pdf'
cluster_plots(adata, group_by='phenotype', output_dir=output_dir)
# check the file exist
full_path = os.path.join(output_dir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"


# umap
def test_umap (adata):
from scimap.plotting.umap import umap
saveDir = os.getcwd() + '/testFigures'
fileName = 'umap.png'
umap(adata, color='phenotype', saveDir=saveDir, fileName=fileName)
# check the file exist
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"


# foldchange
def test_foldchange (adata):
from scimap.tools.foldchange import foldchange
adata = foldchange(adata, from_group = 'ROI1', imageid='ROI')
# plotting
from scimap.plotting.foldchange import foldchange
saveDir = os.getcwd() + '/testFigures'
fileName = 'foldchange.png'
foldchange(adata, label='foldchange', method='heatmap', saveDir=saveDir, fileName=fileName)
# check the file exist
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"





# spatial_scatterPlot
# spatial_distance
# spatial_interaction
Expand Down
Binary file added testFigures/_matrixplot.pdf
Binary file not shown.
Binary file added testFigures/_ranked_markers_per_cluster.pdf
Binary file not shown.
Binary file added testFigures/_umap.pdf
Binary file not shown.
Binary file added testFigures/densityPlot2D.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added testFigures/distPlot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added testFigures/foldchange.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added testFigures/groupCorrelation.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added testFigures/markerCorrelation.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added testFigures/umap.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit cb5937a

Please sign in to comment.