Skip to content

Commit

Permalink
tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ajitjohnson committed Apr 27, 2024
1 parent c10ea6f commit ba8d355
Show file tree
Hide file tree
Showing 22 changed files with 70 additions and 33 deletions.
6 changes: 3 additions & 3 deletions scimap/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from pkg_resources import get_distribution, DistributionNotFound
import importlib.metadata

try:
__version__ = get_distribution('scimap').version
except DistributionNotFound:
__version__ = importlib.metadata.version('scimap')
except importlib.metadata.PackageNotFoundError:
__version__ = '(local)'

import scimap
Expand Down
6 changes: 5 additions & 1 deletion scimap/plotting/densityPlot2D.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,13 @@ def densityPlot2D (adata,


# set color
cp = copy.copy(cm.get_cmap(cmap))
#cp = copy.copy(cm.get_cmap(cmap))
#cp.set_under(alpha=0)

cp = copy.copy(plt.colormaps[cmap])
cp.set_under(alpha=0)


# subset data if neede
if subset is not None:
if isinstance (subset, str):
Expand Down
4 changes: 2 additions & 2 deletions scimap/plotting/heatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ def plot_category_heatmap_vectorized(data,
figsize_height = max(8, len(unique_categories) * base_size)
figsize=(figsize_width, figsize_height)

fig, ax = plt.subplots(figsize=figsize)
fig, ax = plt.subplots(figsize=figsize, constrained_layout=True)


# Heatmap
Expand Down Expand Up @@ -309,7 +309,7 @@ def plot_category_heatmap_vectorized(data,
ax.set_xlabel('Markers')
ax.set_ylabel('Categories')

plt.tight_layout(rect=[0, 0, 0.9, 0.9]) # Adjust the layout
#plt.tight_layout(rect=[0, 0, 0.9, 0.9]) # Adjust the layout

# Saving the figure if saveDir and fileName are provided
if saveDir:
Expand Down
7 changes: 4 additions & 3 deletions scimap/plotting/pie.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,15 +155,15 @@ def pie (adata,

else:
# if group_by is provided
prop = pd.DataFrame(data.groupby([group_by,phenotype]).size()).reset_index(inplace=False)
prop = pd.DataFrame(data.groupby([group_by,phenotype], observed=False).size()).reset_index(inplace=False)
prop.columns = ['group_by',phenotype,'value']
labels = np.unique(prop[phenotype])
#
if ncols is not None:
g = prop.groupby('group_by')
g = prop.groupby('group_by', observed=False)
rows = int(np.ceil(len(g)/ncols))
else:
g = prop.groupby('group_by')
g = prop.groupby('group_by', observed=False)
rows = 1
ncols = len(g)

Expand Down Expand Up @@ -193,6 +193,7 @@ def pie (adata,
final_axes = list(set(total_axes) ^ set(required_axes))
# Plot
fig, axes = plt.subplots(ncols=ncols, nrows=rows)
axes = np.atleast_1d(axes) # This ensures axes is always an array, even if it's a single subplot
for (c, grp), ax in zip(g, axes.flat):
ax.pie(grp.value, labels=label, colors=colors, wedgeprops =wedgeprops)
#ax.pie(grp.value, labels=label, colors=colors, wedgeprops = wedgeprops, **kwargs)
Expand Down
45 changes: 39 additions & 6 deletions scimap/plotting/voronoi.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"""

# import lib
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
Expand Down Expand Up @@ -129,6 +130,8 @@ def voronoi (adata,
overlay_point_alpha= 1,
overlay_point_shape=".",
plot_legend=True,
fileName='voronoi.pdf',
saveDir=None,
legend_size = 6, **kwargs):
"""
Parameters:
Expand Down Expand Up @@ -202,6 +205,12 @@ def voronoi (adata,
plot_legend (bool, optional):
Whether to display a legend for the plot.
fileName (str, optional):
Name of the file to save the plot. Relevant only if `saveDir` is not None.
saveDir (str, optional):
Directory to save the generated plot. If None, the plot is not saved.
legend_size (float, optional):
The font size of the legend text.
Expand Down Expand Up @@ -233,7 +242,7 @@ def voronoi (adata,


# create the data frame needed
data = adata.obs
data = adata.obs.copy()

# Subset the image of interest
if subset is not None:
Expand All @@ -253,13 +262,20 @@ def voronoi (adata,
y2 = min(data[y_coordinate])
else:
y2 = y_lim [1]

# do the actuall subsetting
#if x_lim is not None:
# data = data[data[x_coordinate] >= x1]
# data = data[data[x_coordinate] <= x2]
#if y_lim is not None:
# data = data[data[y_coordinate] <= y1]
# data = data[data[y_coordinate] >= y2]

# do the actuall subsetting
if x_lim is not None:
data = data[data[x_coordinate] >= x1]
data = data[data[x_coordinate] <= x2]
data = data[(data[x_coordinate] >= x1) & (data[x_coordinate] <= x2)]
if y_lim is not None:
data = data[data[y_coordinate] <= y1]
data = data[data[y_coordinate] >= y2]
data = data[(data[y_coordinate] >= y1) & (data[y_coordinate] <= y2)]


# create an extra column with index information
Expand Down Expand Up @@ -419,7 +435,12 @@ def voronoi (adata,
patchList.append(data_key)

first_legend = plt.legend(handles=patchList, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., prop={'size': legend_size})
plt.tight_layout()

try:
plt.tight_layout()
except:
pass

# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)

Expand All @@ -433,4 +454,16 @@ def voronoi (adata,
plt.legend(handles=patchList_scatter, bbox_to_anchor=(-0.05, 1), loc=1, borderaxespad=0., prop={'size': legend_size})
#plt.tight_layout()

# Saving the figure if saveDir and fileName are provided
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()



35 changes: 17 additions & 18 deletions scimap/tests/test_pl.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import pytest
import os
import anndata as ad
import unittest


# load data
Expand Down Expand Up @@ -179,26 +178,26 @@ def test_stacked_barplot (adata):
full_path = os.path.join(saveDir, fileName)
assert os.path.exists(full_path), f"File was not created: {full_path}"


# pie
# =============================================================================
# def test_pie (adata):
# from scimap.plotting.pie import pie
# saveDir = os.getcwd() + '/testFigures'
# fileName = 'pie.png'
#
# pie (adata)
#
#
# pie (adata, x_axis='imageid', y_axis='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}"
# =============================================================================

def test_pie (adata):
from scimap.plotting.pie import pie
saveDir = os.getcwd() + '/testFigures'
fileName = 'pie.png'
pie (adata, x_axis='imageid', y_axis='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}"

# voronoi

def test_voronoi (adata):
from scimap.plotting.voronoi import voronoi
saveDir = os.getcwd() + '/testFigures'
fileName = 'voronoi.png'
voronoi(adata, imageid='ROI', subset='ROI1', color_by='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}"


# image_viewer
# addROI_image
Expand Down
Binary file removed testFigures/_matrixplot.pdf
Binary file not shown.
Binary file removed testFigures/_ranked_markers_per_cluster.pdf
Binary file not shown.
Binary file removed testFigures/_umap.pdf
Binary file not shown.
Binary file removed testFigures/densityPlot2D.png
Binary file not shown.
Binary file removed testFigures/distPlot.png
Binary file not shown.
Binary file removed testFigures/foldchange.png
Binary file not shown.
Binary file removed testFigures/groupCorrelation.png
Binary file not shown.
Binary file removed testFigures/heatmap.png
Binary file not shown.
Binary file removed testFigures/markerCorrelation.png
Binary file not shown.
Binary file removed testFigures/spatialInteractionNetwork.png
Binary file not shown.
Binary file removed testFigures/spatial_distance.png
Binary file not shown.
Binary file removed testFigures/spatial_interaction.png
Binary file not shown.
Binary file removed testFigures/spatial_pscore.png
Binary file not shown.
Binary file removed testFigures/spatial_scatterPlot.png
Binary file not shown.
Binary file removed testFigures/stacked_barplot.png
Binary file not shown.
Binary file removed testFigures/umap.png
Binary file not shown.

0 comments on commit ba8d355

Please sign in to comment.