Skip to content

Commit 96a763d

Browse files
authored
Merge pull request #84 from AllenCell/reviewer_response_2
Reviewer response 2
2 parents 3031f6e + 6dcf2d0 commit 96a763d

3 files changed

Lines changed: 639 additions & 2 deletions

File tree

Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
import argparse
2+
import os
3+
import sys
4+
from pathlib import Path
5+
import pandas as pd
6+
import numpy as np
7+
from br.models.compute_features import get_embeddings
8+
from br.models.utils import get_all_configs_per_dataset
9+
from skimage import measure as skmeasure
10+
from skimage import morphology as skmorpho
11+
from tqdm import tqdm
12+
from br.features.classification import get_classification_df
13+
import matplotlib.pyplot as plt
14+
import seaborn as sns
15+
16+
17+
def get_surface_area(input_img):
18+
# Forces a 1 pixel-wide offset to avoid problems with binary
19+
# erosion algorithm
20+
input_img[:, :, [0, -1]] = 0
21+
input_img[:, [0, -1], :] = 0
22+
input_img[[0, -1], :, :] = 0
23+
input_img_surface = np.logical_xor(
24+
input_img, skmorpho.binary_erosion(input_img)
25+
).astype(np.uint8)
26+
# Loop through the boundary voxels to calculate the number of
27+
# boundary faces. Using 6-neighborhod.
28+
pxl_z, pxl_y, pxl_x = np.nonzero(input_img_surface)
29+
dx = np.array([0, -1, 0, 1, 0, 0])
30+
dy = np.array([0, 0, 1, 0, -1, 0])
31+
dz = np.array([-1, 0, 0, 0, 0, 1])
32+
surface_area = 0
33+
for (k, j, i) in zip(pxl_z, pxl_y, pxl_x):
34+
surface_area += 6 - (input_img[k + dz, j + dy, i + dx] > 0).sum()
35+
return int(surface_area)
36+
37+
38+
def get_basic_features(img):
39+
features = {}
40+
input_image = img.copy()
41+
input_image = (input_image > 0).astype(np.uint8)
42+
input_image_lcc = skmeasure.label(input_image)
43+
features["connectivity_cc"] = input_image_lcc.max()
44+
if features["connectivity_cc"] > 0:
45+
counts = np.bincount(input_image_lcc.reshape(-1))
46+
lcc = 1 + np.argmax(counts[1:])
47+
input_image_lcc[input_image_lcc != lcc] = 0
48+
input_image_lcc[input_image_lcc == lcc] = 1
49+
input_image_lcc = input_image_lcc.astype(np.uint8)
50+
for img, suffix in zip([input_image, input_image_lcc], ["", "_lcc"]):
51+
z, y, x = np.where(img)
52+
features[f"shape_volume{suffix}"] = img.sum()
53+
features[f"position_depth{suffix}"] = 1 + np.ptp(z)
54+
features[f"position_height{suffix}"] = 1 + np.ptp(y)
55+
features[f"position_width{suffix}"] = 1 + np.ptp(x)
56+
for uname, u in zip(["x", "y", "z"], [x, y, z]):
57+
features[f"position_{uname}_centroid{suffix}"] = u.mean()
58+
features[f"roundness_surface_area{suffix}"] = get_surface_area(img)
59+
else:
60+
for img, suffix in zip([input_image, input_image_lcc], ["", "_lcc"]):
61+
features[f"shape_volume{suffix}"] = np.nan
62+
features[f"position_depth{suffix}"] = np.nan
63+
features[f"position_height{suffix}"] = np.nan
64+
features[f"position_width{suffix}"] = np.nan
65+
for uname in ["x", "y", "z"]:
66+
features[f"position_{uname}_centroid{suffix}"] = np.nan
67+
features[f"roundness_surface_area{suffix}"] = np.nan
68+
return features
69+
70+
71+
def main(args):
72+
73+
config_path = os.environ.get("CYTODL_CONFIG_PATH")
74+
results_path = config_path + "/results/"
75+
DATASET_INFO = get_all_configs_per_dataset(results_path)
76+
77+
all_ret, orig_df = get_embeddings(
78+
["Rotation_invariant_pointcloud_SDF"],
79+
args.dataset_name,
80+
DATASET_INFO,
81+
args.embeddings_path,
82+
)
83+
orig_df["volume_of_nucleus_um3"] = orig_df["dna_shape_volume_lcc"] * 0.108**3
84+
85+
bins = [
86+
(247.407, 390.752),
87+
(390.752, 533.383),
88+
(533.383, 676.015),
89+
(676.015, 818.646),
90+
(818.646, 961.277),
91+
]
92+
correct_bins = []
93+
for ind, row in orig_df.iterrows():
94+
this_bin = []
95+
for bin_ in bins:
96+
if (row["volume_of_nucleus_um3"] > bin_[0]) and (
97+
row["volume_of_nucleus_um3"] <= bin_[1]
98+
):
99+
this_bin.append(bin_)
100+
if row["volume_of_nucleus_um3"] < bins[0][0]:
101+
this_bin.append(bin_)
102+
if row["volume_of_nucleus_um3"] > bins[4][1]:
103+
this_bin.append(bin_)
104+
assert len(this_bin) == 1
105+
correct_bins.append(this_bin[0])
106+
orig_df["vol_bins"] = correct_bins
107+
orig_df["vol_bins_inds"] = pd.factorize(orig_df["vol_bins"])[0]
108+
109+
all_feats = []
110+
for ind, row in tqdm(orig_df.iterrows(), total=len(orig_df)):
111+
img = np.load(row["seg_path"])
112+
feats = get_basic_features(img)
113+
feats["CellId"] = row["CellId"]
114+
all_feats.append(pd.DataFrame(feats, index=[0]))
115+
all_feats = pd.concat(all_feats, axis=0)
116+
all_feats = all_feats.merge(
117+
orig_df[["CellId", "vol_bins", "vol_bins_inds"]], on="CellId"
118+
)
119+
all_feats["mean_volume"] = all_feats["shape_volume"] / all_feats["connectivity_cc"]
120+
all_feats["mean_surface_area"] = (
121+
all_feats["roundness_surface_area"] / all_feats["connectivity_cc"]
122+
)
123+
124+
all_feats = all_feats.merge(
125+
orig_df[["CellId", "STR_connectivity_cc_thresh"]], on="CellId"
126+
)
127+
all_feats = all_feats.loc[all_feats["CellId"] != 724520].reset_index(
128+
drop=True
129+
) # nan row
130+
all_ret = all_ret.loc[all_ret["CellId"] != 724520].reset_index(drop=True) # nan row
131+
assert not all_feats["mean_surface_area"].isna().any()
132+
133+
all_ret = all_ret.merge(
134+
orig_df[["CellId", "vol_bins", "vol_bins_inds"]],
135+
on="CellId",
136+
)
137+
from br.features.classification import get_classification_df
138+
139+
all_baseline = []
140+
all_feats["model"] = "baseline"
141+
for bin in all_feats["vol_bins"].unique():
142+
this = all_feats.loc[all_feats["vol_bins"] == bin].reset_index(drop=True)
143+
baseline = get_classification_df(
144+
this,
145+
"STR_connectivity_cc_thresh",
146+
None,
147+
["mean_volume", "mean_surface_area"],
148+
)
149+
baseline["vol_bin"] = str(bin)
150+
all_baseline.append(baseline)
151+
all_baseline = pd.concat(all_baseline, axis=0)
152+
153+
all_ret["model"] = "reps"
154+
all_reps = []
155+
for bin in all_ret["vol_bins"].unique():
156+
this = all_ret.loc[all_ret["vol_bins"] == bin].reset_index(drop=True)
157+
reps = get_classification_df(this, "STR_connectivity_cc_thresh", None, None)
158+
reps["vol_bin"] = str(bin)
159+
all_reps.append(reps)
160+
all_reps = pd.concat(all_reps, axis=0)
161+
all_reps["features"] = "Rotation invariant point cloud representation"
162+
all_baseline["features"] = "Mean nucleoli volume and surface area"
163+
plot = pd.concat([all_reps, all_baseline], axis=0)
164+
map_ = {
165+
"reps": "Rotation invariant point cloud representation",
166+
"baseline": "Mean nucleoli volume and surface area",
167+
}
168+
plot["model"] = plot["model"].replace(map_)
169+
170+
fig, ax = plt.subplots(1, 1, figsize=(5, 5))
171+
x_order = [
172+
"(247.407, 390.752)",
173+
"(390.752, 533.383)",
174+
"(533.383, 676.015)",
175+
"(676.015, 818.646)",
176+
"(818.646, 961.277)",
177+
]
178+
g = sns.boxplot(
179+
ax=ax, data=plot, x="vol_bin", y="top_1_acc", hue="features", order=x_order
180+
)
181+
plt.xticks(rotation=30)
182+
ax.set_xticklabels(
183+
["0", "1", "2", "3", "4"], rotation=0
184+
) # Set tick labels, rotate for readability
185+
ax.set_ylabel("Accuracy")
186+
ax.set_xlabel("Volume bin")
187+
188+
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
189+
fig.savefig(
190+
args.save_path + "classification_number_pieces.png",
191+
bbox_inches="tight",
192+
dpi=300,
193+
)
194+
# fig.savefig("classification_number_pieces_nogrouping.png", bbox_inches="tight", dpi=300)
195+
196+
197+
if __name__ == "__main__":
198+
parser = argparse.ArgumentParser(
199+
description="Script for computing perturbation detection metrics"
200+
)
201+
parser.add_argument(
202+
"--save_path", type=str, required=True, help="Path to save the results."
203+
)
204+
parser.add_argument(
205+
"--embeddings_path",
206+
type=str,
207+
required=True,
208+
help="Path to the saved embeddings.",
209+
)
210+
parser.add_argument(
211+
"--dataset_name", type=str, required=True, help="Name of the dataset."
212+
)
213+
args = parser.parse_args()
214+
215+
# Validate that required paths are provided
216+
if not args.save_path or not args.embeddings_path:
217+
print("Error: Required arguments are missing.")
218+
sys.exit(1)
219+
220+
main(args)
221+
222+
"""
223+
Example run:
224+
225+
python src/br/analysis/run_classification.py --save_path "./outputs_npm1/" --embeddings_path "./morphology_appropriate_representation_learning/model_embeddings/npm1/" --dataset_name "npm1"
226+
"""

0 commit comments

Comments
 (0)