-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPy16progs.py
7976 lines (6726 loc) · 289 KB
/
Py16progs.py
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Module: I16 Data analysis programs "Py16Progs.py"
By Dan Porter, PhD
Diamond
2016
Usage:
******In Script********
include the following lines at the top of your script
import sys
sys.path.insert(0,'/dls_sw/i16/software/python/Py16') # location of Py16Progs
import Py16Progs as p16
p16.filedir = '/dls/i16/data/2015/mt0000-1' # your experiment folder
p16.savedir = '/dls/i16/data/2015/mt0000-1/processing' # where to save output
# Use functions:
p16.checkexp()
num = p16.latest()
d= p16.readscan(num)
p16.plotscan(num)
p16.plotpil(num)
******In Console*******
Run the file in the current console:
>> cd /dls_sw/i16/software/python/Py16/
>> ipython -i --matplotlib tk
In the python console:
>> import Py16progs as p16
Change filedir:
>> p16.filedir = '/dls/i16/data/2015/cm12169-2/CsFeSe' # your experiment folder
# Use functions:
>> d= p16.readscan(12345) # generate data structure for scan number 12345
>> d.eta # returns scan data for eta psudo-device
>> d.metadata.Energy # returns metadata for scan (at start of scan)
>> p16.checkexp() # experiment dates + scans numbers
>> num = p16.latest() # Latest scan number
**********************
Some Useful Functions:
d = readscan(num)
x,y,dy,varx,vary,ttl,d = getdata(num/d,'varx','vary',save=None)
x,y,z,varx,vary,varz,ttl = joindata([nums],'varx','vary','varz')
vol = getvol(num)
ROI_sum,ROI_maxval,ROI_bkg = pilroi(num,ROIcen,ROIsize,findpeak,peakregion)
A = getmeta([nums],'Field')
num = latest()
checkexp()
checkscan(num1=None,num2=None)
checklog(time=None,mins=2,cmd=False)
prend(start,end)
polflip(sigsig,sigpi,fit='Gauss',output=False)
metaprint(d1,d2=None)
savedata(num/d,'varx','vary')
plotscan(num=None,vary='',fit=None,save=None)
plotpil(num,cax=None,imnum=None)
plotscans3D(scans,depvar='Ta',vary='',save=None)
fit,err = fit_scans(scans,depvar='Ta',vary='',save=None)
out,err = peakfit(x,y,dy,type='dVoight')
HHH,KKK,LLL = pixel2hkl(num)
XXX,YYY,ZZZ = pixel2xyz(num)
TTH,INT = pixel2tth(num)
ROIcen_ij,ROIcen_frame = pilpeak(Y,test = 1,disp=False)
ispeak(Y,test = 1,disp=False)
peak = peakfind(Y,cutoff=0.01)*
labels(title,xlabel,ylabel,zlabel)
vals = frange(start,stop=None,step=1)
str = stfm(val,err)
Version 4.9.1
Last updated: 31/10/24
Version History:
07/02/16 0.9 Program created from DansI16progs.py V3.0
18/02/16 1.0 Functions renamed, readscan updated for errors, simplifications to outputs
03/03/16 1.1 Tested on Beamline, removed errors, cleaned up
08/03/16 1.2 Refinements after a week of beamline use
15/04/16 1.3 New masks method in peak_fit
05/05/16 1.4 Fixed bug that did integer normalisation of APD/counttime
10/05/16 1.5 Added print buffer function
19/05/16 1.6 Fixed 3D plotting bugs, new outputs on fit_scans, catch psi='unavailable' bug (psi=0)
12/07/16 1.7 Ungraded peakfit with variable backgrouns, estimate input and new default values.
10/08/16 1.8 Added logplot and diffplot options to plotscan
08/09/16 1.9 Generalised getvol for any detector by pre-loading the first image
21/09/16 2.0 Removed dnp.io.load. New title includes folder and new functions for lists of scan numbers
07/10/16 2.1 Ordered keys in dataloader, some minor fixes
17/10/16 2.2 Improved ROI functionality - _sfm to remove first frame
14/12/16 2.3 Improved multiscan titles, funtions to write + load previous experiment directories for fast access
20/12/16 2.4 Added checkscans and auto_varx/vary functions, added dont_normalise for none-normalisable values
02/02/17 2.5 Added checkhkl and checkwl. Bugs fixed when using DifCalc (psi+azih not recorded)
22/02/17 2.6 Added dead pixel mask for pilatus for experiments in Feb 2017
13/06/17 2.7 Added getmeta() function
24/07/17 2.8 Added d.metadata.hkl_str, fixing incorrect position bug. Various other fixes.
01/08/17 2.9 Added check for large pilatus arrays.
02/10/17 2.9 Added various misc functions, other bugs fixed
06/10/17 3.0 Added pixel2hkl functions, incluing plots, other bug fixes
17/10/17 3.1 Added choice of temperature sensor, d.metadata.temperature
23/10/17 3.2 Added new plotting features, better multi-dimensional fits
17/11/17 3.3 Added normalisation to pixel2tth, added default bpm behaviour
06/12/17 3.4 Added new plots for pixel2tth
23/01/18 3.5 Added d.counter to scans, made pixel2hkl work for hkl scans
23/02/18 3.6 Added bin_pixel_hkl_cut, new fit methods
09/03/18 3.6 Added, scanpol, updated to correct for python3.6 test errors
18/03/18 3.7 Added exp_parameters_save and _load
01/05/18 3.8 Added sort to joinscans, updated for new PA + pilatus3, added scanimage
21/05/18 3.8 Changed automatic titles to include psi angle and reference
01/08/18 3.9 Removed psutil, added getRAM, various updates and fixes, added plotmeta and pilmaxval, corrected joinscan save
19/10/18 3.9 Corrected type input of getvol.
26/11/18 4.0 Output of checkscan, checklog now str
14/12/18 4.1 Update to simpfit, giving better estimates of peak position, changed default tmpdir
21/02/19 4.2 Update to pcolorplot, removed some bugs
18/03/19 4.2 Update to plotscans, correcting normalisation for multi-vary
15/04/19 4.3 Update to readscan, additional checks on metadata added
15/05/19 4.4 Updated labels function, added newplot, multiplot, sliderplot, sliderplot2D
02/10/19 4.5 Added plotqbpm, added defaults for phase plate scans
23/10/19 4.6 Fixed exec compatibility, now python3 compatible, readnexus added using nexusformat or h5py
29/11/19 4.7 Changed fit_scans save name to include vary, added nexus_rsremap and nexus_plot_rsremap
21/02/20 4.7 Added findscans
29/02/20 4.7 Added output to plotqbpm
27/05/20 4.7 Added licence
01/07/20 4.7.5 Updated plotqbpm to correct error
11/02/21 4.8 Added colormap options
23/04/21 4.8 Added detector to findscans
24/05/21 4.8.1 Added file input to readscan
29/09/21 4.8.2 Added fig_dpi parameter
01/10/21 4.8.3 Corrected error from os.path.isfile(d)
21/01/22 4.8.4 Corrected error on dat files with "=" in ubMeta
26/04/22 4.8.5 Corrected error in CheckScan for python3
03/05/22 4.8.6 Corrected error for merlinroi1 in getdata
30/07/22 4.8.7 Corrected error in polflip plotting, remove plt.show from plotscan
13/09/22 4.8.8 Corrected detector slits label in several functions, added phaseplate_normalisation, added fig_size parameter
19/06/23 4.8.9 Changed [...] to [()] in nexus reader
03/07/23 4.9.0 Changed latest() to work with scans >1000000
31/10/24 4.9.1 Switch to using np.genfromtxt for reading columns to handle string input
###FEEDBACK### Please submit your bug reports, feature requests or queries to: dan.porter@diamond.ac.uk
@author: Dan Porter
I16, Diamond Light Source
2016
-----------------------------------------------------------------------------
Copyright 2023 Diamond Light Source Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dr Daniel G Porter, dan.porter@diamond.ac.uk
www.diamond.ac.uk
Diamond Light Source, Chilton, Didcot, Oxon, OX11 0DE, U.K.
"""
#Ideas for the future:
# - Pilatus peak finding (2D fitting?) as separate function to dpilroi
# - dataloader contain functions (more pythony...)
# - Refactor fitting routines in new Py16fit module
# - Create dead_pixel files for detectors, load based on which detector used
# - Better naming convention of fit files, including HKL
# - save parameters per experiment
from __future__ import print_function
import sys,os
import glob # find files
import re # regular expressions
import datetime # Dates and times
import time # For timing
import tempfile # Find system temp directory
import numpy as np
import h5py # read hdf5 files such as nexus (.nxs)
#import scisoftpy as dnp # Make sure this is in your python path
import matplotlib.pyplot as plt # Plotting
import matplotlib.ticker as mtick # formatting of tick labels
from matplotlib.colors import LogNorm # logarithmic colormaps
from mpl_toolkits.mplot3d import Axes3D # 3D plotting
from scipy.optimize import curve_fit # Peak fitting
#from scipy import misc # read pilatus images
from imageio import imread # read Tiff images
from scipy.signal import convolve
from itertools import product
from collections import OrderedDict
# read hdf5 files such as nexus (.nxs)
try:
from nexusformat.nexus import nxload
except ImportError:
print('nexusformat not available, nexus files will be read using h5py')
from h5py import File as nxload
###########################################################################
#############################PARAMETERS####################################
###########################################################################
"-----------------------Default Experiment Directory----------------------"
# Variable filedir is called from the namespace and can be changed at any
# time,even once the module has been imported, if you change it in the current namespace
filedir = '/dls/i16/data/2023'
savedir = '/home/i16user/Desktop'
#tmpdir = tempfile.gettempdir() # I16 user accounts don't have access
tmpdir = os.path.expanduser('~')
"-----------------------------Data file format----------------------------"
datfile_format = '%i.dat'
nxsfile_format = '%i.nxs'
"-----------------------Error Estimation Parameters-----------------------"
error_func = lambda x: np.sqrt(np.abs(x)+0.1) # Define how the error on each intensity is estimated
#error_func = rolling_fun
# error_func = lambda x: 0*x + 1 # Switch errors off
"-------------------------Normalisation Parameters------------------------"
exp_ring_current = 300.0 # Standard ring current for current experiment for normalisation
exp_monitor = 800.0 # Standard ic1monitor value for current experiment for normalisation
normby = 'rc' # Incident beam normalisation option: 'rc','ic1' or 'none'
dont_normalise = ['Ta','Tb','Tc','Td','ic1monitor','rc','Cmes','Vmes','Rmes', 'fwhm']
detectors = ['APD','sum','maxval'] # error bars are only calculated for counting detectors
default_sensor = 'Ta' # d.metadata.temperature will read this sensor as the standard
"----------------------------Pilatus Parameters---------------------------"
pil_centre = [106,238] # Centre of pilatus images [y,x], find the current value in /dls_sw/i16/software/gda/config/scripts/localStation.py (search for "ci=")
hot_pixel = 2**20-100 # Pixels on the pilatus greater than this are set to the intensity chosen by dead_pixel_func
peakregion=[7,153,186,332] # Search for peaks within this area of the detector [min_y,min_x,max_y,max_x]
pilpara=[119.536,1904.17,44.4698,0.106948,-0.738038,412.19,-0.175,-0.175] # pilatus position parameters for pixel2hkl
dead_pixel_func = np.median # Define how to choose the replaced intensity for hot/broken pixels
pil_max_size = 1e8 # Maximum volume size that will be loaded. 1e8~1679*1475*41 -> 41 points of pil2M, ~ 800MB
# pilatus_dead_pixels = np.array([[101, 244],
# [102, 242],
# [102, 243],
# [102, 244],
# [103, 242],
# [103, 243],
# [103, 244],
# [104, 241],
# [104, 242],
# [104, 243],
# [104, 244],
# [105, 240],
# [105, 242],
# [105, 243],
# [105, 244],
# [106, 240],
# [107, 242],
# [107, 243]]) # Dead pixels at centre of pilatus ***Feb 2017***
pilatus_dead_pixels = np.zeros(shape=(0,2),dtype=int) # Blank
"----------------------------Plotting Parameters--------------------------"
plot_colors = ['b','g','m','c','y','k','r'] # change the default colours of plotscan
exp_title = '' # Experiment title
default_colormap = 'viridis' # maplotlib colormap
fig_dpi = 80
fig_size = [10,8]
#plt.xkcd() # cool plots!
"-------------------------------Data Defaults-----------------------------"
# These parameters will always be defined in the metadata
# Structure meta_defaults['name']=[['list of possible names'],default value if not available]
meta_defaults = {}
meta_defaults['Energy'] = [['Energy','Energy2','en','pgm_energy'],0]
meta_defaults['stokes'] = [['stokes','stoke'],0]
meta_defaults['azih'] = [['azih'],0]
meta_defaults['azik'] = [['azik'],0]
meta_defaults['azil'] = [['azil'],0]
meta_defaults['psi'] = [['psi'],666]
meta_defaults['Ta'] = [['Ta'],300.0]
meta_defaults['h'] = [['h'],0]
meta_defaults['k'] = [['k'],0]
meta_defaults['l'] = [['l'],0]
# If these
scan_defaults = {}
scan_defaults['t'] = [['t', 'count_time']]
scan_defaults['energy'] = [['energy','energy2']]
scan_defaults['rc'] = [['rc','energy2']]
scan_defaults['TimeSec'] = [['TimeSec','TimeFromEpoch']]
###########################################################################
##############################FUNCTIONS####################################
###########################################################################
"----------------------------Loading Functions----------------------------"
def read_dat_file(filename):
"""
Reads #####.dat files from instrument, returns class instance containing all data
Input:
filename = string filename of data file
Output:
d = class instance with parameters associated to scanned values in the data file, plus:
d.metadata - class containing all metadata from datafile
d.keys() - returns all parameter names
d.values() - returns all parameter values
d.items() - returns parameter (name,value) tuples
"""
f = open(filename,'r', errors='ignore')
lines = f.readlines()
f.close()
# Read metadata
meta = OrderedDict()
lineno = 0
for ln in lines:
lineno += 1
if '&END' in ln: break
ln = ln.strip(' ,\n')
neq = ln.count('=')
if neq == 1:
'e.g. cmd = "scan x 1 10 1"'
inlines = [ln]
elif neq > 1 and '{' not in ln:
'e.g. SRSRUN=571664,SRSDAT=201624,SRSTIM=183757'
' but not ubMeta={"name": "crystal=big", ...}'
inlines = ln.split(',')
else:
'e.g. <MetaDataAtStart>'
continue
for inln in inlines:
vals = inln.split('=')
if len(vals) != 2: continue
try:
meta[vals[0]] = eval( vals[1] )
except:
meta[vals[0]] = vals[1]
# Read Main data
# previous loop ended at &END, now starting on list of names
names = lines[lineno].split()
# Load 2D arrays of scanned values
# vals = np.loadtxt(lines[lineno+1:],ndmin=2)
try:
vals = np.genfromtxt(lines[lineno+1:], ndmin=2) # changed 31/10/24 to handle 'true'/'false' in file (returns nan)
except TypeError: # numpy < 1.2
vals = np.genfromtxt(lines[lineno+1:])
if np.ndim(vals) < 2: # single point scans
vals = np.reshape(vals, (1, -1))
# Assign arrays to a dictionary
main = OrderedDict()
for name,value in zip(names,vals.T):
main[name] = value
# Convert to class instance
d = dict2obj(main, order=names)
d.metadata = dict2obj(meta)
return d
def readscan(num):
"""
Loads Diamond #.dat data file
d=readscan(#)
d=readscan(0) - gives current run data
d=readscan(-n) - gives previous run data
d is a dataholder storing all scan data. For example:
d.eta = array of eta values in an eta scan
d.APD = array of intensities when using the APD
d.roi2_sum = array of pilatus region sums when using this option
d.metadata gives ancillary data. For example:
d.metadata.cmd = scan command
d.metadata.Ta = current temperature
d.metadata.en = current energy
use d.keys() or d.metadata.keys() to see all values
"""
if type(num) is dict2obj:
return num
elif type(num) is str and os.path.isfile(num):
file = num
else:
if os.path.isdir(filedir) == False:
print( "I can't find the directory: {}".format(filedir) )
return None
if num < 1:
if latest() is None: return None
num = latest()+num
file = os.path.join(filedir, datfile_format %num)
#print(file)
try:
d = read_dat_file(file)
#d = dnp.io.load(file,warn=False) # from SciSoftPi
except:
print( "Scan {} doesn't exist or can't be read".format(num) )
return None
" Shorten the scan command if it is very long to help with titles etc."
try:
cmd = d.metadata.cmd
except:
print( "Scan {} doesn't contain any metadata".format(num) )
return None
if len(cmd) > 80:
" Shorten long commands"
" This little functions finds long strings and rounds them to three dp"
def caller(match):
return '{:1.4g}'.format(round(float(match.group(0)),2))
d.metadata.cmd_short=re.sub('[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?',caller,cmd) # find numbers in command and round them to 3dp
else:
d.metadata.cmd_short = cmd
" Correct re-assigned values"
keys = list(d.keys())
metakeys = list(d.metadata.keys())
" For some reason, parameter names change occsaionaly, add correction here"
# Correct d.scannables
if 'count_time' in keys: d.t = d.count_time
if 'energy2' in keys: d.energy = d.energy2
if 'rc' not in keys: d.rc = exp_ring_current*np.ones(len(d[keys[0]]))
if 'TimeSec' not in keys: d.TimeSec = np.arange(0,len(d[keys[0]]))
# Correct d.metadata
if 'en' in metakeys: d.metadata.Energy = d.metadata.en; metakeys+=['Energy']
if 'pgm_energy' in metakeys: d.metadata.Energy = d.metadata.pgm_energy; metakeys+=['Energy']
if 'stokes' in metakeys: d.metadata.stoke = d.metadata.stokes
# Missing metaddata
if 'SRSRUN' not in metakeys: d.metadata.SRSRUN = num
if 'a' not in metakeys: d.metadata.a = 1.
if 'b' not in metakeys: d.metadata.b = 1.
if 'c' not in metakeys: d.metadata.c = 1.
if 'alpha1' not in metakeys: d.metadata.alpha1 = 90.0
if 'alpha2' not in metakeys: d.metadata.alpha2 = 90.0
if 'alpha3' not in metakeys: d.metadata.alpha3 = 90.0
if 'thp' not in metakeys: d.metadata.thp = 0.0
if 'delta_axis_offset' not in metakeys: d.metadata.delta_axis_offset = 0.0
if 'Energy' not in metakeys: d.metadata.Energy = np.NaN
if 's5xgap' not in metakeys: d.metadata.s5xgap=-1;d.metadata.s5ygap=-1
if 's6xgap' not in metakeys: d.metadata.s6xgap=-1;d.metadata.s6ygap=-1
if 'm4pitch' not in metakeys: d.metadata.m4pitch=0.0
if 'Atten' not in metakeys: d.metadata.Atten=-1;d.metadata.Transmission=1.0
if 'gam' not in metakeys: d.metadata.gam=0
if 'azih' not in metakeys: d.metadata.azih=0;d.metadata.azik=0;d.metadata.azil=0
if 'psi' not in metakeys: d.metadata.psi = 666
if 'h' not in metakeys: d.metadata.h = 0.0
if 'k' not in metakeys: d.metadata.k = 0.0
if 'l' not in metakeys: d.metadata.l = 0.0
if 'Ta' not in metakeys: d.metadata.Ta = 300.0
" Add filename"
d.metadata.filename = file
" Add a scan position counter"
d.counter = np.arange(0,len(d.TimeSec))
" Add the scan time value"
d.ScanTime = d.TimeSec - d.TimeSec[0]
" Add a hkl string"
d.metadata.hkl_str = scanhkl(d)
" Add a temperature string"
d.metadata.temperature = scantemp(d,default_sensor)
" Add energy string"
d.metadata.energy_str = scanenergy(d)
" Add minimirror string"
d.metadata.minimirrors = scanminimirrors(d)
" Correct psi values"
if type(d.metadata.psi) is str: d.metadata.psi = 666
if d.metadata.psi < -1000: d.metadata.psi = 0.0
if type(d.metadata.azih) is str: d.metadata.azih=0;d.metadata.azik=0;d.metadata.azil=0
# Add additional parameters
try:
" Add azimuth string"
d.metadata.azimuth = scanazimuth(d)
" Add title string"
d.metadata.title = scantitle(d)
except:
print('The scantitle or azimuth couldn''t be generated')
pass
" Array items"
d.scannables = [x for x in keys if type(d[x]) == np.ndarray ] # only keys linked to arrays
" Update keys"
d.update(d.__dict__)
d.metadata.update(d.metadata.__dict__)
return d
def getdata(num=None, varx='', vary='', norm=True, abscor=None):
"""
Get useful values from scans
x,y,dy,varx,vary,ttl,d = getdata(#/d,'varx','vary')
vary can also call re-intergrate pilatus regions of interest:
vary = 'nroipeak' - search for peak and create roi around it
vary = 'nroipeakbkg' - subtract average background defined outside roi
vary = 'nroi[110,242,75,67]' - creates roi [ceni,cenj,widi,widj]
vary = 'nroi[31,31]' - creates centred roi with size [widi,widj]
vary = 'nroi' - creates roi2 like roi
vary = 'nroibkg' - as above but with background subtraction
"""
"---Handle inputs---"
if num is None:
num = latest()
" Multiple nums given"
if type(num)==list:
nums = num[1:]
num = num[0]
else:
nums = []
"---Load data---"
try:
d = readscan(num)
except TypeError:
d = num
if d is None:
return [],[],[],'','','',d
"---Get metadata---"
keys = [x for x in d.keys() if type(d[x]) == np.ndarray ] # only keys linked to arrays
m = d.metadata
cmd = m.cmd # Scan command
"""
# Is this a 2D scan?
nfloats = 0
for s in cmd.split():
try:
float(s)
nfloats+=1
except ValueError:
pass
if nfloats > 6:
print( "This may be a 2D Scan - I'm afraid this isn't implemented yet!" )
"""
ttl = scantitle(d)
"---Determine scan variables from scan command---"
if varx not in keys:
try:
x = np.asarray(getattr(m, varx)).reshape(-1) # allow single value x
except:
varx = auto_varx(d)
x = getattr(d, varx)
else:
" y values from data file"
x = getattr(d, varx)
"***Get y values***"
if vary.lower().startswith('nroi'):
" y values from automatic peak search in pilatus"
# e.g. 'nroi' > Defaults to ROI2 in centre of pilatus
# e.g. 'nroi[11,11]' > in centre with size [11,11]
# e.g. 'nroi[109,241,11,11] > centred at [109,241] with size [11,11]
# e.g. 'nroibkg > As 'nroi', with background subtraction
# e.g. 'nroipeak' > As 'nroi', with peak search
# e.g. 'nroipeak[11,11]'> at peak centre, with size [11,11]
# e.g. 'nroipeakbkg[31,31]' > at peak centre with background subtraction
# e.g. 'nroi_sfm' > subtract frame 0 from all images before ROI is generated
vol = getvol(m.SRSRUN) # Load pilatus images as 3D volume
" Subtract first frame"
if 'sfm' in vary.lower():
bkgcut = vol[:,:,0].copy()
for n in range(len(x)):
vol[:,:,n] = vol[:,:,n] - bkgcut
" Find requested position in string"
roival = re.findall('\d+',vary) # get numbers in vary
if len(roival) == 2: roival = [str(pil_centre[0]),str(pil_centre[1]),roival[0],roival[1]] # Only two values given for size
if len(roival) < 4: roival = [str(pil_centre[0]),str(pil_centre[1]),'75','67'] # No values given - default to I16 ROI2
ROIcen = [int(roival[0]),int(roival[1])]
ROIsize = [int(roival[2]),int(roival[3])]
" Search for peak in pilatus"
if 'peak' in vary.lower():
ROIcen,frame = pilpeak(vol,disp=True)
y,ROI_maxval,ROI_bkg = pilroi(vol,ROIcen=ROIcen,ROIsize=ROIsize)
if 'maxval' in vary.lower():
y = ROI_maxval
" Handle single value x"
if len(x) < len(y) and len(x)==1:
y = np.asarray(np.mean(y)).reshape(-1)
" Calculate errors"
dy = error_func(y)
" Background"
if 'bkg' in vary.lower():
y = y-ROI_bkg
dy = np.sqrt( dy**2 + error_func(ROI_bkg)**2 )
else:
if vary not in keys:
try:
y = getattr(m,vary)*np.ones(len(x))
except:
vary = auto_vary(d)
y = getattr(d,vary)
else:
" y values from data file"
y = getattr(d,vary)
" Handle single value x"
if len(x) < len(y) and len(x)==1:
y = np.asarray(np.mean(y)).reshape(-1)
" Only apply errors to counting detectors"
if 'roi' in vary or vary in detectors:
dy = error_func(y)
else:
dy = 0*y
"---Get count time---"
# Count time can have several names
if 't' in keys:
cnt = 1.0*d.t
elif 'counttime' in keys:
cnt = 1.0*d.counttime
elif 'count_time' in keys:
cnt = 1.0*d.count_time
else:
cnt=1.0
"---Get incident beam normalisation---"
if normby.lower() in ['ic1','ic1monitor']:
inorm = d.ic1monitor/exp_monitor
normtxt = '('+normby+'/'+str(exp_monitor)+')'
elif normby.lower() in ['rc','ring current']:
inorm = d.rc/exp_ring_current
normtxt = '('+normby+'/'+str(exp_ring_current)+')'
else:
inorm = np.ones(len(d.rc))
normtxt = ''
" Normalise the data by time, transmission and incident beam"
if norm and vary not in dont_normalise:
y = y/d.metadata.Transmission/cnt/inorm
dy = dy/d.metadata.Transmission/cnt/inorm
vary += '/Tran./t/'+normtxt
"---Apply absorption correction---"
if abscor is not None and abscor is not False:
# Absorption correction based on a flat plate perpendicular to the scattering plane
# Requires abscor = absorption coefficient of material
if abscor == True:
abscor = 1.0
A = scanvolcor(d,abscor)
y = y/A
dy = dy/A
vary += '/A'
return x,y,dy,varx,vary,ttl,d
def getmeta(nums=None, field='Energy'):
"""
Get metadata from multiple scans and return array of values
Usage: A = getmeta( [nums], 'field')
[nums] = list of scan numbers
field = name of metadata field
A = array of values from each scan with same length as nums
Any scans that do not contain field are returned 0
"""
nums = np.asarray(nums).reshape([-1])
# Prepare output array
metavals = np.zeros(len(nums))
for n,num in enumerate(nums):
d = readscan(num)
if d is None: continue
# Get values from dat file
if field in d.keys():
val = np.mean(getattr(d,field))
elif field in d.metadata.keys():
val = getattr(d.metadata,field)
else:
print( 'ERROR: Scan ',num,' contains no ',field,' data' )
continue
metavals[n] = val
if len(metavals) == 1:
metavals = metavals[0]
return metavals
def getmetas(nums=[0], fields=['Energy']):
"""
Get several metadata values from multiple scans and return list of values
Usage: A = getmetas( [nums], 'field')
[nums] = list of scan numbers / or nums=12345
fields = name or list of metadata field/ fields
A = list of values from each scan with same length as nums
Any scans that do not contain field are returned NaN
"""
" Multiple nums given as input"
try:
nums = nums[0:]
except TypeError:
nums=[nums]
" single field given"
if type(fields) is str:
fields = [fields]
"Loop over scans"
metavals = []
for n,num in enumerate(nums):
" scan object given as input"
try:
d = readscan(num)
except TypeError:
d = num
if d is None: continue
fieldvals = []
for field in fields:
# Get values from dat file
if field.lower() == 'hkl':
val = scanhkl(d)
elif field in d.keys():
val = np.mean(getattr(d,field))
elif field in d.metadata.keys():
val = getattr(d.metadata,field)
else:
val = np.NaN
print( 'ERROR: Scan ',num,' contains no ',field,' data' )
fieldvals += [val]
metavals += [fieldvals]
return metavals
def joindata(nums=None, varx='', vary='Energy', varz='', norm=True, sort=False, abscor=None, save=False):
"""
Get useful values from scans, join multiple scans together, output joined arrays
x,y,z,varx,vary,varz,ttl = joindata([nums],'varx','vary','varz')
x = nxm array of scanned values, where n is the length of the scan and m is the number of scans
y = nxm array of values that change with each scan
z = nxm array of measured values
varx,vary,varz = names of scan values
ttl = title generated for these scans
Options:
norm True/False Normalisation options as in getdata
sort True/False Sort the data by y
abscor True/False Absorption correction as in getdata
save True/False Save the resulting arrays in a numpy file
If the output is saved as a numpy file, it can be loaded using the command:
x,y,z,dz = np.load('path/outputfile.npy')
"""
" Single 2D scan"
if type(nums) == int or len(nums)==1:
d = readscan(nums)
keys = d.keys()
if varx not in keys: varx = keys[0]
if vary not in keys: vary = keys[1]
x,z,dz,out_varx,out_varz,ttl,d = getdata(nums,varx=varx,vary=varz,norm=norm,abscor=abscor)
y,z,dz,out_vary,out_varz,ttl,d = getdata(nums,varx=vary,vary=varz,norm=norm,abscor=abscor)
" Determine steps in 1st dimension"
cmd = d.metadata.cmd.split()
ln=len(frange(float(cmd[2]),float(cmd[3]),float(cmd[4])))
n_steps = len(x)/ln
# Reshape
storex = x.reshape([-1,n_steps])
storey = y.reshape([-1,n_steps])
storez = z.reshape([-1,n_steps])
storedz = dz.reshape([-1,n_steps])
skip = []
nums = [nums]
else:
" Load first scan to assign data sizes"
num = nums[0]
x,z,dz,out_varx,out_varz,ttl,d = getdata(num,varx=varx,vary=varz,norm=norm,abscor=abscor)
scn_points = len(x)
n_scans = len(nums)
ini_cmd = d.metadata.cmd_short
" Assign storage arrays"
storex = np.zeros([scn_points,n_scans])
storey = np.zeros([scn_points,n_scans])
storez = np.zeros([scn_points,n_scans])
storedz = np.zeros([scn_points,n_scans])
skip = []
" Loop over each run and get data"
for n,num in enumerate(nums):
# Get x and z values using getdata
x,z,dz,varx2,varz2,ttl2,d = getdata(num,varx,varz,norm,abscor)
# Get y values from dat file
if vary in d.keys():
y = getattr(d,vary)
elif vary in d.metadata.keys():
yval = getattr(d.metadata,vary)
if vary == 'psi' and yval < 0:
yval = yval+360.0
y = np.ones(scn_points)*yval
else:
print( 'ERROR: Scan ',num,' contains no ',vary,' data' )
return
# Check correct length of scan
if len(x) != scn_points:
print( 'Error: Scan ',num,' has the wrong number of data points. Skipping...' )
skip += [n]
continue
# Check correct type of scan
if varx2 != out_varx:
print( 'Error: Scan ',num,' is the wrong type of scan. Skipping...' )
skip += [n]
continue
storex[:,n] = x # Scanned variable
storey[:,n] = y # dependent variable
storez[:,n] = z # measured variable
storedz[:,n] = dz # error on measured variable
" Remove skipped columns"
storex = np.delete(storex,skip,1)
storey = np.delete(storey,skip,1)
storez = np.delete(storez,skip,1)
storedz = np.delete(storedz,skip,1)
" Sort y"
if sort:
sort_index = np.argsort(storey[0,:])
storex = storex[:,sort_index]
storey = storey[:,sort_index]
storez = storez[:,sort_index]
storedz = storedz[:,sort_index]
"Generate title"
"""
vals=ttl.split()
ettl = vals[0]
rn = vals[1]
hkl = vals[2]
energy = vals[3]
temp = vals[4]
if len(vals) > 5:
pol = vals[5]
else:
pol = ''
fmt = '{ttl} {xvar}-{yvar} #{rn1:1.0f}-{rn2:1.0f} {hkl} {en} {temp} {pol}'
if out_varx in ['Energy','en'] or vary in ['Energy','en']:
energy=''
if out_varx in ['Ta','Tb'] or vary in ['Ta','Tb']:
temp=''
out_ttl = fmt.format(ttl=ettl,rn1=nums[0],rn2=nums[-1],
xvar=out_varx,yvar=vary,
hkl=hkl,en=energy,temp=temp,pol=pol).strip()
"""
out_ttl = scantitle(nums)
" Save a .npy file"
" Data can be loaded with x,y,z,dz = np.load(file.npy)"
if save not in [None, False, '']:
# save data to file
if type(save) is str:
savefile = os.path.join(savedir, '{}.npy'.format(save))
head = '{}\n{}\n{}, {}, {}, {}'.format(out_ttl,ini_cmd,out_varx,vary,out_varz,'error_'+out_varz)
else:
savefile = os.path.join(savedir, '{} dep {}-{}.npy'.format(vary,nums[0],nums[-1]))
head = '{}\n{}\n{}, {}, {}, {}'.format(out_ttl,ini_cmd,out_varx,vary,out_varz,'error_'+out_varz)
np.save(savefile,(storex,storey,storez,storedz))#,header=head)
print( 'Scans saved as {}'.format(savefile) )
print( 'Load with: x,y,z,dz = np.load(\'{}\')'.format(savefile))
return storex,storey,storez,out_varx,vary,out_varz,out_ttl
def getvol(num, ROIcen=None, ROIsize=None):
"""
Load Pilatus images into a single volume:
vol=getvol(#/d)
# is the scan number or dataloader from readscan
vol is a [n x m x o] sized numpy array, where n and m are the size of the
pilatus detector (195 x 487) and o is the length of the scan.
The volume from a region of interest can be obtained using:
vol=getvol(#/d,ROIcen=[110,242],ROIsize=[31,31])
"""
" Load data"
try:
d = readscan(num)
except TypeError:
d = num
" Check 100k (small) or 2m (large) detector"
try:
pilname = [s for s in d.metadata.keys() if "_path_template" in s][0]
pilpath = getattr(d.metadata,pilname)
except IndexError:
print( 'Not a pilatus file!' )
return
" Load first image to get the detector size"
tif=pilpath % d.path[0]
file = os.path.join(filedir,tif)
file=file.replace('/',os.path.sep)
#im=misc.imread(file,flatten=True) # flatten required to read zylar 16 bit files
im = imread(file) # imageio
pil_size = im.shape
"""
if 'pilatus100k_path_template' in d.metadata.keys():
pilpath = d.metadata.pilatus100k_path_template
pil_size = [195,487]
elif 'pilatus2m_path_template' in d.metadata.keys():
pilpath = d.metadata.pilatus2m_path_template
pil_size = [1679,1475]
elif 'medipix_path_template' in d.metadata.keys():
pilpath = d.metadata.medipix_path_template
pil_size = [256,256]
elif 'cam1_path_template' in d.metadata.keys():
pilpath = d.metadata.cam1_path_template
pil_size = [946,1292]
else:
print( 'Not a pilatus file!' )
return
"""
"Check volume size - don't load large volumes as it is too slow"
numimag = len(d.path)
if pil_size[0]*pil_size[1]*numimag > pil_max_size:
print('The array size is too large! Returning only the first image')
numimag = 1
"Load each image into a single volume"
vol = np.zeros([pil_size[0],pil_size[1],numimag]) # [195,487,~31]
for n in range(numimag):
" Prepare file name"
tif=pilpath % d.path[n]
file = os.path.join(filedir,tif)
file=file.replace('/',os.path.sep)
" Load image "
#t=dnp.io.load(file,warn=False)
#vol[:,:,n] = t.image0 #"image0" varies for some reason
#im=misc.imread(file,flatten=True) # this is more reliable than dnp.io.load
im = imread(file) # imageio
" Flip image"
#im = np.flipud(im)
" Convert to double"
im = 1.0*im
" Assign dead pixels to median intensity, or zero for bad image (all -1)"
im[im<0] = dead_pixel_func(im)
im[im<0] = 0
" Assign hot pixels to median intensity, or zero for bad image (all hot)"
im[im>hot_pixel] = dead_pixel_func(im)
im[im>hot_pixel] = 0
" Mask dead pixels ***Feb 2017***"
im[pilatus_dead_pixels[:,0],pilatus_dead_pixels[:,1]] = 0
" Add to 3D array"
vol[:,:,n] = im
if ROIsize is not None:
if ROIcen is None:
ROIcen = pil_centre
" Only load the volume within the region of interest"
idxi = [ROIcen[0]-ROIsize[0]//2,ROIcen[0]+ROIsize[0]//2+1]
idxj = [ROIcen[1]-ROIsize[1]//2,ROIcen[1]+ROIsize[1]//2+1]
#print( 'ROI = [{0},{1},{2},{3}]'.format(idxi[0],idxj[0],idxi[1],idxj[1]) )
" Check the box is within the detector"
if idxi[0] < 0: idxi[1] = idxi[1] - idxi[0]; idxi[0] = 0
if idxi[1] > pil_size[0]: idxi[0] = idxi[0] - (idxi[1]-pil_size[0]); idxi[1] = pil_size[0]
if idxj[0] < 0: idxj[1] = idxj[1] - idxj[0]; idxj[0] = 0
if idxj[1] > pil_size[1]: idxj[0] = idxj[0] - (idxj[1]-pil_size[1]); idxj[1] = pil_size[1]