tools_sequencer_interp_galaxies.py 23.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
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
123
124
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
248
249
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
import numpy as np
import h5py
import glob
import json
import sys
import math

BATCH_PARALLELISM = 1

import os

    
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) 





    
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 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 + ":/"

    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,
        

        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) 


    
def get_scalars(  iE = None ,  
                  reference_address = None,
                  signals_file =  None, 
                  target_file = None,
                  
                  use_optional_solution=False,
                  save_factors = False,
                  load_factors_from = None,
                  selected_rois = None,
                  scal_prod_use_optional_solution= False,
                  scal_prod_load_factors         = False,
                  scal_prod_load_factors_from    = None,
):
    
    input_string = """
    superR_scal_deltaXimages :
       sample_address : {signals_file}:/E{iE}
       delta_address : {reference_address}


       # roi_keys       :  [60, 64, 35, 69, 34, 24, 5, 6, 71, 70, 39, 58, 56, 33]
       roi_keys       :  {selected_rois}

       nbin : 1
       target_address : {target_file}:/E{iE}/scal_prods
    """
    if scal_prod_use_optional_solution:
        input_string = input_string+"""
       optional_solution : {target_file}:/E{iE}/volume
        """

    if True:
        input_string = input_string+"""
       save_factors_on : factors_{iE}.json
        """
    if scal_prod_load_factors :
        input_string = input_string+"""
       load_factors_from : %s
        """ % scal_prod_load_factors_from


    input_string = input_string .format( iE=iE,
                                      signals_file = signals_file ,
                                      reference_address = reference_address, 
                                      target_file  = target_file,
                                      selected_rois = list(selected_rois)
    )
        
    process_input( input_string, exploit_slurm_mpi = 0)    

def get_volume(  iE = None,
                 volumes_file= None,
                 niter =  None,
                 beta  = None,
                 

):
    inputstring = """    
     superR_getVolume :
        scalprods_address : {volumes_file}:/E{iE}/scal_prods
        target_address :  {volumes_file}:/E{iE}/volume
        niter : {niter}
        beta : {beta}
        eps : 2e-07
        debin : [1, 1]
    """
    s=inputstring.format( iE = iE,   
                         volumes_file = volumes_file, niter = niter, beta = beta )
    process_input(s, exploit_slurm_mpi = 0  )


    
def collect_factors(pattern="factors_*.json", newfile="newfactors.json"):

    files = glob.glob(pattern)

    indexes = [ int(    (s.split("_")[1]).replace(".json","" )    ) for s in files ]
    order = np.argsort(indexes)
    files = [files[i] for i in order]

    files  = files[1:-1]
    result  = {}
    result2 = {}
    Nkeys = None
    for f in files:
        factors = json.load(open(f,"r"))
        if Nkeys is None:
            Nkeys = len(list(factors.keys()))
        assert(Nkeys == len(list(factors.keys())) )
        for k,val in factors.items():
            if k not in result:
                result[k] = 0.0
                result2[k] = 0.0
            result[k] += factors[k]/ len(files)
            result2[k] += (factors[k]*factors[k])/ len(files)
    json.dump(result,open(newfile,"w") )     
    keys = list(result.keys() )
    keys.sort(key=int)
    for k  in keys:
        print( k , " ",   result[k] , " " , math.sqrt( result2[k] - result[k]*result[k]    ) / result[k]  )



    
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()


def interpolate( peaks_shifts, interp_file_str,  interp_file_target_str, energy_exp_grid):

    interp_file = h5py.File(  interp_file_str ,"r+")
    interp_file_target = h5py.File( interp_file_target_str   ,"r+")

    volum_list = list(interp_file.keys())

    scan_num_list = np.array([    int(''.join(filter(str.isdigit, str(t) )))   for t in volum_list])
    ene_list      = np.array([    energy_exp_grid[t] for t in scan_num_list  ] )


    order = np.argsort(  ene_list    )

    ene_list  = ene_list [order]
    
    scan_num_list  = scan_num_list [order]
    volum_list  = [ volum_list [ii]  for ii in order  ] 
    print(ene_list)
    
    # raise

    ene_list_for_search = np.array(ene_list ,"d")
    ene_list_for_search[0]  -=1.0e-6
    ene_list_for_search[-1] +=1.0e-6
    
    for t_vn, t_sn, t_ene in list(zip(volum_list,  scan_num_list, ene_list    ))[0:]:
        rois_coeffs={}
        for roi_num, de in enumerate(     peaks_shifts   ):
            print ( roi_num, "===== " , t_ene+de , ene_list_for_search .min() , t_ene+de , ene_list_for_search .max()  ) 
            if  t_ene+de < ene_list_for_search .min() or t_ene+de > ene_list_for_search .max():
                continue
            
            i0 = np.searchsorted(   ene_list_for_search    , t_ene+de )-1
            assert(i0>=0)
            i1=i0+1
            print (i0, i1, len(ene_list))
            print (ene_list) 
            assert(i1<len( ene_list ))

            DE = (  ene_list[i1] -  ene_list[i0]   )
            df = (  t_ene+de  -  ene_list[i0]   )/ DE

            rois_coeffs[ roi_num  ] =  [   i0,(1-df)   , i1,df         ]
        print ( " for reinterpolation of ", t_vn ," interpolation scheme is the following ",  rois_coeffs)



        fscans = interp_file_target[ t_vn   ]  #  ["scans"]
        keys_list = list(  fscans.keys() )
        print ( " keylist ", keys_list)

        print ( " roislist   keylist", list(rois_coeffs.keys())  )
        for k in keys_list:
            if k[:3]=="ROI":
                if int(k[3:]) not in rois_coeffs:
                    print (" rimuovo ", k)
                    del fscans[k]
        for sn in range(t_sn, t_sn+1):
            fScan = fscans["Scan0"]
            keys_list = list(  fScan.keys() )
            for k in keys_list:
                if k!="motorDict":
                    if int(k) not in rois_coeffs:
                        print (" rimuovo da scans", k)
                        del fScan[k]


        for sn in range(t_sn, t_sn+1):
            fScan = fscans["Scan0"]
            keys_list = list(  fScan.keys() )

            print( keys_list )

            for k_str in keys_list:
                if k_str!="motorDict":
                    assert( int(k_str)  in rois_coeffs)
                    k = int(k_str)
                    i0,f0,i1,f1 = rois_coeffs[k]


                    print( volum_list[i0])
                    print(  interp_file_str )
                    print( interp_file[volum_list[i0] ] ["Scan0"] .keys() )
                    print( interp_file[volum_list[i0]  ]["Scan0"  ][k_str]    ) 
                    
                    matrix0 = interp_file[volum_list[i0]  ]["Scan0"  ][k_str]["matrix"][:]
                    matrix1 = interp_file[volum_list[i1]  ]["Scan0"  ][k_str]["matrix"][:]
                    monitor = np.ones( matrix0.shape[0],"f" )
                    newmatrix = f0* matrix0+f1*matrix1

                    if "matrix" in fScan[k_str] :
                        del fScan[k_str]["matrix"]
                    if "monitor" in fScan[k_str] :
                        del fScan[k_str]["monitor"]
                    if "monitor_divider" in fScan[k_str] :
                        del fScan[k_str]["monitor_divider"]

                    fScan[k_str]["matrix"] = newmatrix
                    fScan[k_str]["monitor"] = monitor
                    fScan[k_str]["monitor_divider"] = 1.0

        



    
