batch_extraction_esynth1.py 14.9 KB
Newer Older
1
2
3
4
5
import numpy as np
import h5py
import glob
import json
import os
6
import h5py
7
8
9
10
11
12

BATCH_PARALLELISM = 4


import os
def main():
13
14
15
16
17
    peaks_shifts = h5py.File("peaks_positions_for_analysers.h5","r")["peaks_positions"][()]
    assert( len(peaks_shifts) == 72)
    os.system("xz -dk mask.h5.xz")
    Enominal = np.median(peaks_shifts)
    peaks_shifts-= Enominal
18
19
20
21
22
23

    datadir =  "/data/id20/inhouse/data/run3_20/run3_es949"

    os.system("mkdir results")
    
    roi_target_path    = "results/myrois.h5:/ROIS"
24
25
26
    # roi_target_path    = "rr.h5:/extracted/ROI_AS_SELECTED"
    filter_path = "mask.h5:/FILTER_MASK/filter" 
    roi_scan_num   = [245,246,247] 
27
28
29
30
31
32
    
    first_scan_num = 651 
    Ydim        = 25
    Zdim        = 10
    Edim        = 7
    
33
    monitor_column = "izero/0.000001"
34
35
36
37
38
    
    signals_target_file = "results/signals.h5"
    
    interpolated_signals_target_file = "results/interpolated_signals.h5"

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    extracted_reference_target_file = "results/reference.h5"
    
    reference_scan_list = [245, 246, 247]

    # If reference_clip is not None, then a smaller part of the reference scan is considered
    # This may be usefule to obtain smaller volumes containing the interesting part
    # The used reference scan  will the correspond to the positions from reference_clip[0] to reference_clip[1]-1 included
    ###########
    #    reference_clip = None
    reference_clip = [ 90, 180 ]

    ## in the reference scan for each position there is a spot with a maximum. We set zero the background which is further than
    ## such radius from the maximum
    isolate_spot_by = 6
    
54
55
56
    steps_to_do = {
        "do_step_make_roi":                      False,
        "do_step_sample_extraction":             False,
57
58
59
        "do_step_interpolation":                 False,
        "do_extract_reference_scan":             True,
        
60
61
62
        
        "do_step_make_reference":                False,
        "do_step_scalar_products":               False, 
63
        "do_step_finalise_for_fit":              False
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    }
    

    tools_sequencer(  peaks_shifts          = peaks_shifts          ,
                      datadir               = datadir               ,
                      filter_path           = filter_path           ,
                      roi_scan_num          = roi_scan_num          ,
                      roi_target_path       = roi_target_path       ,
                      
                      steps_to_do = steps_to_do,
                      
                      first_scan_num =  first_scan_num,
                      Ydim        =  Ydim       ,
                      Zdim        =  Zdim       ,
                      Edim        =  Edim       ,

                      monitor_column = monitor_column,
81
82
83
84
85
86
87
                      signals_target_file = signals_target_file,
                      interpolated_signals_target_file = interpolated_signals_target_file,

                      reference_scan_list = reference_scan_list,
                      reference_clip = reference_clip,
                      extracted_reference_target_file = extracted_reference_target_file ,
                      isolate_spot_by =  isolate_spot_by
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
    )
    
    


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  ):
        os.system(prefix +"mpirun -n 1 XRS_swissknife  input_tmp_%d.par  %s"%(go, background_activator))
    elif (  exploit_slurm_mpi>0  ):
        os.system(prefix + "mpirun XRS_swissknife  input_tmp_%d.par  %s"%(go, background_activator) )
    else:
        os.system(prefix + "mpirun -n %d XRS_swissknife  input_tmp_%d.par  %s"%(abs( exploit_slurm_mpi  ), go, background_activator) )
 


def select_rois( datadir = None,  roi_scan_num=None, roi_target_path = None, filter_path = None):
113
114
115
116
117
118

    if np.isscalar(roi_scan_num):
        scans = [roi_scan_num]
    else:
        scans = list(roi_scan_num)
        
119
120
121
    inputstring = """
    create_rois: 
        expdata : {expdata} 
122
        scans : {scans} 
123
124
125
        roiaddress : {roi_target_path}
        filter_path : {filter_path}
    """.format(
126
127
        expdata = os.path.join( datadir, "hydra"),
        scans = scans,
128
129
130
131
132
133
        roi_target_path = roi_target_path,
        filter_path = filter_path
    )
    process_input( inputstring,  exploit_slurm_mpi = 0 )


