11import  argparse 
2+ import  json 
23import  os 
4+ import  pickle 
5+ 
36import  imageio .v3  as  imageio 
47from  glob  import  glob 
58from  pathlib  import  Path 
1013import  pandas  as  pd 
1114from  matplotlib  import  cm , colors 
1215
16+ from  flamingo_tools .s3_utils  import  BUCKET_NAME , create_s3_target 
1317from  util  import  sliding_runlength_sum , frequency_mapping , SYNAPSE_DIR_ROOT , to_alias 
1418
1519INPUT_ROOT  =  "/home/pape/Work/my_projects/flamingo-tools/scripts/M_LR_000227_R/scale3" 
2125    "Type-II" : "Prph" ,
2226}
2327
28+ FILE_EXTENSION  =  "png" 
29+ 
2430png_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
2795def  _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
234322if  __name__  ==  "__main__" :
0 commit comments