## THE FOLLOWING PART IS THE RELEVANT ONE
def tools_sequencer(  peaks_shifts          = None  ,
                      data_path_template    = None  ,
                      filter_path           = None  ,
                      roi_scan_num          = None  ,
                      roi_target_path       = None  ,
                      
                      first_scan         = None  ,                      
                      Ydim                  = None  ,
                      Zdim                  = None  ,
                      Edim                  = None  ,
                    
                      monitor_path_template = None ,
                      signals_target_file = None,
                      interpolated_signals_target_file = None,
                      
                      steps_to_do = None,
                      
                      reference_clip = None,
                      isolate_spot_by = None,
                      reference_scan_list = None,
                      reference_data_path_template = None,
                      extracted_reference_target_file    = None,
                      response_target_file = None,
                      response_fit_options = None,
                      resynthetised_reference_and_roi_target_file = None,
                      resynth_z_square = None,
                      
                      selected_rois = None,
                      scal_prod_use_optional_solution = None,
                      scalar_products_and_volume_target_file      = None,
                      
                      volume_retrieval_beta  = None,
                      volume_retrieval_niter = None,
                      energy_exp_grid = None
):
    
    

    
    if(steps_to_do["do_step_make_roi"]):   # ROI selection and reference scan
        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   )
    roi_path = roi_target_path


    if("do_step_make_reference" in steps_to_do and steps_to_do["do_step_make_reference"]):  
        get_reference( roi_path = roi_path ,    reference_target_file = resynthetised_reference_and_roi_target_file    )
    reference_file = resynthetised_reference_and_roi_target_file



    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      = [first_scan, first_scan+ Ydim*Zdim   ]      ,
            Ydim               = Ydim               ,
            Zdim               = Zdim               ,
            Edim               = Edim               ,
            signals_target_file = signals_target_file 
        )
    signals_file = signals_target_file    



    if(steps_to_do["do_step_interpolation"]):    
        os.system("cp {signals_file} {interpolated_signals_target_file}".format(signals_file=signals_file, interpolated_signals_target_file =interpolated_signals_target_file) )
        interpolate(  peaks_shifts , signals_file ,  interpolated_signals_target_file, energy_exp_grid )

    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" ,
            target_address = response_target_file  +":/FIT",
            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
        )
    


    if(steps_to_do["do_step_scalar"]):
        for iE in range( Edim):            
            get_scalars( iE = iE  , 
                         reference_address = resynthetised_reference_and_roi_target_file +  ":/rois_and_reference/Scan0" ,
                         signals_file  =   interpolated_signals_target_file ,
                         target_file   = scalar_products_and_volume_target_file,
                         selected_rois = selected_rois                , 
                         scal_prod_use_optional_solution= scal_prod_use_optional_solution,
                         scal_prod_load_factors         = False,
                         scal_prod_load_factors_from    = None
            )

            
        if(scal_prod_use_optional_solution):
            collect_factors(pattern="factors_*.json", newfile="newfactors.json")
        
            for iE in range( Edim ):            
                get_scalars( iE = iE, 
                             reference_address = resynthetised_reference_and_roi_target_file +  ":/rois_and_reference/Scan0" ,
                             signals_file  =  interpolated_signals_target_file  ,
                             target_file   = scalar_products_and_volume_target_file,
                             selected_rois = selected_rois                , 
                             scal_prod_use_optional_solution= False,
                             scal_prod_load_factors         = False,
                             scal_prod_load_factors_from    = "newfactors.json"
                )


    scalarprods_file = scalar_products_and_volume_target_file

    if(steps_to_do["do_step_volume_retrieval"]):          
        for iE in range( Edim ):            
            get_volume(  iE,
                         volumes_file = scalar_products_and_volume_target_file,
                         beta  = volume_retrieval_beta ,
                         niter = volume_retrieval_niter,
            )