Skip to content

Commit 3dd2abd

Browse files
committed
added tests for the utils module
1 parent 8a92740 commit 3dd2abd

3 files changed

Lines changed: 337 additions & 0 deletions

File tree

‎tests/test_processing.py‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import pytest
2+
import numpy as np
3+
import pandas as pd
4+
from decoupling.utils.preprocessing import (
5+
set_seed,
6+
align_inputs,
7+
preprocess_features,
8+
get_low_variance_features,
9+
get_high_correlation_features,
10+
)
11+
from decoupling.utils.postprocessing import remap_labels
12+
13+
#----------------------------------------
14+
def test_set_seed_consistency():
15+
"""
16+
Verify that set_seed reproducibly sets the random seed for NumPy
17+
such that identical calls produce the same random numbers.
18+
"""
19+
seed = set_seed(42, verbose=False)
20+
arr1 = np.random.rand(3)
21+
set_seed(42, verbose=False)
22+
arr2 = np.random.rand(3)
23+
np.testing.assert_array_equal(arr1, arr2)
24+
25+
#----------------------------------------
26+
def test_align_inputs_basic():
27+
"""
28+
Ensure align_inputs correctly aligns two DataFrames with identical indices,
29+
returning both DataFrames unchanged and the original index as an array.
30+
"""
31+
df1 = pd.DataFrame({"a":[1,2,3]}, index=["s1","s2","s3"])
32+
df2 = pd.DataFrame({"b":[4,5,6]}, index=["s1","s2","s3"])
33+
M, E, ids = align_inputs(df1, df2)
34+
pd.testing.assert_frame_equal(M, df1)
35+
pd.testing.assert_frame_equal(E, df2)
36+
np.testing.assert_array_equal(ids, np.array(["s1","s2","s3"]))
37+
38+
#----------------------------------------
39+
def test_align_inputs_partial_overlap():
40+
"""
41+
Verify that align_inputs returns only the overlapping indices
42+
when the input DataFrames partially overlap.
43+
"""
44+
df1 = pd.DataFrame({"a":[1,2,3]}, index=["s1","s2","s3"])
45+
df2 = pd.DataFrame({"b":[4,5,6]}, index=["s2","s3","s4"])
46+
M, E, ids = align_inputs(df1, df2)
47+
np.testing.assert_array_equal(ids, np.array(["s2","s3"]))
48+
assert list(M.index) == ["s2","s3"]
49+
assert list(E.index) == ["s2","s3"]
50+
51+
#----------------------------------------
52+
def test_align_inputs_no_overlap_raises():
53+
"""
54+
Confirm that align_inputs raises a ValueError when the DataFrames
55+
have no overlapping indices.
56+
"""
57+
df1 = pd.DataFrame({"a":[1]}, index=["s1"])
58+
df2 = pd.DataFrame({"b":[2]}, index=["s2"])
59+
with pytest.raises(ValueError):
60+
align_inputs(df1, df2)
61+
62+
#----------------------------------------
63+
def test_preprocess_features_filters():
64+
"""
65+
Ensure preprocess_features correctly filters out low-variance
66+
features and highly correlated features according to thresholds.
67+
"""
68+
X = pd.DataFrame({
69+
"low_var": [1,1,1,1],
70+
"high_corr1": [1,2,3,4],
71+
"high_corr2": [2,4,6,8],
72+
"normal": [1,2,1,2],
73+
})
74+
processed = preprocess_features(X, low_var_thresh=0.01, corr_thresh=0.9)
75+
assert "low_var" not in processed.columns
76+
assert "high_corr2" not in processed.columns
77+
assert "high_corr1" in processed.columns
78+
assert "normal" in processed.columns
79+
80+
#----------------------------------------
81+
def test_get_low_variance_features():
82+
"""
83+
Verify get_low_variance_features identifies columns with variance below a threshold.
84+
"""
85+
X = pd.DataFrame({
86+
"a":[1,1,1],
87+
"b":[1,2,3],
88+
})
89+
low_var = get_low_variance_features(X, 0.01)
90+
assert low_var == ["a"]
91+
92+
#----------------------------------------
93+
def test_get_high_correlation_features():
94+
"""
95+
Verify get_high_correlation_features identifies columns
96+
that are highly correlated with any other column above a threshold.
97+
"""
98+
X = pd.DataFrame({
99+
"x":[1,2,3],
100+
"y":[2,4,6],
101+
"z":[1,2,1],
102+
})
103+
high_corr = get_high_correlation_features(X, 0.9)
104+
assert "y" in high_corr
105+
106+
#----------------------------------------
107+
def test_remap_labels_ordering():
108+
"""
109+
Ensure remap_labels maps cluster labels to a consecutive range starting from 1
110+
while preserving the number of samples.
111+
"""
112+
X = pd.DataFrame({
113+
"f1":[0,0,1,1],
114+
"f2":[0,1,0,1]
115+
})
116+
labels = np.array([0,0,1,1])
117+
remapped = remap_labels(X, labels)
118+
assert remapped.min() == 1
119+
assert remapped.max() == 2
120+
assert remapped.shape[0] == len(labels)

