-
Notifications
You must be signed in to change notification settings - Fork 9
/
filewriters.py
1661 lines (1397 loc) · 55.1 KB
/
filewriters.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
"""
Bluesky callbacks for writing files (such as for SPEC or NeXus).
The filewriter callbacks here are written as classes since they
cache information while collecting data and preserve information
about the state of the document sequence.
.. autosummary::
~FileWriterCallbackBase
~NXWriterAPS
~NXWriter
~SpecWriterCallback
~spec_comment
"""
#-----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: jemian@anl.gov
# :copyright: (c) 2017-2020, UChicago Argonne, LLC
#
# Distributed under the terms of the Creative Commons Attribution 4.0 International Public License.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
from collections import OrderedDict
import datetime
import getpass
import h5py
import logging
import numpy as np
import os
import pyRestTable
import socket
import time
import yaml
logger = logging.getLogger(__name__)
NEXUS_FILE_EXTENSION = "hdf" # use this file extension for the output
NEXUS_RELEASE = 'v2020.1' # NeXus release to which this file is written
SPEC_TIME_FORMAT = "%a %b %d %H:%M:%S %Y"
SCAN_ID_RESET_VALUE = 0
def _rebuild_scan_command(doc):
"""
reconstruct the scan command for SPEC data file #S line
PARAMETERS
doc
*object* :
instance of a bluesky ``start`` document
RETURNS
*str* :
"scan_number reconstructed_scan_command"
"""
def get_name(src):
"""
get name field from object representation
given: EpicsMotor(prefix='xxx:m1', name='m1', settle_time=0.0,
timeout=None, read_attrs=['user_readback', 'user_setpoint'],
configuration_attrs=['motor_egu', 'velocity', 'acceleration',
'user_offset', 'user_offset_dir'])
return: "m1"
"""
s = str(src)
p = s.find("(")
if p > 0: # only if an open parenthesis is found
parts = s[p+1:].rstrip(")").split(",")
for item in parts:
# should be key=value pairs
item = item.strip()
p = item.find("=")
if item[:p] == "name":
s = item[p+1:] # get the name value
break
return s
s = []
if "plan_args" in doc:
for _k, _v in doc['plan_args'].items():
if _k == "detectors":
_v = doc[_k]
elif _k.startswith("motor"):
_v = doc["motors"]
elif _k == "args":
_v = "[" + ", ".join(map(get_name, _v)) + "]"
s.append(f"{_k}={_v}")
cmd = "{}({})".format(doc.get("plan_name", ""), ", ".join(s))
scan_id = doc.get("scan_id") or 1
return f"{scan_id} {cmd}"
# TODO: consider refactor to use FileWriterCallbackBase()
class SpecWriterCallback(object):
"""
Collect data from Bluesky RunEngine documents to write as SPEC data.
This gathers data from all documents in a scan and appends scan to the file
when the ``stop`` document is received. One or more scans can be written to
the same file. The file format is text.
.. note:: ``SpecWriterCallback()`` does **not** inherit
from ``FileWriterCallbackBase()``.
PARAMETERS
filename
*string* :
(optional)
Local, relative or absolute name of SPEC data file to be used.
If ``filename=None``, defaults to format of ``YYYmmdd-HHMMSS.dat``
derived from the current system time.
auto_write
*boolean* :
(optional)
If ``True`` (default), ``write_scan()`` is called when *stop* document
is received.
If ``False``, the caller is responsible for calling ``write_scan()``
before the next ``start`` document is received.
RE
*object* :
Instance of ``bluesky.RunEngine`` or ``None``.
reset_scan_id
*boolean* :
(optional)
If True, and filename exists, then sets ``RE.md.scan_id`` to
highest scan number in existing SPEC data file.
default: False
User Interface methods
.. autosummary::
~receiver
~newfile
~usefile
~make_default_filename
~clear
~prepare_scan_contents
~write_scan
Internal methods
.. autosummary::
~write_header
~start
~descriptor
~event
~bulk_events
~datum
~resource
~stop
"""
# EXAMPLE : the :ref:`specfile_example() <example_specfile>`
# writes one or more scans to a SPEC data file using a jupyter notebook.
def __init__(self, filename=None, auto_write=True, RE=None, reset_scan_id=False):
self.clear()
self.buffered_comments = self._empty_comments_dict()
self.spec_filename = filename
self.auto_write = auto_write
self.uid_short_length = 8
self.write_file_header = False
self.spec_epoch = None # for both #E & #D line in header, also offset for all scans
self.spec_host = None
self.spec_user = None
self._datetime = None # most recent document time as datetime object
self._streams = {} # descriptor documents, keyed by uid
self.RE = RE
if reset_scan_id == True:
reset_scan_id = SCAN_ID_RESET_VALUE
self.reset_scan_id = reset_scan_id
if filename is None or not os.path.exists(filename):
self.newfile(filename)
else:
max_scan_id = self.usefile(filename)
if RE is not None and reset_scan_id is not False:
RE.md["scan_id"] = max_scan_id
def clear(self):
"""reset all scan data defaults"""
self.uid = None
self.scan_epoch = None # absolute epoch to report in scan #D line
self.time = None # full time from document
self.comments = self._empty_comments_dict()
self.data = OrderedDict() # data in the scan
self.detectors = OrderedDict() # names of detectors in the scan
self.hints = OrderedDict() # why?
self.metadata = OrderedDict() # #MD lines in header
self.motors = OrderedDict() # names of motors in the scan
self.positioners = OrderedDict() # names in #O, values in #P
self.num_primary_data = 0
#
# note: for one scan, #O & #P information is not provided
# unless collecting baseline data
# wait for case with baseline data that needs #O/#P lines
#
self.columns = OrderedDict() # #L in scan
self.scan_command = None # #S line
self.scanning = False
def _empty_comments_dict(self):
return dict(
start=[],
event=[],
descriptor=[],
resource=[],
datum=[],
stop=[])
def _cmt(self, key, text):
"""enter a comment"""
dt = self._datetime or datetime.datetime.now()
ts = datetime.datetime.strftime(dt, SPEC_TIME_FORMAT)
if self.scanning:
dest = self.comments
else:
dest = self.buffered_comments
dest[key].append(f"{ts}. {text}")
def receiver(self, key, document):
"""Bluesky callback: receive all documents for handling"""
xref = dict(
start = self.start,
descriptor = self.descriptor,
event = self.event,
bulk_events = self.bulk_events,
datum = self.datum,
resource = self.resource,
stop = self.stop,
)
logger = logging.getLogger(__name__)
if key in xref:
uid = document.get("uid") or document.get("datum_id")
logger.debug("%s document, uid=%s", key, str(uid))
ts = document.get("time")
if ts is None:
ts = datetime.datetime.now()
else:
ts = datetime.datetime.fromtimestamp(document["time"])
self._datetime = ts
xref[key](document)
else:
msg = f"custom_callback encountered: {key} : {document}"
# raise ValueError(msg)
logger.warning(msg)
def start(self, doc):
"""handle *start* documents"""
known_properties = """
uid time project sample scan_id group owner
hints
plan_type plan_name plan_args
""".split()
self.clear()
self.scanning = True
self.uid = doc["uid"]
self._cmt("start", f"uid = {self.uid}")
self.metadata["uid"] = f"{self.uid}"
for d, cl in self.buffered_comments.items():
# bring in any comments collected when not scanning
self.comments[d] += cl
self.buffered_comments = self._empty_comments_dict()
self.time = doc["time"]
self.scan_epoch = int(self.time)
self.scan_id = doc["scan_id"] or 0
# Which reference? fixed counting time or fixed monitor count?
# Can this be omitted?
self.T_or_M = None # for now
# self.T_or_M = "T" # TODO: how to get this from the document stream?
# self.T_or_M_value = 1
# self._cmt("start", "!!! #T line not correct yet !!!")
# metadata
for key in sorted(doc.keys()):
if key not in known_properties:
self.metadata[key] = doc[key]
self.start_hints = doc.get("hints", {})
# various dicts
for item in "detectors hints motors".split():
if item in doc:
obj = self.__getattribute__(item)
for key in doc.get(item):
obj[key] = None
cmt = "plan_type = " + doc["plan_type"]
ts = datetime.datetime.strftime(self._datetime, SPEC_TIME_FORMAT)
self.comments["start"].insert(0, f"{ts}. {cmt}")
self.scan_command = _rebuild_scan_command(doc)
def descriptor(self, doc):
"""
handle *descriptor* documents
prepare for primary scan data, ignore any other data stream
"""
if doc["uid"] in self._streams:
fmt = "duplicate descriptor UID {} found"
raise KeyError(fmt.format(doc["uid"]))
# log descriptor documents by uid
# referenced by event and bulk_events documents
self._streams[doc["uid"]] = doc
if doc["name"] != "primary":
return
keyset = list(doc["data_keys"].keys())
doc_hints_names = []
for k, d in doc["hints"].items():
doc_hints_names.append(k)
doc_hints_names += d["fields"]
# independent variable(s) first
# assumes start["motors"] was defined
first_keys = [k for k in self.motors if k in keyset]
# TODO: if len(first_keys) == 0: look at self.start_hints
# dependent variable(s) last
# assumes start["detectors"] was defined
last_keys = [d for d in self.detectors if d in doc_hints_names]
# TODO: if len(last_keys) == 0: look at doc["hints"]
# get remaining keys from keyset, they go in the middle
middle_keys = [k for k in keyset if k not in first_keys + last_keys]
epoch_keys = "Epoch_float Epoch".split()
self.data.update({k: [] for k in first_keys+epoch_keys+middle_keys+last_keys})
def event(self, doc):
"""
handle *event* documents
"""
stream_doc = self._streams.get(doc["descriptor"])
if stream_doc is None:
fmt = "descriptor UID {} not found"
raise KeyError(fmt.format(doc["descriptor"]))
if stream_doc["name"] == "primary":
for k in doc["data"].keys():
if k not in self.data.keys():
msg = f"unexpected failure here, key {k} not found"
raise KeyError(msg)
#return # not our expected event data
for k in self.data.keys():
if k == "Epoch":
v = int(doc["time"] - self.time + 0.5)
elif k == "Epoch_float":
v = doc["time"] - self.time
else:
v = doc["data"].get(k, 0) # like SPEC, default to 0 if not found by name
self.data[k].append(v)
self.num_primary_data += 1
def bulk_events(self, doc):
"""handle *bulk_events* documents"""
pass
def datum(self, doc):
"""handle *datum* documents"""
self._cmt("datum", "datum " + str(doc))
def resource(self, doc):
"""handle *resource* documents"""
self._cmt("resource", "resource " + str(doc))
def stop(self, doc):
"""handle *stop* documents"""
if "num_events" in doc:
for k, v in doc["num_events"].items():
self._cmt("stop", f"num_events_{k} = {v}")
if "exit_status" in doc:
self._cmt("stop", "exit_status = " + doc["exit_status"])
else:
self._cmt("stop", "exit_status = not available")
if self.auto_write:
self.write_scan()
self.scanning = False
def prepare_scan_contents(self):
"""
format the scan for a SPEC data file
:returns: [str] a list of lines to append to the data file
"""
dt = datetime.datetime.fromtimestamp(self.scan_epoch)
lines = []
lines.append("")
lines.append("#S " + self.scan_command)
lines.append("#D " + datetime.datetime.strftime(dt, SPEC_TIME_FORMAT))
if self.T_or_M is not None:
lines.append(f"#{self.T_or_M} {self.T_or_M_value}")
for v in self.comments["start"]:
#C Wed Feb 03 16:51:38 2016. do ./usaxs.mac.
lines.append("#C " + v) # TODO: add time/date stamp as SPEC does
for v in self.comments["descriptor"]:
lines.append("#C " + v)
for k, v in self.metadata.items():
# "#MD" is our ad hoc SPEC data tag
lines.append(f"#MD {k} = {v}")
lines.append("#P0 ")
lines.append("#N " + str(len(self.data.keys())))
if len(self.data.keys()) > 0:
lines.append("#L " + " ".join(self.data.keys()))
for i in range(self.num_primary_data):
str_data = OrderedDict()
s = []
for k in self.data.keys():
datum = self.data[k][i]
if isinstance(datum, str):
# SPEC scan data is expected to be numbers
# this is text, substitute the row number
# and report after this line in a #U line
str_data[k] = datum
datum = i
s.append(str(datum))
lines.append(" ".join(s))
for k in str_data.keys():
# report the text data
lines.append(f"#U {i} {k} {str_data[k]}")
else:
lines.append("#C no data column labels identified")
for v in self.comments["event"]:
lines.append("#C " + v)
for v in self.comments["resource"]:
lines.append("#C " + v)
for v in self.comments["datum"]:
lines.append("#C " + v)
for v in self.comments["stop"]:
lines.append("#C " + v)
return lines
def _write_lines_(self, lines, mode="a"):
"""write (more) lines to the file"""
with open(self.spec_filename, mode) as f:
f.write("\n".join(lines))
def write_header(self):
"""write the header section of a SPEC data file"""
dt = datetime.datetime.fromtimestamp(self.spec_epoch)
lines = []
lines.append(f"#F {self.spec_filename}")
lines.append(f"#E {self.spec_epoch}")
lines.append(f"#D {datetime.datetime.strftime(dt, SPEC_TIME_FORMAT)}")
lines.append(f"#C Bluesky user = {self.spec_user} host = {self.spec_host}")
lines.append("#O0 ")
lines.append("#o0 ")
lines.append("")
if os.path.exists(self.spec_filename):
lines.insert(0, "")
self._write_lines_(lines, mode="a+")
self.write_file_header = False
def write_scan(self):
"""
write the most recent (completed) scan to the file
* creates file if not existing
* writes header if needed
* appends scan data
note: does nothing if there are no lines to be written
"""
if os.path.exists(self.spec_filename):
with open(self.spec_filename) as f:
buf = f.read()
if buf.find(self.uid) >= 0:
# raise exception if uid is already in the file!
msg = f"{self.spec_filename} already contains uid={self.uid}"
raise ValueError(msg)
logger = logging.getLogger(__name__)
lines = self.prepare_scan_contents()
lines.append("")
if lines is not None:
if self.write_file_header:
self.write_header()
logger.info("wrote header to SPEC file: %s", self.spec_filename)
self._write_lines_(lines, mode="a")
logger.info("wrote scan %d to SPEC file: %s", self.scan_id, self.spec_filename)
def make_default_filename(self):
"""generate a file name to be used as default"""
now = datetime.datetime.now()
return datetime.datetime.strftime(now, "%Y%m%d-%H%M%S")+".dat"
def newfile(self, filename=None, scan_id=None, RE=None):
"""
prepare to use a new SPEC data file
but don't create it until we have data
"""
self.clear()
filename = filename or self.make_default_filename()
if os.path.exists(filename):
from spec2nexus.spec import SpecDataFile
sdf = SpecDataFile(filename)
scan_list = sdf.getScanNumbers()
l = len(scan_list)
m = max(map(float, scan_list))
highest = int(max(l, m) + 0.9999) # solves issue #128
scan_id = max(scan_id or 0, highest)
self.spec_filename = filename
self.spec_epoch = int(time.time()) # ! no roundup here!!!
self.spec_host = socket.gethostname() or 'localhost'
self.spec_user = getpass.getuser() or 'BlueskyUser'
self.write_file_header = True # don't write the file yet
# backwards-compatibility
if isinstance(scan_id, bool):
# True means reset the scan ID to default
# False means do not modify it
scan_id = {True: SCAN_ID_RESET_VALUE, False: None}[scan_id]
if scan_id is not None and RE is not None:
# RE is an instance of bluesky.run_engine.RunEngine
# (or duck type for testing)
RE.md["scan_id"] = scan_id
self.scan_id = scan_id
return self.spec_filename
def usefile(self, filename):
"""read from existing SPEC data file"""
if not os.path.exists(self.spec_filename):
raise IOError(f"file {filename} does not exist")
scan_id = None
with open(filename, "r") as f:
key = "#F"
line = f.readline().strip()
if not line.startswith(key+" "):
raise ValueError(f"first line does not start with {key}")
key = "#E"
line = f.readline().strip()
if not line.startswith(key+" "):
raise ValueError(f"first line does not start with {key}")
epoch = int(line.split()[-1])
key = "#D"
line = f.readline().strip()
if not line.startswith(key+" "):
raise ValueError("first line does not start with "+key)
# ignore content, it is derived from #E line
key = "#C"
line = f.readline().strip()
if not line.startswith(key+" "):
raise ValueError("first line does not start with "+key)
p = line.split()
username = "BlueskyUser"
if len(p) > 4 and p[2] == "user":
username = p[4]
# find the highest scan number used
key = "#S"
scan_ids = []
for line in f.readlines():
if line.startswith(key+" ") and len(line.split())>1:
scan_id = int(line.split()[1])
scan_ids.append(scan_id)
scan_id = max(scan_ids)
self.spec_filename = filename
self.spec_epoch = epoch
self.spec_user = username
return scan_id
def spec_comment(comment, doc=None, writer=None):
"""
make it easy to add spec-style comments in a custom plan
These comments *only* go into the SPEC data file.
PARAMETERS
comment
*string* :
(optional)
Comment text to be written. SPEC expects it to be only one line!
doc
*string* :
(optional)
Bluesky RunEngine document type.
One of: ``start descriptor event resource datum stop``
(default: ``event``)
writer
*obj* :
(optional)
Instance of ``SpecWriterCallback()``,
typically: ``specwriter = SpecWriterCallback()``
EXAMPLE:
Execution of this plan (with ``RE(myPlan())``)::
def myPlan():
yield from bps.open_run()
spec_comment("this is a start document comment", "start")
spec_comment("this is a descriptor document comment", "descriptor")
yield bps.Msg('checkpoint')
yield from bps.trigger_and_read([scaler])
spec_comment("this is an event document comment after the first read")
yield from bps.sleep(2)
yield bps.Msg('checkpoint')
yield from bps.trigger_and_read([scaler])
spec_comment("this is an event document comment after the second read")
spec_comment("this is a stop document comment", "stop")
yield from bps.close_run()
results in this SPEC file output::
#S 1145 myPlan()
#D Mon Jan 28 12:48:09 2019
#C Mon Jan 28 12:48:09 2019. plan_type = generator
#C Mon Jan 28 12:48:09 2019. uid = ef98648a-8e3a-4e7e-ac99-3290c9b5fca7
#C Mon Jan 28 12:48:09 2019. this is a start document comment
#C Mon Jan 28 12:48:09 2019. this is a descriptor document comment
#MD APSTOOLS_VERSION = 2019.0103.0+5.g0f4e8b2
#MD BLUESKY_VERSION = 1.4.1
#MD OPHYD_VERSION = 1.3.0
#MD SESSION_START = 2019-01-28 12:19:25.446836
#MD beamline_id = developer
#MD ipython_session_start = 2018-02-14 12:54:06.447450
#MD login_id = mintadmin@mint-vm
#MD pid = 21784
#MD proposal_id = None
#N 2
#L Epoch_float scaler_time Epoch
1.4297869205474854 1.1 1
4.596935987472534 1.1 5
#C Mon Jan 28 12:48:11 2019. this is an event document comment after the first read
#C Mon Jan 28 12:48:14 2019. this is an event document comment after the second read
#C Mon Jan 28 12:48:14 2019. this is a stop document comment
#C Mon Jan 28 12:48:14 2019. num_events_primary = 2
#C Mon Jan 28 12:48:14 2019. exit_status = success
"""
global specwriter # such as: specwriter = SpecWriterCallback()
writer = writer or specwriter
if doc is None:
if writer.scanning:
doc = "event"
else:
doc = "start"
for line in comment.splitlines():
writer._cmt(doc, line)
class FileWriterCallbackBase:
"""
Base class for filewriter callbacks.
New with apstools release 1.3.0.
Applications should subclass and rewrite the ``writer()`` method.
The local buffers are cleared when a start document is received.
Content is collected here from each document until the stop document.
The content is written once the stop document is received.
User Interface methods
.. autosummary::
~receiver
Internal methods
.. autosummary::
~clear
~make_file_name
~writer
Document Handler methods
.. autosummary::
~bulk_events
~datum
~descriptor
~event
~resource
~start
~stop
"""
file_extension = "dat"
file_name = None
file_path = None
# convention: methods written in alphabetical order
def __init__(self, *args, **kwargs):
"""Initialize: clear and reset."""
self.clear()
self.xref = dict(
bulk_events = self.bulk_events,
datum = self.datum,
descriptor = self.descriptor,
event = self.event,
resource = self.resource,
start = self.start,
stop = self.stop,
)
def receiver(self, key, doc):
"""
bluesky callback (handles a stream of documents)
"""
handler = self.xref.get(key)
if handler is None:
logger.error("unexpected key %s" % key)
else:
handler(doc)
# - - - - - - - - - - - - - - -
def clear(self):
"""
delete any saved data from the cache and reinitialize
"""
self.acquisitions = {}
self.detectors = []
self.exit_status = None
self.externals = {}
self.metadata = {}
self.plan_name = None
self.positioners = []
self.scanning = False
self.scan_id = None
self.streams = {}
self.start_time = None
self.stop_reason = None
self.stop_time = None
self.uid = None
def make_file_name(self):
"""
generate a file name to be used as default
default format: {ymd}-{hms}-S{scan_id}-{short_uid}.{ext}
where the time (the run start time):
* ymd = {year:4d}{month:02d}{day:02d}
* hms = {hour:02d}{minute:02d}{second:02d}
override in subclass to change
"""
start_time = datetime.datetime.fromtimestamp(self.start_time)
fname = start_time.strftime("%Y%m%d-%H%M%S")
fname += f"-S{self.scan_id:05d}"
fname += f"-{self.uid[:7]}.{self.file_extension}"
path = os.path.abspath(self.file_path or os.getcwd())
return os.path.join(path, fname)
def writer(self):
"""
print summary of run as diagnostic
override this method in subclass to write a file
"""
# logger.debug("acquisitions: %s", yaml.dump(self.acquisitions))
fname = self.file_name or self.make_file_name()
print("print to console")
print(f"suggested file name: {fname}")
tbl = pyRestTable.Table()
tbl.labels = "key value".split()
keys = "plan_name scan_id exit_status start_time stop_reason stop_time uid".split()
for k in sorted(keys):
tbl.addRow((k, getattr(self, k)))
print(tbl)
def trim(value, length=60):
text = str(value)
if len(text) > length:
text = text[:length-3] + "..."
return text
tbl = pyRestTable.Table()
tbl.labels = "metadata_key value".split()
for k, v in sorted(self.metadata.items()):
tbl.addRow((k, trim(v)))
print(tbl)
tbl = pyRestTable.Table()
tbl.labels = "stream num_vars num_values".split()
for k, v in sorted(self.streams.items()):
if len(v) != 1:
print("expecting only one descriptor in stream %s, found %s" % (k, len(v)))
else:
data = self.acquisitions[v[0]]["data"]
num_vars = len(data)
symbol = list(data.keys())[0] # get the key (symbol) of first data object
if num_vars == 0:
num_values = 0
else:
num_values = len(data[symbol]["data"])
tbl.addRow((k, num_vars, num_values))
print(tbl)
tbl = pyRestTable.Table()
tbl.labels = "external_key type value".split()
for k, v in self.externals.items():
tbl.addRow((k, v["_document_type_"], trim(v)))
print(tbl)
print(f"elapsed scan time: {self.stop_time-self.start_time:.3f}s")
# - - - - - - - - - - - - - - -
def bulk_events(self, doc):
"""Deprecated. Use EventPage instead."""
if not self.scanning:
return
logger.info("not handled yet")
logger.info(doc)
logger.info("-"*40)
def datum(self, doc):
"""
Like an event, but for data recorded outside of bluesky.
Example::
Datum
=====
datum_id : 621caa0f-70f1-4e3d-8718-b5123d434502/0
datum_kwargs :
HDF5_file_name : /mnt/usaxscontrol/USAXS_data/2020-06/06_10_Minjee_waxs/AGIX3N1_0699.hdf
point_number : 0
resource : 621caa0f-70f1-4e3d-8718-b5123d434502
"""
if not self.scanning:
return
# stash the whole thing (sort this out in the writer)
ext = self.externals[doc["datum_id"]] = dict(doc)
ext["_document_type_"] = "datum"
def descriptor(self, doc):
"""
description of the data stream to be acquired
"""
if not self.scanning:
return
stream = doc["name"]
uid = doc["uid"]
if stream not in self.streams:
self.streams[stream] = []
self.streams[stream].append(uid)
if uid not in self.acquisitions:
self.acquisitions[uid] = dict(
stream = stream,
data = {}
)
data = self.acquisitions[uid]["data"]
for k, entry in doc["data_keys"].items():
# logger.debug("entry %s: %s", k, entry)
dd = data[k] = {}
dd["source"] = entry.get("source", 'local')
dd["dtype"] = entry.get("dtype", '')
dd["shape"] = entry.get( "shape", [])
dd["units"] = entry.get("units", '')
dd["lower_ctrl_limit"] = entry.get("lower_ctrl_limit", '')
dd["upper_ctrl_limit"] = entry.get("upper_ctrl_limit", '')
dd["precision"] = entry.get("precision", 0)
dd["object_name"] = entry.get("object_name", k)
dd["data"] = [] # entry data goes here
dd["time"] = [] # entry time stamps here
dd["external"] = entry.get("external") is not None
# logger.debug("dd %s: %s", k, data[k])
def event(self, doc):
"""
a single "row" of data
"""
if not self.scanning:
return
# uid = doc["uid"]
descriptor_uid = doc["descriptor"]
# seq_num = doc["seq_num"]
# gather the data by streams
descriptor = self.acquisitions.get(descriptor_uid)
if descriptor is not None:
for k, v in doc["data"].items():
data = descriptor["data"].get(k)
if data is None:
print("entry key %s not found in descriptor of %s" % (k, descriptor["stream"]))
else:
data["data"].append(v)
data["time"].append(doc["timestamps"][k])
def resource(self, doc):
"""
like a descriptor, but for data recorded outside of bluesky
"""
if not self.scanning:
return
# stash the whole thing (sort this out in the writer)
ext = self.externals[doc["uid"]] = dict(doc)
ext["_document_type_"] = "resource"
def start(self, doc):
"""
beginning of a run, clear cache and collect metadata
"""
self.clear()
self.plan_name = doc["plan_name"]
self.scanning = True
self.scan_id = doc["scan_id"] or 0
self.start_time = doc["time"]
self.uid = doc["uid"]
self.detectors = doc.get("detectors", [])
self.positioners = doc.get("positioners") or doc.get("motors") or []
# gather the metadata
for k, v in doc.items():
if k in "scan_id time uid".split():
continue
self.metadata[k] = v
def stop(self, doc):
"""
end of the run, end collection and initiate the ``writer()`` method
"""
if not self.scanning:
return
self.exit_status = doc["exit_status"]
self.stop_reason = doc.get("reason", "not available")
self.stop_time = doc["time"]
self.scanning = False
self.writer()
class NXWriter(FileWriterCallbackBase):
"""
General class for writing HDF5/NeXus file (using only NeXus base classes).
New with apstools release 1.3.0.
One scan is written to one HDF5/NeXus file.
METHODS
.. autosummary::
~writer
~h5string
~add_dataset_attributes
~assign_signal_type
~create_NX_group
~get_sample_title
~get_stream_link
~write_data
~write_detector