-
Notifications
You must be signed in to change notification settings - Fork 2
/
xanes_exporter.py
233 lines (199 loc) · 8.03 KB
/
xanes_exporter.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
from prefect import flow, task, get_run_logger
from tiled.client import from_profile
import time as ttime
tiled_client = from_profile("nsls2")["srx"]
tiled_client_raw = tiled_client["raw"]
def xanes_textout(
scanid=-1,
header=[],
userheader={},
column=[],
usercolumn={},
usercolumnname=[],
output=True,
):
"""
scan: can be scan_id (integer) or uid (string). default=-1 (last scan run)
header: a list of items that exist in the event data to be put into
the header
userheader: a dictionary defined by user to put into the header
column: a list of items that exist in the event data to be put into
the column data
output: print all header fileds. if output = False, only print the ones
that were able to be written
default = True
"""
h = tiled_client_raw[scanid]
if "Beamline Commissioning (beamline staff only)".lower() in h.start["proposal"]["type"].lower():
filepath = f"/nsls2/data/srx/proposals/commissioning/{h.start['data_session']}/scan_{h.start['scan_id']}_xanes.txt"
else:
filepath = f"/nsls2/data/srx/proposals/{h.start['cycle']}/{h.start['data_session']}/scan_{h.start['scan_id']}_xanes.txt" # noqa: E501
with open(filepath, "w") as f:
dataset_client = h["primary"]["data"]
staticheader = (
"# XDI/1.0 MX/2.0\n"
+ "# Beamline.name: "
+ h.start["beamline_id"]
+ "\n"
+ "# Facility.name: NSLS-II\n"
+ "# Facility.ring_current:"
+ str(dataset_client["ring_current"][0])
+ "\n"
+ "# Scan.start.uid: "
+ h.start["uid"]
+ "\n"
+ "# Scan.start.time: "
+ str(h.start["time"])
+ "\n"
+ "# Scan.start.ctime: "
+ ttime.ctime(h.start["time"])
+ "\n"
+ "# Mono.name: Si 111\n"
)
f.write(staticheader)
for item in header:
if item in dataset_client.keys():
f.write("# " + item + ": " + str(dataset_client[item]) + "\n")
if output is True:
print(f"{item} is written")
else:
print(f"{item} is not in the scan")
for key in userheader:
f.write("# " + key + ": " + str(userheader[key]) + "\n")
if output is True:
print(f"{key} is written")
file_data = {}
for idx, item in enumerate(column):
if item in dataset_client.keys():
# retrieve the data from tiled that is going to be used
# in the file
file_data[item] = dataset_client[
item
].read()
f.write("# Column." + str(idx + 1) + ": " + item + "\n")
f.write("# ")
for item in column:
if item in dataset_client.keys():
f.write(str(item) + "\t")
for item in usercolumnname:
f.write(item + "\t")
f.write("\n")
f.flush()
offset = False
for idx in range(len(file_data[column[0]])):
for item in column:
if item in file_data:
f.write("{0:8.6g} ".format(file_data[item][idx]))
for item in usercolumnname:
if item in usercolumn:
if offset is False:
try:
f.write("{0:8.6g} ".format(usercolumn[item][idx]))
except KeyError:
offset = True
f.write("{0:8.6g} ".format(
usercolumn[item][idx + 1]))
else:
f.write("{0:8.6g} ".format(usercolumn[item][idx + 1]))
f.write("\n")
@task
def xanes_afterscan_plan(scanid):
logger = get_run_logger()
# Custom header list
headeritem = []
# Load header for our scan
h = tiled_client_raw[scanid]
if h.start["scan"].get("type") != "XAS_STEP":
logger.info(
"Incorrect document type. Not running exporter on this document."
)
return
# Construct basic header information
userheaderitem = {}
userheaderitem["uid"] = h.start["uid"]
userheaderitem["sample.name"] = h.start["scan"]["sample_name"]
# Create columns for data file
columnitem = ["energy_energy", "energy_bragg", "energy_c2_x"]
# Include I_M, I_0, and I_t from the SRS
if "sclr1" in h.start["detectors"]:
if "sclr_i0" in h["primary"].descriptors[0]["object_keys"]["sclr1"]:
columnitem.extend(["sclr_im", "sclr_i0", "sclr_it"])
else:
columnitem.extend(["sclr1_mca3", "sclr1_mca2", "sclr1_mca4"])
else:
raise KeyError("SRS not found in data!")
# Include fluorescence data if present, allow multiple rois
if "xs" in h.start["detectors"]:
if "ROI" in h.start["scan"].keys():
roinum = list(h.start["scan"]["ROI"])
else:
roinum = [1] # if no ROI key found, assume ROI 1
logger.info(roinum)
for i in roinum:
logger.info(f"Current roinumber: {i}")
roi_name = "roi{:02}".format(i)
roi_key = []
xs_channels = h["primary"].descriptors[0]["object_keys"]["xs"]
for xs_channel in xs_channels:
logger.info(f"Current xs_channel: {xs_channel}")
if "mca" + roi_name in xs_channel and "total_rbv" in xs_channel: # noqa: E501
roi_key.append(xs_channel)
columnitem.extend(roi_key)
# if ('xs2' in h.start['detectors']):
# if (type(roinum) is not list):
# roinum = [roinum]
# for i in roinum:
# roi_name = 'roi{:02}'.format(i)
# roi_key = []
# roi_key.append(getattr(xs2.channel1.rois, roi_name).value.name)
# [columnitem.append(roi) for roi in roi_key]
# Construct user convenience columns allowing prescaling of ion chamber,
# diode and fluorescence detector data
usercolumnitem = {}
datatablenames = []
if "xs" in h.start["detectors"]:
datatablenames.extend(roi_key)
if "xs2" in h.start["detectors"]:
datatablenames.extend(roi_key)
if "sclr1" in h.start["detectors"]:
if "sclr_im" in h["primary"].descriptors[0]["object_keys"]["sclr1"]:
datatablenames.extend(["sclr_im", "sclr_i0", "sclr_it"])
datatable = h["primary"].read(datatablenames)
else:
datatablenames.extend(["sclr1_mca2", "sclr1_mca3", "sclr1_mca4"])
datatable = h["primary"].read(datatablenames)
else:
raise KeyError
# Calculate sums for xspress3 channels of interest
if "xs" in h.start["detectors"]:
for i in roinum:
roi_name = "roi{:02}".format(i)
roi_key = []
for xs_channel in xs_channels:
if "mca" + roi_name in xs_channel and "total_rbv" in xs_channel: # noqa: E501
roi_key.append(xs_channel)
roisum = sum(datatable[roi_key].to_array()).to_series()
roisum = roisum.rename_axis("seq_num").rename(lambda x: x + 1)
usercolumnitem["If-{:02}".format(i)] = roisum
# usercolumnitem['If-{:02}'.format(i)].round(0)
# if 'xs2' in h.start['detectors']:
# for i in roinum:
# roi_name = 'roi{:02}'.format(i)
# roisum=datatable[getattr(xs2.channel1.rois,roi_name).value.name]
# usercolumnitem['If-{:02}'.format(i)] = roisum
# usercolumnitem['If-{:02}'.format(i)].round(0)
xanes_textout(
scanid=scanid,
header=headeritem,
userheader=userheaderitem,
column=columnitem,
usercolumn=usercolumnitem,
usercolumnname=usercolumnitem.keys(),
output=False,
)
@flow(log_prints=True)
def xanes_exporter(ref):
logger = get_run_logger()
logger.info("Start writing file with xanes_exporter...")
xanes_afterscan_plan(ref)
logger.info("Finish writing file with xanes_exporter.")