tools_sequencer_esynth_galaxies.py 22 KB
Newer Older
1
2
3
4
import numpy as np
import h5py
import glob
import json
5
import sys
6
7
8
9

BATCH_PARALLELISM = 1
import os

myron's avatar
myron committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def synthetise_response(scan_address=None, target_address=None,             response_fit_options = None
):
    input_string = """
    superR_fit_responses :
       foil_scan_address : "{scan_address}"
       nref : 7                 # the number of subdivision per pixel dimension used to 
                                # represent the optical response function at higher resolution
       niter_optical  :  {niter_optical}    # the number of iterations used in the optimisation of the optical
                                # response
       beta_optical  :  {beta_optical}     # The L1 norm factor in the regularisation 
                                #  term for the optical functions
       pixel_dim : 1            # The pixel response function is represented with a 
                                #  pixel_dim**2 array
       niter_pixel : 10        # The number of iterations in the pixel response optimisation
                                # phase. A negative number stands for ISTA, positive for FISTA
       beta_pixel  :  0.0    # L1 factor for the pixel response regularisation

       ## The used trajectories are always written whith the calculated response 
       ## They can be reloaded and used as initialization(and freezed with do_refine_trajectory : 0 )
       ## Uncomment the following line if you want to reload a set of trajectories
       ## without this options trajectories are initialised from the spots drifts
       ##
       #   reload_trajectories_file : "response.h5"

       filter_rois : 0


       ######
       ## The method first find an estimation of the foil scan trajectory on each roi
       ## then, based on this, obtain a fit of the optical response function
       ## assuming a flat pixel response. Finally the pixel response is optimised
       ##
       ## There is a final phase where a global optimisation
       ## is done in niter_global steps.
       ##
       ## Each step is composed of optical response fit, followed by a pixel response fit.
       ## If do_refine_trajectory is different from zero, the trajectory is reoptimised at each step
       ## 
       niter_global  :  {niter_global}

       ## if do_refine_trajectory=1 the start and end point of the trajectory are free
       ##  if =2 then the start and end point are forced to a trajectory which is obtained
       ##  from a reference scan : the foil scan may be short, then one can use the scan of
       ##   an object to get another one : key *trajectory_reference_scan_address*
       ##

       do_refine_trajectory : 1

       ## optional: only if do_refine_trajectory = 2

       trajectory_reference_scansequence_address : "demo_newrois.h5:/ROI_FOIL/images/scans/"
       trajectory_threshold   : 0.1

       ## if the pixel response function is forced to be symmetrical 

       simmetrizza : 1

       ## where the found responses are written

       target_file : {target_address}
       # target_file : "fitted_responses.h5"

    """ 
    s=input_string.format(  scan_address=scan_address ,
                           target_address=target_address,
                           niter_optical = response_fit_options[ "niter_optical"],
                           beta_optical=response_fit_options["beta_optical"],
                           niter_global=response_fit_options["niter_global"]
    )
    process_input( s , exploit_slurm_mpi = 1, stop_omp = True) 


    
def    resynthetise_scan(
        old_scan_address= None,
        response_file  =  None ,
        target_address =  None,
        original_roi_path = None,
        resynth_z_square = None
    ):


    input_string = """
     superR_recreate_rois :
     ### we have calculated the responses in responsefilename
         ### and we want to enlarge the scan  by a margin of 3 times
         ### the original scan on the right and on the left 
         ###  ( so for a total of a 7 expansion factor )

         responsefilename :  {response_file}
         nex : 0

         ## the old scan covered by the old rois
         old_scan_address : {old_scan_address}

         ## where new rois and bnew scan are written
         target_filename : {target_address}
         filter_rois      : 0

         original_roi_path : {original_roi_path}

         resynth_z_square : {resynth_z_square}

"""
    s=input_string.format(  response_file = response_file ,
                            target_address = target_address,
                            old_scan_address=old_scan_address,
                            original_roi_path = original_roi_path +"/rois_definition",
                            resynth_z_square = resynth_z_square)
    
    process_input( s , exploit_slurm_mpi = 0, stop_omp = True) 


123
124


