Skip to content

Commit 13fe35a

Browse files
committed
Update figures with option for file extension
1 parent ff08ecc commit 13fe35a

File tree

6 files changed

+289
-54
lines changed

6 files changed

+289
-54
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: 105 additions & 17 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"
@@ -21,8 +25,72 @@
2125
"Type-II": "Prph",
2226
}
2327

28+
FILE_EXTENSION = "png"
29+
2430
png_dpi = 300
2531

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

2795
def _plot_colormap(vol, title, plot, save_path):
2896
# before creating the figure:
@@ -51,7 +119,10 @@ def _plot_colormap(vol, title, plot, save_path):
51119
if plot:
52120
plt.show()
53121

54-
plt.savefig(save_path)
122+
if ".png" in save_path:
123+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
124+
else:
125+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
55126
plt.close()
56127

57128

@@ -97,26 +168,31 @@ def fig_03c_rl(save_path, plot=False):
97168
ax.legend(title="cochlea")
98169
plt.tight_layout()
99170

100-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
171+
if ".png" in save_path:
172+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
173+
else:
174+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
175+
101176
if plot:
102177
plt.show()
103178
else:
104179
plt.close()
105180

106181

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

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

122198
result["cochlea"].extend([alias] * len(octave_binned))
@@ -140,7 +216,11 @@ def fig_03c_octave(save_path, plot=False):
140216
ax.set_title("Ribbon synapse count per octave band")
141217
plt.legend(title="Cochlea")
142218

143-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
219+
if ".png" in save_path:
220+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
221+
else:
222+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
223+
144224
if plot:
145225
plt.show()
146226
else:
@@ -198,7 +278,11 @@ def fig_03d_fraction(save_path, plot):
198278
ax.set_xlabel("Type")
199279
ax.legend(title="Cochlea ID")
200280

201-
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
281+
if ".png" in save_path:
282+
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1, dpi=png_dpi)
283+
else:
284+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
285+
202286
if plot:
203287
plt.show()
204288
else:
@@ -217,18 +301,22 @@ def main():
217301
args = parser.parse_args()
218302

219303
os.makedirs(args.figure_dir, exist_ok=True)
304+
tonotopic_data = get_tonotopic_data()
220305

221306
# Panel A: Tonotopic mapping of SGNs and IHCs (rendering in napari + heatmap)
222-
fig_03a(save_path=os.path.join(args.figure_dir, "fig_03a_cmap.png"), plot=args.plot, plot_napari=True)
307+
# fig_03a(save_path=os.path.join(args.figure_dir, f"fig_03a_cmap.{FILE_EXTENSION}"),
308+
# plot=args.plot, plot_napari=True)
223309

224310
# Panel C: Spatial distribution of synapses across the cochlea.
225311
# We have two options: running sum over the runlength or per octave band
226-
fig_03c_rl(save_path=os.path.join(args.figure_dir, "fig_03c_runlength.png"), plot=args.plot)
227-
fig_03c_octave(save_path=os.path.join(args.figure_dir, "fig_03c_octave.png"), plot=args.plot)
312+
# fig_03c_rl(save_path=os.path.join(args.figure_dir, f"fig_03c_runlength.{FILE_EXTENSION}"), plot=args.plot)
313+
fig_03c_octave(tonotopic_data=tonotopic_data,
314+
save_path=os.path.join(args.figure_dir, f"fig_03c_octave.{FILE_EXTENSION}"),
315+
plot=args.plot)
228316

229317
# Panel D: Spatial distribution of SGN sub-types.
230-
fig_03d_fraction(save_path=os.path.join(args.figure_dir, "fig_03d_fraction.png"), plot=args.plot)
231-
fig_03d_octave(save_path=os.path.join(args.figure_dir, "fig_03d_octave.png"), plot=args.plot)
318+
# fig_03d_fraction(save_path=os.path.join(args.figure_dir, f"fig_03d_fraction.{FILE_EXTENSION}"), plot=args.plot)
319+
# fig_03d_octave(save_path=os.path.join(args.figure_dir, f"fig_03d_octave.{FILE_EXTENSION}"), plot=args.plot)
232320

233321

234322
if __name__ == "__main__":

0 commit comments

Comments
 (0)