Skip to content

Commit 17a6778

Browse files
authored
Merge branch 'master' into update_measure_synapses
2 parents 4087d3b + 13fe35a commit 17a6778

File tree

6 files changed

+288
-56
lines changed

6 files changed

+288
-56
lines changed

scripts/figures/plot_fig2.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from util import literature_reference_values, SYNAPSE_DIR_ROOT
1212

1313
png_dpi = 300
14+
FILE_EXTENSION = "png"
1415

1516

1617
def scramble_instance_labels(arr):
@@ -58,7 +59,10 @@ def plot_seg_crop(img_path, seg_path, save_path, xlim1, xlim2, ylim1, ylim2, bou
5859
ax.imshow(boundary_overlay)
5960
ax.axis("off")
6061
plt.tight_layout()
61-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
62+
if ".png" in save_path:
63+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
64+
else:
65+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
6266

6367
if plot:
6468
plt.show()
@@ -149,12 +153,12 @@ def fig_02c(save_path, plot=False, all_versions=False):
149153
versions = [version_1, version_2, version_3]
150154
settings = [settings_1, settings_2, settings_3]
151155
save_suffix = ["_v4b", "_v4c", "_v4c_filter"]
152-
save_paths = [save_path + i for i in save_suffix]
156+
save_paths = [save_path.split(".")[0] + i + "." + save_path.split(".")[1] for i in save_suffix]
153157
else:
154158
versions = [version_2]
155159
settings = [settings_2]
156160
save_suffix = ["_v4c"]
157-
save_paths = [save_path + i for i in save_suffix]
161+
save_paths = [save_path.split(".")[0] + i + "." + save_path.split(".")[1] for i in save_suffix]
158162

159163
for version, setting, save_path in zip(versions, settings, save_paths):
160164
precision = [i[0] for i in version]
@@ -193,7 +197,11 @@ def fig_02c(save_path, plot=False, all_versions=False):
193197
plt.grid(axis="y", linestyle="--", alpha=0.5)
194198

195199
plt.tight_layout()
196-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
200+
201+
if ".png" in save_path:
202+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
203+
else:
204+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
197205

198206
if plot:
199207
plt.show()
@@ -239,7 +247,7 @@ def fig_02d_01(save_path, plot=False, all_versions=False, plot_average_ribbon_sy
239247
fig, axes = plt.subplots(rows, columns, figsize=(columns*4, rows*4))
240248
ax = axes.flatten()
241249

242-
save_path_new = save_path + suffix
250+
save_path_new = save_path.split(".")[0] + suffix + "." + save_path.split(".")[1]
243251
ax[0].boxplot(sgn_values)
244252
ax[1].boxplot(ihc_values)
245253

@@ -308,7 +316,11 @@ def fig_02d_01(save_path, plot=False, all_versions=False, plot_average_ribbon_sy
308316
ax[2].fill_between([xmin, xmax], lower_y, upper_y, color="C0", alpha=0.05, interpolate=True)
309317

310318
plt.tight_layout()
311-
plt.savefig(save_path_new, dpi=png_dpi)
319+
320+
if ".png" in save_path:
321+
plt.savefig(save_path_new, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
322+
else:
323+
plt.savefig(save_path_new, bbox_inches='tight', pad_inches=0)
312324

313325
if plot:
314326
plt.show()
@@ -386,7 +398,11 @@ def fig_02d_02(save_path, filter_zeros=True, plot=False):
386398
plt.grid(axis="y", linestyle="--", alpha=0.5)
387399
plt.legend(fontsize=legendsize)
388400
plt.tight_layout()
389-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
401+
402+
if ".png" in save_path:
403+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
404+
else:
405+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
390406

391407
if plot:
392408
plt.show()
@@ -404,14 +420,14 @@ def main():
404420

405421
# Panes A and B: Qualitative comparison of visualization results.
406422
fig_02a_sgn(save_dir=args.figure_dir, plot=args.plot)
407-
return
408423
fig_02b_ihc(save_dir=args.figure_dir, plot=args.plot)
409424

410425
# Panel C: Evaluation of the segmentation results:
411-
fig_02c(save_path=os.path.join(args.figure_dir, "fig_02c"), plot=args.plot, all_versions=False)
426+
fig_02c(save_path=os.path.join(args.figure_dir, f"fig_02c.{FILE_EXTENSION}"), plot=args.plot, all_versions=False)
412427

413428
# Panel D: The number of SGNs, IHCs and average number of ribbon synapses per IHC
414-
fig_02d_01(save_path=os.path.join(args.figure_dir, "fig_02d"), plot=args.plot, plot_average_ribbon_synapses=True)
429+
fig_02d_01(save_path=os.path.join(args.figure_dir, f"fig_02d.{FILE_EXTENSION}"),
430+
plot=args.plot, plot_average_ribbon_synapses=True)
415431

416432
# Alternative version of synapse distribution for panel D.
417433
# fig_02d_02(save_path=os.path.join(args.figure_dir, "fig_02d_02"), plot=args.plot)

scripts/figures/plot_fig3.py

Lines changed: 104 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import argparse
2+
import json
23
import os
4+
import pickle
5+
36
import imageio.v3 as imageio
47
from glob import glob
58
from pathlib import Path
@@ -10,6 +13,7 @@
1013
import pandas as pd
1114
from matplotlib import cm, colors
1215

16+
from flamingo_tools.s3_utils import BUCKET_NAME, create_s3_target
1317
from util import sliding_runlength_sum, frequency_mapping, SYNAPSE_DIR_ROOT, to_alias
1418

1519
# INPUT_ROOT = "/home/pape/Work/my_projects/flamingo-tools/scripts/M_LR_000227_R/scale3"
@@ -23,8 +27,72 @@
2327
"Type-II": "Prph",
2428
}
2529

30+
FILE_EXTENSION = "png"
31+
2632
png_dpi = 300
2733

34+
# The cochlea for the CHReef analysis.
35+
COCHLEAE_DICT = {
36+
"M_LR_000226_L": {"alias": "M01L", "component": [1]},
37+
"M_LR_000226_R": {"alias": "M01R", "component": [1]},
38+
"M_LR_000227_L": {"alias": "M02L", "component": [1]},
39+
"M_LR_000227_R": {"alias": "M02R", "component": [1]},
40+
}
41+
42+
43+
def get_tonotopic_data():
44+
s3 = create_s3_target()
45+
source_name = "IHC_v4c"
46+
ihc_version = source_name.split("_")[1]
47+
cache_path = "./tonotopic_data.pkl"
48+
cochleae = [key for key in COCHLEAE_DICT.keys()]
49+
50+
if os.path.exists(cache_path):
51+
with open(cache_path, "rb") as f:
52+
return pickle.load(f)
53+
54+
chreef_data = {}
55+
for cochlea in cochleae:
56+
print("Processsing cochlea:", cochlea)
57+
content = s3.open(f"{BUCKET_NAME}/{cochlea}/dataset.json", mode="r", encoding="utf-8")
58+
info = json.loads(content.read())
59+
sources = info["sources"]
60+
61+
# Load the seg table and filter the compartments.
62+
source = sources[source_name]["segmentation"]
63+
rel_path = source["tableData"]["tsv"]["relativePath"]
64+
table_content = s3.open(os.path.join(BUCKET_NAME, cochlea, rel_path, "default.tsv"), mode="rb")
65+
table = pd.read_csv(table_content, sep="\t")
66+
67+
# May need to be adjusted for some cochleae.
68+
component_labels = COCHLEAE_DICT[cochlea]["component"]
69+
print(cochlea, component_labels)
70+
table = table[table.component_labels.isin(component_labels)]
71+
ihc_dir = f"ihc_counts_{ihc_version}"
72+
synapse_dir = f"/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/predictions/synapses/{ihc_dir}"
73+
tab_path = os.path.join(synapse_dir, f"ihc_count_{cochlea}.tsv")
74+
syn_tab = pd.read_csv(tab_path, sep="\t")
75+
syn_ids = syn_tab["label_id"].values
76+
77+
syn_per_ihc = [0 for _ in range(len(table))]
78+
table.loc[:, "syn_per_IHC"] = syn_per_ihc
79+
for syn_id in syn_ids:
80+
table.loc[table["label_id"] == syn_id, "syn_per_IHC"] = syn_tab.at[syn_tab.index[syn_tab["label_id"] == syn_id][0], "synapse_count"] # noqa
81+
82+
# The relevant values for analysis.
83+
try:
84+
values = table[["label_id", "length[µm]", "frequency[kHz]", "syn_per_IHC"]]
85+
except KeyError:
86+
print("Could not find the values for", cochlea, "it will be skippped.")
87+
continue
88+
89+
chreef_data[cochlea] = values
90+
91+
with open(cache_path, "wb") as f:
92+
pickle.dump(chreef_data, f)
93+
with open(cache_path, "rb") as f:
94+
return pickle.load(f)
95+
2896

2997
def _plot_colormap(vol, title, plot, save_path):
3098
# before creating the figure:
@@ -53,7 +121,10 @@ def _plot_colormap(vol, title, plot, save_path):
53121
if plot:
54122
plt.show()
55123

56-
plt.savefig(save_path)
124+
if ".png" in save_path:
125+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
126+
else:
127+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
57128
plt.close()
58129

59130

@@ -99,26 +170,31 @@ def fig_03c_rl(save_path, plot=False):
99170
ax.legend(title="cochlea")
100171
plt.tight_layout()
101172

102-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
173+
if ".png" in save_path:
174+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
175+
else:
176+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
177+
103178
if plot:
104179
plt.show()
105180
else:
106181
plt.close()
107182

108183

109-
def fig_03c_octave(save_path, plot=False):
184+
def fig_03c_octave(tonotopic_data, save_path, plot=False, use_alias=True):
110185
ihc_version = "ihc_counts_v4c"
111186
tables = glob(os.path.join(SYNAPSE_DIR_ROOT, ihc_version, "ihc_count_M_LR*.tsv"))
112187
assert len(tables) == 4, len(tables)
113188

114189
result = {"cochlea": [], "octave_band": [], "value": []}
115-
for tab_path in tables:
116-
cochlea = Path(tab_path).stem.lstrip("ihc_count")
117-
alias = to_alias(cochlea)
118-
tab = pd.read_csv(tab_path, sep="\t")
119-
freq = tab["frequency"].values
120-
syn_count = tab["synapse_count"].values
121-
190+
for name, values in tonotopic_data.items():
191+
if use_alias:
192+
alias = COCHLEAE_DICT[name]["alias"]
193+
else:
194+
alias = name.replace("_", "").replace("0", "")
195+
196+
freq = values["frequency[kHz]"].values
197+
syn_count = values["syn_per_IHC"].values
122198
octave_binned = frequency_mapping(freq, syn_count, animal="mouse")
123199

124200
result["cochlea"].extend([alias] * len(octave_binned))
@@ -142,7 +218,11 @@ def fig_03c_octave(save_path, plot=False):
142218
ax.set_title("Ribbon synapse count per octave band")
143219
plt.legend(title="Cochlea")
144220

145-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
221+
if ".png" in save_path:
222+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
223+
else:
224+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
225+
146226
if plot:
147227
plt.show()
148228
else:
@@ -200,7 +280,11 @@ def fig_03d_fraction(save_path, plot):
200280
ax.set_xlabel("Type")
201281
ax.legend(title="Cochlea ID")
202282

203-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
283+
if ".png" in save_path:
284+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
285+
else:
286+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
287+
204288
if plot:
205289
plt.show()
206290
else:
@@ -219,21 +303,22 @@ def main():
219303
args = parser.parse_args()
220304

221305
os.makedirs(args.figure_dir, exist_ok=True)
306+
tonotopic_data = get_tonotopic_data()
222307

223308
# Panel A: Tonotopic mapping of SGNs and IHCs (rendering in napari + heatmap)
224-
fig_03a(save_path=os.path.join(args.figure_dir, f"fig_03a_cmap.{FILE_EXTENSION}"),
225-
plot=args.plot, plot_napari=False)
309+
# fig_03a(save_path=os.path.join(args.figure_dir, f"fig_03a_cmap.{FILE_EXTENSION}"),
310+
# plot=args.plot, plot_napari=True)
226311

227312
# Panel C: Spatial distribution of synapses across the cochlea.
228313
# We have two options: running sum over the runlength or per octave band
229314
# fig_03c_rl(save_path=os.path.join(args.figure_dir, f"fig_03c_runlength.{FILE_EXTENSION}"), plot=args.plot)
230-
# fig_03c_octave(tonotopic_data=tonotopic_data,
231-
# save_path=os.path.join(args.figure_dir, f"fig_03c_octave.{FILE_EXTENSION}"),
232-
# plot=args.plot)
315+
fig_03c_octave(tonotopic_data=tonotopic_data,
316+
save_path=os.path.join(args.figure_dir, f"fig_03c_octave.{FILE_EXTENSION}"),
317+
plot=args.plot)
233318

234319
# Panel D: Spatial distribution of SGN sub-types.
235-
fig_03d_fraction(save_path=os.path.join(args.figure_dir, "fig_03d_fraction.png"), plot=args.plot)
236-
fig_03d_octave(save_path=os.path.join(args.figure_dir, "fig_03d_octave.png"), plot=args.plot)
320+
# fig_03d_fraction(save_path=os.path.join(args.figure_dir, f"fig_03d_fraction.{FILE_EXTENSION}"), plot=args.plot)
321+
# fig_03d_octave(save_path=os.path.join(args.figure_dir, f"fig_03d_octave.{FILE_EXTENSION}"), plot=args.plot)
237322

238323

239324
if __name__ == "__main__":

0 commit comments

Comments
 (0)