134
135
136
137
138
139
140
141
def get_reference(   roi_path =  None,
                     datadir = None,
                     reference_scan_num=None,
                     monitor_column = None,
                     extracted_reference_target_file = None,
                     isolate_spot_by = None,
):
    signal_path = extracted_reference_target_file + ":/"
142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    inputstring = """
    loadscan_2Dimages :
       expdata : {expdata} 
       roiaddress :  {roi_path} 
       monitor_column : {monitor_column} 
       scan_interval : [{reference_scan_num},{reference_scan_num_plus1} ] 
       signaladdress : {signal_path}
       isolateSpot : {isolate_spot_by}
       save_also_roi : True
  
       sumto1D  : 0
       energycolumn : 'stx'
    """
    s=inputstring.format(
        exp_data = os.path.join( datadir, "hydra"),
        reference_scan_num = reference_scan_num,
        reference_scan_num_plus1 =  reference_scan_num+1,
        monitor_column = monitor_column,
        roi_path = roi_path,
        isolate_spot_by = isolate_spot_by,
        signal_path = signal_path
    )
    process_input( s , exploit_slurm_mpi = 1) 
166
167
168
169
170
171
172
173

    
def extract_sample_givenrois(
        roi_path = None,
        datadir = None, 
        Start = None,
        End   = None,
        Thickness = None ,
174
175
        monitor_column = None,
        signals_target_file = None,
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
):
    for start in range(Start,End, Thickness):
        
        end = start+Thickness

        signal_path = signals_target_file + ":/_{start}_{end}".format(start=start, end=end)
        
        inputstring = """
        loadscan_2Dimages :
            expdata : {expdata}
            roiaddress : {roi_path} 
            scan_interval : [{start}, {end}] 
            energy_column : sty 
            signaladdress : {signal_path}
            monitor_column : {monitor_column}
            sumto1D  : 0
        """.format(
193
            expdata = os.path.join( datadir, "hydra"),
194
195
196
197
198
199
            roi_path = roi_path,
            start = start,
            end = end,
            monitor_column = monitor_column,
            signal_path = signal_path
        ) 
200
        process_input(inputstring, exploit_slurm_mpi = 1)
201
202
203
204
        


        
205
def interpolate( peaks_shifts, interp_file_str,  interp_file_target_str):
206

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

210
    
211

212
213
214
    volum_list = list(interp_file.keys())
    scan_num_list = np.array([ int( t.split("_") [1]) for t in volum_list])
    ene_list      = np.array([    interp_file[vn]["scans"]["Scan%03d"%sn ]["motorDict"]["energy"].value for vn,sn in zip(volum_list, scan_num_list   )   ])
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
    print ( " ecco la scannumlist " , scan_num_list)
    print (" ecco ene_list", ene_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  ] 

    # raise
    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 .min() , t_ene+de , ene_list .max()  ) 
            if  t_ene+de < ene_list .min() or t_ene+de > ene_list .max():
                continue

            print ( " CONTINUO ", t_ene+de, ene_list .min() ,ene_list .max() )

            i0 = np.searchsorted(   ene_list    , 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)
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

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

        # interp_file_target.flush()

        fscans = interp_file_target[ 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["Scan%03d"% sn]
            keys_list = list(  fScan.keys() )
268
            for k in keys_list:
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
                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["Scan%03d"% sn]
            keys_list = list(  fScan.keys() )
            for k in keys_list:
                if k!="motorDict":
                    assert( int(k)  in rois_coeffs)
                    k = int(k)
                    i0,f0,i1,f1 = rois_coeffs[k]

                    matrix0 = interp_file[volum_list[i0]  ]["scans"]["Scan%03d"%( scan_num_list[i0]+sn-t_sn)  ][str(k)]["matrix"][:]
                    matrix1 = interp_file[volum_list[i1]  ]["scans"]["Scan%03d"%( yyyscan_num_list[i1]+sn-t_sn)  ][str(k)]["matrix"][:]
                    monitor = np.ones( matrix0.shape[0],"f" )
                    newmatrix = f0* matrix0+f1*matrix1

                    if "matrix" in fScan[str(k)] :
                        del fScan[str(k)]["matrix"]
                    if "monitor" in fScan[str(k)] :
                        del fScan[str(k)]["monitor"]
                    if "monitor_divider" in fScan[str(k)] :
                        del fScan[str(k)]["monitor_divider"]

                    fScan[str(k)]["matrix"] = newmatrix
                    fScan[str(k)]["monitor"] = monitor
                    fScan[str(k)]["monitor_divider"] = 1.0
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321

        
            
def tools_sequencer(  peaks_shifts = None,
                      datadir = None,
                      filter_path = None, 
                      roi_scan_num = None,
                      roi_target_path       = None,

                      first_scan_num =  None ,
                      Ydim        =  None ,
                      Zdim        =  None ,
                      Edim        =  None ,
                      
                      monitor_column = None, 
                      signals_target_file = None,
                      interpolated_signals_target_file = None,
                                            
                      steps_to_do = None,

                      #####################################################
                      ## can be left to None, will be set to the used target
                      roi_path              = None,
322
323
324
325
326
327
328
329
                      signals_file = None,
                      interpolated_signals_file = None,

                      reference_clip = None,
                      isolate_spot_by = None,
                      reference_scan_list = None,
                      extracted_reference_target_file = None ,

330
331
332
333
334
335
336
337
338
339
340
341
342
343

) :

    if roi_path is None:
        roi_path = roi_target_path        
    if signals_file  is None:
       signals_file   =  signals_target_file
    if interpolated_signals_file  is None:
       interpolated_signals_file   =  interpolated_signals_target_file
    
    if(steps_to_do["do_step_make_roi"]):   # ROI selection and reference scan
        select_rois(datadir         = datadir ,
                    roi_scan_num    = roi_scan_num ,
                    roi_target_path = roi_target_path,
344
                    filter_path     = filter_path
345
346
347
348
349
350
351
352
        )
                        
    if(steps_to_do["do_step_sample_extraction"]): 
        extract_sample_givenrois(
            roi_path = roi_path,
            datadir = datadir, 
            Start =  first_scan_num ,
            End   = (first_scan_num + Zdim * Edim ) ,
353
            Thickness = Zdim,
354
355
356
357
358
359
            monitor_column = monitor_column,
            signals_target_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) )