myron's avatar
myron committed
125
126

    
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def process_input(s, go=0, exploit_slurm_mpi = 0, stop_omp = False):
    open("input_tmp_%d.par"%go, "w").write(s)
    background_activator = ""
    if (go % BATCH_PARALLELISM ):
        background_activator = "&"

    prefix=""
    if stop_omp:
        prefix = prefix +"export OMP_NUM_THREADS=1 ;"

        
    if (  exploit_slurm_mpi==0  ):
        comando = (prefix +"mpirun -n 1 XRS_swissknife  input_tmp_%d.par  %s"%(go, background_activator))
    elif (  exploit_slurm_mpi>0  ):
        comando = (prefix + "mpirun XRS_swissknife  input_tmp_%d.par  %s"%(go, background_activator) )
    else:
        comando = (prefix + "mpirun -n %d XRS_swissknife  input_tmp_%d.par  %s"%(abs( exploit_slurm_mpi  ), go, background_activator) )

    res = os.system( comando )

    assert (res==0) , " something went wrong running command : " + comando

def select_rois(  data_path_template=None, filter_path=None, roi_target_path=None, scans_to_use=None   ):
    
    inputstring = """

    create_rois_galaxies :
       expdata     :  {data_path_template}
       filter_path  :  {filter_path}
       roiaddress :       {roi_target_path}      # the target destination for rois
       scans  : {scans_to_use}

    """ .format(data_path_template = data_path_template,
                filter_path = filter_path,
                roi_target_path =  roi_target_path,
                scans_to_use = scans_to_use
    ) 
    process_input( inputstring , exploit_slurm_mpi = 0 )

def extract_sample_givenrois(
        roi_path = None,
        data_path_template = None,
        monitor_path_template = None,
        scan_interval = None,
        Ydim = None,
        Zdim = None,
        Edim = None,
        signals_target_file = None
         ):

    inputstring = """
        loadscan_2Dimages_galaxies :

             roiaddress : {roi_path}

             expdata  :  {data_path_template}

             monitor_address : {monitor_path_template}

             scan_interval    :  {scan_interval}

             Ydim : {Ydim}
             Zdim : {Zdim}
             Edim : {Edim}

             signalfile : {signals_target_file}

    """.format( roi_path = roi_path,
                data_path_template = data_path_template,
                monitor_path_template = monitor_path_template,
                scan_interval = scan_interval,
                Ydim = Ydim,
                Zdim = Zdim,
                Edim = Edim,
                signals_target_file = signals_target_file) 
    

    process_input( inputstring, exploit_slurm_mpi = 0)




def InterpInfo_Esynt_components(peaks_shifts , energy_exp_grid = None,    custom_ene_list =  None, custom_components = None ):

        components = h5py.File( custom_components ,"r")["components"] [()]
        info_dict = {}

        
        for i_interval in range(len(components)):
            info_dict[str(i_interval)]      =   {}            
            info_dict[str(i_interval)]["E"] = custom_ene_list[ i_interval   ]
            info_dict[str(i_interval)]["coefficients"]={}

            for i_n in range(len(energy_exp_grid)):
                info_dict[str(i_interval)]["coefficients"  ][  str(i_n)  ]={}
                for roi_num, de in enumerate(     peaks_shifts   ):
                    info_dict[str(i_interval)]["coefficients"  ][ str(i_n) ][ str(roi_num) ] = 0


        for ic in range(len(components)):
                
            for i_interval in range(len(custom_ene_list)-1):
                cE1 =  custom_ene_list[ i_interval   ]
                cE2 =  custom_ene_list[ i_interval+1 ]
                for i_ene, t_ene  in enumerate( energy_exp_grid)   :

                    for roi_num, de in enumerate(     peaks_shifts   ):
                        if  t_ene+de < cE1 or t_ene+de > cE2:
                            continue
                        alpha = (cE2-(t_ene+de) )/(cE2+cE1)

                        info_dict[str(ic)]["coefficients"  ][  str(i_ene)  ][  str(roi_num)  ]   += alpha * components[ic][ i_interval ]

                        
                        info_dict[str(ic)]["coefficients"  ][  str(i_ene)  ][  str(roi_num)  ]   += (1-alpha)*components[ic][ i_interval+1  ]

        return info_dict    

    
def  InterpInfo_Esynt( peaks_shifts , energy_exp_grid = None,    custom_ene_list =  None):