‎tests/test_profiles.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import numpy as np
2+
from decoupling.utils.postprocessing import compute_molecular_profiles
3+
4+
#----------------------------------------
5+
def generate_dummy_data(n=50, seed=0):
6+
"""
7+
Helper function to generate synthetic marker and soma depth data
8+
for testing molecular profile computations.
9+
"""
10+
rng = np.random.default_rng(seed)
11+
soma_depth = rng.uniform(0, 2, n)
12+
markers = rng.choice(
13+
["PV", "Sst", "Vip", "-/-/-"],
14+
size=n
15+
)
16+
return markers, soma_depth
17+
18+
#----------------------------------------
19+
def test_compute_profiles_structure():
20+
"""
21+
Ensure the output of compute_molecular_profiles contains
22+
all required columns: depth, marker, counts, fraction.
23+
"""
24+
markers, soma_depth = generate_dummy_data()
25+
profiles = compute_molecular_profiles(
26+
markers=markers,
27+
soma_depth=soma_depth
28+
)
29+
required_columns = {"depth", "marker", "counts", "fraction"}
30+
assert required_columns.issubset(profiles.columns)
31+
32+
#----------------------------------------
33+
def test_profiles_depth_not_lost():
34+
"""
35+
Verify that depth information is preserved in the computed profiles
36+
and no NaN values are present.
37+
"""
38+
markers, soma_depth = generate_dummy_data()
39+
profiles = compute_molecular_profiles(
40+
markers=markers,
41+
soma_depth=soma_depth
42+
)
43+
assert "depth" in profiles.columns
44+
assert profiles["depth"].notna().all()
45+
46+
#----------------------------------------
47+
def test_profiles_fraction_range():
48+
"""
49+
Ensure that the fraction column in profiles is between 0 and 100.
50+
"""
51+
markers, soma_depth = generate_dummy_data()
52+
profiles = compute_molecular_profiles(
53+
markers=markers,
54+
soma_depth=soma_depth
55+
)
56+
assert profiles["fraction"].min() >= 0
57+
assert profiles["fraction"].max() <= 100
58+
59+
#----------------------------------------
60+
def test_profiles_fraction_normalization():
61+
"""
62+
Check that the counts per depth bin sum to 100 after normalization.
63+
"""
64+
markers, soma_depth = generate_dummy_data()
65+
profiles = compute_molecular_profiles(
66+
markers=markers,
67+
soma_depth=soma_depth
68+
)
69+
sums = profiles.groupby("depth")["counts"].sum()
70+
sums = sums[sums > 0]
71+
assert np.allclose(sums.values, 100, atol=1e-6)
72+
73+
#----------------------------------------
74+
def test_profiles_handles_empty_marker_group():
75+
"""
76+
Ensure the function works even if some marker groups are not present
77+
in the input data.
78+
"""
79+
soma_depth = np.array([0.1, 0.2, 0.3])
80+
markers = np.array(["PV", "PV", "PV"])
81+
profiles = compute_molecular_profiles(
82+
markers=markers,
83+
soma_depth=soma_depth
84+
)
85+
assert len(profiles) > 0