360
        interpolate(  peaks_shifts , signals_file ,  interpolated_signals_target_file )
361
362

        
363
364
365
366
367
368
369
370
371
372
373
374
    if(steps_to_do["do_extract_reference_scan"]):  # of course we need the REFERENCE SCAN

        for reference_scan_num in reference_scan_list:
            get_reference( datadir = datadir,
                           monitor_column = monitor_column,
                           extracted_reference_target_file = extracted_reference_target_file,
                           isolate_spot_by = isolate_spot_by,
                           reference_scan_num = reference_scan_num
            )
        
        # for other in other_rois_for_ref:
        #     os.system("cp  roi_%d.h5  roi_%d.h5"%(roi_scann, other) )
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
        # if reference_clip is not None:
            
        #     clip1, clip2= reference_clip
            
        #     ftarget = h5py.File( "roi_%d.h5" % roi_scann ,"r+")
        #     target_group = ftarget["extracted/ROI_AS_SELECTED/calibration_scan/scans/Scan%03d"% roi_scann ]
        #     for k in target_group.keys():
        #         if k != "motorDict":
        #             print(" SHRINKING scan for ROI %s   in file roi_%d.h5 " %( k, roi_scann   ))
        #             for dsn in ["matrix", "monitor", "xscale"]:
        #                 mat = target_group[k][dsn][()]
        #                 del target_group[k][dsn]
        #                 target_group[k][dsn] = mat[clip1:clip2]
        #     ftarget.close()

        # for other in other_rois_for_ref:
        #     get_reference(roi_scan_num=other)

        #     ftarget = h5py.File( "roi_%d.h5" % roi_scann ,"r+")
        #     fsource = h5py.File( "roi_%d.h5" % other     , "r")

        #     source_group = fsource["extracted/ROI_AS_SELECTED/calibration_scan/scans/Scan%03d"% other ]
        #     target_group = ftarget["extracted/ROI_AS_SELECTED/calibration_scan/scans/Scan%03d"% roi_scann ]
        #     for k in target_group.keys():
        #         if k != "motorDict":
        #             print(" ADDING data for ROI %s   from file roi_%d.h5 " %( k, other   ))
        #             mat = source_group[k]["matrix"][()]
        #             if clip1 is not None:
        #                 mat = mat[clip1:clip2]
        #             target_group[k]["matrix"][:] +=  mat

        # print( " SUCCESS ") 



main()