myron's avatar
myron committed
248
249
    print(energy_exp_grid)
    print(peaks_shifts)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    info_dict = {"energy_exp_grid":list(energy_exp_grid), "de_list": list(peaks_shifts)}

    N_custom = len(custom_ene_list)
    N_data   = len( energy_exp_grid ) 
    
    for i_interval in range(len(custom_ene_list)):
        info_dict[str(i_interval)]      =   {}            
        info_dict[str(i_interval)]["E"] = custom_ene_list[ i_interval   ]
        info_dict[str(i_interval)]["coefficients"]={}

        for i_n in range(len(energy_exp_grid)):

            info_dict[str(i_interval)]["coefficients"  ][  str(i_n)  ]={}
            for roi_num, de in enumerate(     peaks_shifts   ):
                info_dict[str(i_interval)]["coefficients"  ][ str(i_n) ][ str(roi_num) ] = 0


    for i_interval in range( N_custom -1):
        
        cE1 =  custom_ene_list[ i_interval   ]
        cE2 =  custom_ene_list[ i_interval+1 ]
        
        for i_ene, t_ene  in enumerate( energy_exp_grid)   :
            
            for roi_num, de in enumerate(     peaks_shifts   ):
                if  t_ene+de < cE1 or t_ene+de > cE2:
                    continue
                alpha = (cE2-(t_ene+de) )/(cE2-cE1)

                info_dict[str(i_interval)]["coefficients"  ][  str(i_ene)  ][  str(roi_num)  ]   = alpha
                info_dict[str(i_interval+1)]["coefficients"][  str(i_ene)  ][  str(roi_num)  ] = 1-alpha
                
    return info_dict    



    def __init__(self, peaks_shifts, interp_file, source,  custom_ene_list = None):
        
        volum_list = list(interp_file[source].keys())
        scan_num_list = np.array([ int( t.split("_") [1]) for t in volum_list])
        
        ene_list      = np.array([    interp_file[source][vn]["scans"]["Scan%03d"%sn ]["motorDict"]["energy"][()] for vn,sn in zip(volum_list, scan_num_list   )   ])

        print ( " ecco la scannumlist " , scan_num_list)
        print (" ecco ene_list", ene_list)
        
        
        self.volum_list    =  volum_list
        self.scan_num_list =  scan_num_list
        self.ene_list      =  ene_list

        order = np.argsort(  self.ene_list    )
        
        self.ene_list  = self.ene_list [order]

        if custom_ene_list is None:
            self.custom_ene_list      = self.ene_list
        else:
            self.custom_ene_list   = custom_ene_list

        self.scan_num_list  = self.scan_num_list [order]
        self.volum_list  = [ self.volum_list [ii]  for ii in order  ] 
        
        self.interp_file=interp_file
        self.source= source
        self.peaks_shifts=peaks_shifts


# info_dict={}
# for i in range(NC):
#     dizio = {}
#     info_dict[str(i)] = {"coefficients":dizio}
#     c = model.components_[i]
#     np = len(c)
#     for j in range(np):
#         dizio[str(j)] = float(c[j])

# json.dump(info_dict,open( interpolation_infos_file,"w"), indent=4)


        
    def interpola_Esynt(self,  roi_sel=roi_sel ):
        print ( " ECCO I DATI ")
        print (  self.ene_list  ) 
        print (  self.peaks_shifts   )

        info_dict = {}

        for i_intervallo in range(len(self.custom_ene_list)):
            info_dict[str(i_intervallo)]      =   {}            
            info_dict[str(i_intervallo)]["E"] = self.custom_ene_list[ i_intervallo   ]
            info_dict[str(i_intervallo)]["coefficients"]={}
            for t_vn, t_sn, t_ene in list(zip(self.volum_list,  self.scan_num_list, self.ene_list    )):
                info_dict[str(i_intervallo)]["coefficients"  ][  t_vn  ]={}

        for i_intervallo in range(len(self.custom_ene_list)-1):
            cE1 =  self.custom_ene_list[ i_intervallo   ]
            cE2 =  self.custom_ene_list[ i_intervallo+1 ]
            for t_vn, t_sn, t_ene in list(zip(self.volum_list,  self.scan_num_list, self.ene_list    ))[0:]:
                for roi_num, de in enumerate(     self.peaks_shifts   ):
                    if roi_num not in roi_sel:
                        continue
                    if  t_ene+de < cE1 or t_ene+de > cE2:
                        continue
                    alpha = (cE2-(t_ene+de) )/(cE2-cE1)

                    info_dict[str(i_intervallo)]["coefficients"  ][  str(t_vn)  ][  str(roi_num)  ]   = alpha
                    info_dict[str(i_intervallo+1)]["coefficients"][  str(t_vn)  ][  str(roi_num)  ] = 1-alpha

        return info_dict    


myron's avatar
myron committed
362
363
364
365
366
367
368
369
def get_reference(   roi_path =  None,
                     data_path_template = None,
                     monitor_path_template = None ,
                     reference_scan_list = None,
                     extracted_reference_target_file = None,
                     isolate_spot_by = None
):
    signal_path = extracted_reference_target_file + ":/"