‎tests/test_visualization.py‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import numpy as np
2+
import pandas as pd
3+
from decoupling.utils.visualization import (
4+
rotation_matrix,
5+
linear_reg_coeffs,
6+
plot_embedding,
7+
default_colormap,
8+
plot_embedding_by_layer,
9+
plot_features_by_layer,
10+
plot_decoupling_schema,
11+
colorbar,
12+
)
13+
import matplotlib
14+
matplotlib.use("Agg")
15+
import matplotlib.pyplot as plt
16+
plt.ioff()
17+
18+
#----------------------------------------
19+
def test_rotation_matrix_properties():
20+
"""
21+
Ensure the rotation_matrix function returns a valid rotation matrix:
22+
- determinant equals 1
23+
- inverse equals the transpose
24+
"""
25+
theta = np.pi / 4
26+
R = rotation_matrix(theta)
27+
det = np.linalg.det(R)
28+
assert np.isclose(det, 1.0)
29+
assert np.allclose(np.linalg.inv(R), R.T)
30+
31+
#----------------------------------------
32+
def test_linear_reg_coeffs_basic():
33+
"""
34+
Linear regression should correctly compute the slope coefficient.
35+
"""
36+
X = np.array([[1], [2], [3]])
37+
y = np.array([2, 4, 6])
38+
coeffs = linear_reg_coeffs(X, y)
39+
assert np.allclose(coeffs, [2.0])
40+
41+
#----------------------------------------
42+
def test_plot_embedding_output():
43+
"""
44+
plot_embedding should return a valid figure and axis.
45+
"""
46+
np.random.seed(0)
47+
X_emb = np.random.rand(5, 2)
48+
colors = np.array([0, 1, 0, 1, 0])
49+
fig, ax = plot_embedding(X_emb, colors)
50+
assert fig is not None
51+
assert ax is not None
52+
plt.close(fig)
53+
54+
#----------------------------------------
55+
def test_default_colormap_type():
56+
"""
57+
default_colormap should return a Matplotlib ListedColormap.
58+
"""
59+
cmap = default_colormap()
60+
from matplotlib.colors import ListedColormap
61+
assert isinstance(cmap, ListedColormap)
62+
63+
#----------------------------------------
64+
def test_plot_embedding_by_layer_shapes():
65+
"""
66+
plot_embedding_by_layer should produce a figure with the expected grid
67+
of subplots for layer-wise features.
68+
"""
69+
np.random.seed(0)
70+
embedding = np.random.rand(10, 2)
71+
feature = np.linspace(0, 1, 10)
72+
layers = np.array([0, 1, 2, 0, 1, 2, 3, 4, 2, 4])
73+
fig, axes = plot_embedding_by_layer(embedding, feature, layers)
74+
assert fig is not None
75+
assert axes.shape[0] == 6 # 2x3 grid flattened
76+
plt.close(fig)
77+
78+
#----------------------------------------
79+
def test_plot_features_by_layer_basic():
80+
"""
81+
plot_features_by_layer should create a figure and axes for each feature group.
82+
"""
83+
X = pd.DataFrame({
84+
"layer": [0,0,1,1],
85+
"feat1": [1,2,1,2],
86+
"feat2": [2,3,2,3]
87+
})
88+
ticks = [[0,1,2,3],[0,1,2,3]]
89+
fig, axs = plot_features_by_layer(X, ticks)
90+
assert fig is not None
91+
assert len(axs) == 2
92+
plt.close(fig)
93+
94+
#----------------------------------------
95+
def test_plot_decoupling_schema_runs():
96+
"""
97+
plot_decoupling_schema should produce a figure with one axis per schema group.
98+
"""
99+
cluster_means = pd.DataFrame({
100+
"spike_frequency": [-0.5, 0, 0.5],
101+
"spike_frequency_adaptation": [-0.4, 0, 0.4],
102+
"dendrite_vertical_extent": [-1,0,1],
103+
"axon_vertical_extent": [-1,0,1],
104+
})
105+
schema = {
106+
"Group I": {"spike_frequency": (">", 0), "spike_frequency_adaptation": ("<", 0)},
107+
"Group II": {"axon_vertical_extent": ("<", 0), "dendrite_vertical_extent": (">", 0)}
108+
}
109+
fig, axs = plot_decoupling_schema(cluster_means, schema)
110+
assert fig is not None
111+
assert len(axs) == len(schema)
112+
plt.close(fig)
113+
114+
#----------------------------------------
115+
def test_colorbar_creation_continuous_and_categorical():
116+
"""
117+
colorbar should work for both continuous and categorical color mappings.
118+
"""
119+
# Continuous
120+
fig, ax = plt.subplots()
121+
points = ax.scatter(np.arange(5), np.arange(5), c=np.linspace(0,1,5))
122+
cbar1 = colorbar(fig, ax)
123+
assert cbar1 is not None
124+
plt.close(fig)
125+
126+
# Categorical
127+
fig, ax = plt.subplots()
128+
labels = np.array([0,1,0,1,2])
129+
points = ax.scatter(np.arange(5), np.arange(5), c=labels)
130+
cbar2 = colorbar(fig, ax, labels=labels)
131+
assert cbar2 is not None
132+
plt.close(fig)

0 commit comments

Comments
 (0)