Skip to content

Commit c77b385

Browse files
Add script for frequency mapping export
1 parent 39b313f commit c77b385

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import argparse
2+
import json
3+
import os
4+
5+
import matplotlib.pyplot as plt
6+
import numpy as np
7+
import pandas as pd
8+
import tifffile
9+
import zarr
10+
from matplotlib import cm, colors
11+
12+
from flamingo_tools.s3_utils import BUCKET_NAME, SERVICE_ENDPOINT, create_s3_target, get_s3_path
13+
# from tqdm import tqdm
14+
15+
16+
def export_frequency_mapping(cochlea, scale, output_folder, source_name, colormap=None):
17+
s3 = create_s3_target()
18+
19+
content = s3.open(f"{BUCKET_NAME}/{cochlea}/dataset.json", mode="r", encoding="utf-8")
20+
info = json.loads(content.read())
21+
sources = info["sources"]
22+
23+
# Load the seg table and filter the compartments.
24+
source = sources[source_name]["segmentation"]
25+
rel_path = source["tableData"]["tsv"]["relativePath"]
26+
table_content = s3.open(os.path.join(BUCKET_NAME, cochlea, rel_path, "default.tsv"), mode="rb")
27+
table = pd.read_csv(table_content, sep="\t")
28+
max_id = int(table.label_id.values.max())
29+
table = table[table.component_labels == 1]
30+
31+
# Determine the frequency range.
32+
frequencies = table["frequency[kHz]"].values
33+
freq_range = (float(frequencies.min()), float(frequencies.max()))
34+
35+
# Load the segmentation.
36+
seg_path = os.path.join(cochlea, source["imageData"]["ome.zarr"]["relativePath"])
37+
s3_store, _ = get_s3_path(seg_path, bucket_name=BUCKET_NAME, service_endpoint=SERVICE_ENDPOINT)
38+
input_key = f"s{scale}"
39+
with zarr.open(s3_store, mode="r") as f:
40+
seg = f[input_key][:]
41+
42+
mapping = {int(seg_id): freq for seg_id, freq in zip(table.label_id, frequencies)}
43+
lut = np.zeros(max_id + 1, dtype="float32")
44+
for k, v in mapping.items():
45+
lut[k] = v
46+
47+
print("Creating output ...")
48+
output = lut[seg]
49+
if colormap is not None:
50+
norm = colors.Normalize(vmin=freq_range[0], vmax=freq_range[1], clip=True)
51+
cmap = plt.get_cmap(colormap)
52+
mask = output == 0
53+
output = cmap(norm(output))
54+
output[mask] = (0, 0, 0, 0)
55+
56+
# Write the output.
57+
out_folder = os.path.join(output_folder, cochlea, f"scale{scale}")
58+
os.makedirs(out_folder, exist_ok=True)
59+
60+
if colormap is None:
61+
out_path = os.path.join(out_folder, f"frequencies_{source_name}.tif")
62+
else:
63+
out_path = os.path.join(out_folder, f"frequencies_{source_name}_{colormap}.tif")
64+
65+
print("Writing output to", out_path)
66+
tifffile.imwrite(out_path, output, bigtiff=True, compression="zlib")
67+
68+
print("Frequency range:")
69+
print(freq_range[0], "-", freq_range[1], "kHz")
70+
71+
if colormap is not None:
72+
fig, ax = plt.subplots(figsize=(6, 1.3))
73+
fig.subplots_adjust(bottom=0.5)
74+
cb = plt.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, orientation="horizontal")
75+
cb.set_label("Frequency [kHz]")
76+
plt.title(f"Tonotopic Mapping: {source_name}")
77+
plt.tight_layout()
78+
out_path = os.path.join(out_folder, f"frequencies_{source_name}_{colormap}.png")
79+
plt.savefig(out_path)
80+
81+
82+
def main():
83+
parser = argparse.ArgumentParser()
84+
parser.add_argument("--cochlea", "-c", required=True)
85+
parser.add_argument("--scale", "-s", type=int, required=True)
86+
parser.add_argument("--output_folder", "-o", required=True)
87+
parser.add_argument("--source_name", "-n", required=True)
88+
parser.add_argument("--colormap")
89+
args = parser.parse_args()
90+
91+
export_frequency_mapping(args.cochlea, args.scale, args.output_folder, args.source_name, args.colormap)
92+
93+
94+
if __name__ == "__main__":
95+
main()

0 commit comments

Comments
 (0)