370

myron's avatar
myron committed
371
372
373
374
375
376
377
378
379
380
381
382
    input_string = """
    loadscan_2Dimages_galaxies_foilscan :
       roiaddress :  {roi_path} 
       expdata    :  {data_path_template} 
       signalfile :  "{extracted_reference_target_file}"
       isolateSpot :  {isolate_spot_by}
       scan_list : {reference_scan_list}  
    """
    s=input_string.format(
        data_path_template = data_path_template,
        reference_scan_list = reference_scan_list,
        
383

myron's avatar
myron committed
384
385
386
387
388
389
        roi_path = roi_path,
        isolate_spot_by = isolate_spot_by,
        signal_path = signal_path,
        extracted_reference_target_file = extracted_reference_target_file
    )
    process_input( s , exploit_slurm_mpi = 0) 
390
391
392
393
394
395
396
397
398
399
400


def get_scalars( iE = None,
                 signals_file      = None,
                 reference_file    = None,
                 target_file    = None
):

    inputstring = """
    superR_scal_deltaXimages_Esynt :
         sample_address : {signals_file}:/E{iE}
myron's avatar
myron committed
401
         delta_address : {reference_file}:/rois_and_reference/Scan0
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
         load_factors_from : 
         nbin : 1
         target_address : {target_file}:/{iE}/scal_prods
    """ . format( iE = iE,
                  signals_file      = signals_file      ,
                  reference_file    = reference_file    ,
                  target_file    = target_file,
    )
    process_input( inputstring, exploit_slurm_mpi = 0)    


    
def get_volume_Esynt( scalarprods_file = None, interpolation_file = None):
    
    os.system("mkdir DATASFORCC")

    inputstring = """    
     superR_getVolume_Esynt :
        scalprods_address : {scalarprods_file}:/
        dict_interp : {interpolation_file}
        output_prefix : DATASFORCC/test0_
    """.format( scalarprods_file = scalarprods_file ,
                interpolation_file = interpolation_file
    )     
    process_input( inputstring,  exploit_slurm_mpi = 0)

    
def myOrder(tok):
    if("volume" not  in tok):
        tokens = tok.split("_")
        print( tokens)
        return int(tokens[1])*10000+ int(tokens[2])
    else:
        return 0
    
def reshuffle(   volumefile  = "volumes.h5",   nick = None    ):

    h5file_root = h5py.File( volumefile ,"r+" )
    h5file = h5file_root[nick]
    scankeys = list( h5file.keys())
    scankeys.sort(key=myOrder)
    print( scankeys) 
    
    volumes = []
    for k in scankeys:
        if k[:1]!="_":
            continue
        print( k)
        if "volume" in h5file[k]:
            volumes.append( h5file[k]["volume"]  )
    # volume = np.concatenate(volumes,axis=0)
    volume = np.array(volumes)
    if "concatenated_volume" in h5file:
        del h5file["concatenated_volume"]
    h5file["concatenated_volume"]=volume
    h5file_root.close()
    
## THE FOLLOWING PART IS THE RELEVANT ONE

myron's avatar
myron committed
461
462
463
464
465
def tools_sequencer(  peaks_shifts = None,
                      filter_path = None,
                      roi_scan_num = None,
                      roi_target_path          = None,
                      data_path_template = None,
myron's avatar
myron committed
466
467
                      reference_data_path_template = None, 
                      
468
469
                      steps_to_do = None,
                      
myron's avatar
myron committed
470
471
472
473
                      scan_interval = None,
                      Ydim = None,
                      Zdim = None,
                      Edim = None, 
474

myron's avatar
myron committed
475
476
                      monitor_path_template = None,                      
                      signals_target_file      = None,
477
478
479

                      reference_scan_list = None,
                      reference_clip = None,
myron's avatar
myron committed
480
                      extracted_reference_target_file    = None  ,
481

myron's avatar
myron committed
482
                      isolate_spot_by =  None,
483
484
485
                      response_target_file = None,
                      response_fit_options = None,
                      
myron's avatar
myron committed
486
                      resynthetised_reference_and_roi_target_file =   None , 
487
488
489
490
491
                      resynth_z_square = None,
                      selected_rois = None,
                      
                      scalar_products_target_file  = None,

myron's avatar
myron committed
492
                      energy_custom_grid    = None    ,
493
                      custom_components_file = None,
myron's avatar
myron committed
494
                      interpolation_infos_file =  None,
495

myron's avatar
myron committed
496
                      energy_exp_grid  = None
myron's avatar
myron committed
497

498
499
500
501
502
) :


    
    if(steps_to_do["do_step_make_roi"]):   # ROI selection and reference scan
myron's avatar
myron committed
503
        select_rois(  data_path_template = reference_data_path_template, filter_path = filter_path, roi_target_path = roi_target_path, scans_to_use = roi_scan_num   )
504
505
506
    roi_path = roi_target_path


myron's avatar
myron committed
507
    if("do_step_make_reference" in steps_to_do and steps_to_do["do_step_make_reference"]):  
myron's avatar
myron committed
508
509
        get_reference( roi_path = roi_path ,    reference_target_file = resynthetised_reference_and_roi_target_file    )
    reference_file = resynthetised_reference_and_roi_target_file
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527



    if(steps_to_do["do_step_sample_extraction"]): # SAMPLE extraction
        extract_sample_givenrois(
            roi_path              = roi_path               ,
            data_path_template    = data_path_template     ,
            monitor_path_template = monitor_path_template  ,

            scan_interval      = scan_interval      ,
            Ydim               = Ydim               ,
            Zdim               = Zdim               ,
            Edim               = Edim               ,
            signals_target_file = signals_target_file 
        )
    signals_file = signals_target_file    


myron's avatar
myron committed
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
    if(steps_to_do["do_step_extract_reference_scan"]):  # of course we need the REFERENCE SCAN
        get_reference(
                       roi_path = roi_path,
                       data_path_template = reference_data_path_template,
                       monitor_path_template = monitor_path_template  ,
                       extracted_reference_target_file = extracted_reference_target_file,
                       isolate_spot_by = isolate_spot_by,
                       reference_scan_list = reference_scan_list
        )        
        if reference_clip is not None:
            clip1, clip2= reference_clip
            print(extracted_reference_target_file ) 
            ftarget = h5py.File( extracted_reference_target_file  ,"r+")
            target_group = ftarget["Scan0" ]
            for k in target_group.keys():
                if k != "motorDict":
                    for dsn in ["matrix"]:
                        mat = target_group[k][dsn][()]
                        del target_group[k][dsn]
                        target_group[k][dsn] = mat[clip1:clip2]
            ftarget.close()

    if(steps_to_do["do_step_fit_reference_response"]):  
        synthetise_response(
            scan_address=  extracted_reference_target_file +":Scan0" ,
553
            target_address = response_target_file +":/FIT",
myron's avatar
myron committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
            response_fit_options = response_fit_options
        )


        
    if(steps_to_do["do_step_resynthetise_reference"]):  
        resynthetise_scan(
            old_scan_address=  extracted_reference_target_file +":/Scan0" ,
            response_file  = response_target_file +":/FIT",
            target_address =  resynthetised_reference_and_roi_target_file +  ":/rois_and_reference",
            original_roi_path = roi_path,
            resynth_z_square = resynth_z_square
        )
    
568
569


myron's avatar
myron committed
570
    if(steps_to_do["do_step_scalar"]):
myron's avatar
myron committed
571
572
573
574
        os.system("rm %s"%scalar_products_target_file)



575
576
577
        for iE in range(Edim) :
            get_scalars(  iE = iE,
                          signals_file = signals_file,
myron's avatar
myron committed
578
579
                          reference_file = resynthetised_reference_and_roi_target_file,
                          target_file =  scalar_products_target_file
580
581
            )

myron's avatar
myron committed
582
    scalarprods_file = scalar_products_target_file
583
584
585
586


    interpolation_infos_file = "interpolation_infos.json"
    if(steps_to_do["do_step_interpolation_coefficients"]):    # INTERPOLATION  ESYNTH
myron's avatar
myron committed
587
        if custom_components_file is None:        
588
589
590
591
592
593
594
595
            info_dict = InterpInfo_Esynt(  peaks_shifts ,
                                           energy_exp_grid = energy_exp_grid,
                                           custom_ene_list =  energy_custom_grid
            )
        else:
            info_dict = InterpInfo_Esynt_components(  peaks_shifts,
                                                      energy_exp_grid = energy_exp_grid,
                                                      custom_ene_list =  energy_custom_grid,
myron's avatar
myron committed
596
                                                      custom_components = custom_components_file
597
598
599
600
601
602
603
604
605
606
607
            )
        json.dump(info_dict,open( interpolation_infos_file,"w"), indent=4)



    
    # ### ESYNTH
    if(steps_to_do["do_step_finalise_for_fit"]):
        get_volume_Esynt( scalarprods_file = scalarprods_file,
                          interpolation_file = interpolation_infos_file)