-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcomponents.py
More file actions
2139 lines (1782 loc) · 81.2 KB
/
Copy pathcomponents.py
File metadata and controls
2139 lines (1782 loc) · 81.2 KB
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
"""Interfaces to data from specific instruments
"""
import logging
import math
import re
from collections.abc import Iterable
from copy import copy
from warnings import warn
import numpy as np
import pandas as pd
from .exceptions import SourceNameError
from .reader import DataCollection, by_id, by_index
from .read_machinery import DataChunk, roi_shape, split_trains
from .utils import default_num_threads, unstack_regular
from .writer import FileWriter
from .write_cxi import XtdfCXIWriter, JUNGFRAUCXIWriter
__all__ = [
'AGIPD1M',
'AGIPD500K',
'DSSC1M',
'LPD1M',
'JUNGFRAU',
'identify_multimod_detectors',
]
log = logging.getLogger(__name__)
MAX_PULSES = 2700
NO_PULSE_ID = 9999
def multimod_detectors(detector_cls):
"""
Decorator for multimod detector classes (e.g. AGIPD/LPD/JUNGFRAU)
to store them in a list 'multimod_detectors.list' and their names
in 'multimod_detectors.names'.
Parameters
----------
detector_cls: class
Decorated detector class to append to the list.
Returns
-------
detector_cls: class
Unmodified decorated detector class.
"""
multimod_detectors.list = getattr(multimod_detectors, 'list', list())
multimod_detectors.list.append(detector_cls)
multimod_detectors.names = getattr(multimod_detectors, 'names', list())
multimod_detectors.names.append(detector_cls.__name__)
return detector_cls
def _check_pulse_selection(pulses):
"""Check and normalise a pulse selection"""
if not isinstance(pulses, (by_id, by_index)):
pulses = by_index[pulses]
val = pulses.value
if isinstance(pulses.value, slice):
# Ensure start/stop/step are all real numbers
start = val.start if (val.start is not None) else 0
stop = val.stop if (val.stop is not None) else MAX_PULSES
step = val.step if (val.step is not None) else 1
if not all(isinstance(s, int) for s in (start, stop, step)):
raise TypeError("Pulse selection slice must use integers or None")
if step < 1:
raise ValueError("Pulse selection slice must have positive step")
if (start < 0) or (stop < 0):
raise NotImplementedError("Negative pulse indices not supported")
return type(pulses)(slice(start, stop, step))
# Convert everything except slices to numpy arrays
elif isinstance(pulses.value, int):
val = np.array([val], dtype=np.uint64)
else:
val = np.asarray(val, dtype=np.uint64)
if (val < 0).any():
if isinstance(pulses, by_id):
raise ValueError("Pulse IDs cannot be negative")
else:
raise NotImplementedError("Negative pulse indices not supported")
return type(pulses)(val)
def _select_pulse_ids(pulses, data_pulse_ids):
"""Select pulses by ID across a chunk of trains
Returns a boolean array of which entries in data_pulse_ids match.
"""
if isinstance(pulses.value, slice):
s = pulses.value
desired = np.arange(s.start, s.stop, step=s.step, dtype=np.uint64)
else:
desired = pulses.value
return np.isin(data_pulse_ids, desired)
def _out_array(shape, dtype, fill_value=None):
if fill_value is None:
fill_value = np.nan if dtype.kind == 'f' else 0
fill_value = dtype.type(fill_value)
# Zeroed memory can be allocated faster than explicitly writing zeros
if fill_value == 0:
return np.zeros(shape, dtype=dtype)
else:
return np.full(shape, fill_value, dtype=dtype)
class MultimodDetectorBase:
"""Base class for detectors made of several modules as separate data sources
"""
_det_name_pat = r'([^/]+)'
_source_raw_pat = r'/DET/(?P<modno>\d+)CH'
_source_corr_pat = r'/CORR/(?P<modno>\d+)CH'
# Override in subclass
_main_data_key = '' # Key to use for checking data counts match
_mask_data_key = ''
_frames_per_entry = 1 # Override if separate pulse dimension in files
_modnos_start_at = 0 # Override if module numbers start at 1 (JUNGFRAU)
module_shape = (0, 0)
n_modules = 0
def __init__(self, data: DataCollection, detector_name=None, modules=None,
*, min_modules=1, raw=None):
if detector_name is None:
detector_name = self._find_detector_name(data)
if min_modules <= 0:
raise ValueError("min_modules must be a positive integer, not "
f"{min_modules!r}")
source_to_modno = self._identify_sources(data, detector_name, modules, raw=raw)
data = data.select([(src, '*') for src in source_to_modno])
self.detector_name = detector_name
self.source_to_modno = source_to_modno
# pandas' missing-data handling converts the data to floats if there
# are any gaps - so fill them with 0s and convert back to uint64.
mod_data_counts = pd.DataFrame({
src: data.get_data_counts(src, self._main_data_key)
for src in source_to_modno
}).fillna(0).astype(np.uint64)
# Within any train, all modules should have same count or zero
frame_counts = pd.Series(0, index=mod_data_counts.index, dtype=np.uint64)
for tid, data_counts in mod_data_counts.iterrows():
count_vals = set(data_counts) - {0}
if len(count_vals) > 1:
raise ValueError(
f"Inconsistent frame counts for train {tid}: {count_vals}"
)
elif count_vals:
frame_counts[tid] = count_vals.pop()
self.data = self._select_trains(data, mod_data_counts, min_modules)
# This should be a reversible 1-to-1 mapping
self.modno_to_source = {m: s for (s, m) in source_to_modno.items()}
assert len(self.modno_to_source) == len(self.source_to_modno)
self.frame_counts = frame_counts[self.data.train_ids]
self.train_ids_perframe = np.repeat(
self.frame_counts.index.values, self.frame_counts.values.astype(np.intp)
)
# If we add extra instance attributes, check whether they should be
# updated in .select_trains() below.
def __getitem__(self, item):
return MultimodKeyData(self, item)
def __contains__(self, item):
return all(item in self.data[s] for s in self.source_to_modno)
def masked_data(self, key=None, *, mask_bits=None, masked_value=np.nan):
"""Combine corrected data with the mask in the files
This provides an interface similar to ``det['data.adc']``, but masking
out pixels with the mask from the correction pipeline.
Parameters
----------
key: str
The data key to look at, by default the main data key of the detector
(e.g. 'data.adc').
mask_bits: int or list of ints
Reasons to exclude pixels, as a bitmask or a list of integers.
By default, all types of bad pixel are masked out. See the possible
values at: https://extra.readthedocs.io/en/latest/calibration/#extra.calibration.BadPixels
masked_value: int, float
The replacement value to use for masked data. By default this is NaN.
"""
key = key or self._main_data_key
if self._mask_data_key not in self:
raise RuntimeError(
f"This data doesn't include a mask ({self._mask_data_key}). "
f"You might be using raw instead of corrected data."
)
if isinstance(mask_bits, Iterable):
mask_bits = self._combine_bitfield(mask_bits)
return DetectorMaskedKeyData(
self, key, mask_key=self._mask_data_key,
mask_bits=mask_bits, masked_value=masked_value
)
@staticmethod
def _combine_bitfield(ints):
res = 0
for i in ints:
res |= i
return res
@classmethod
def _find_detector_names(cls, data):
# Find sources matching the pattern (raw or proc) for this detector type
raw_re = re.compile(f'(?P<detname>{cls._det_name_pat}){cls._source_raw_pat}')
corr_re = re.compile(f'(?P<detname>{cls._det_name_pat}){cls._source_corr_pat}')
detector_names = set()
for source in data.instrument_sources:
if m := raw_re.match(source) or corr_re.match(source):
detector_names.add(m['detname'])
return detector_names
@classmethod
def _find_detector_name(cls, data):
detector_names = cls._find_detector_names(data)
# We want exactly 1 source
if not detector_names:
raise SourceNameError(f'{cls._det_name_pat}({cls._source_raw_pat}|{cls._source_corr_pat})')
elif len(detector_names) > 1:
names_s = ', '.join(repr(n) for n in sorted(detector_names))
raise ValueError(
f"Multiple detectors found in the data: {names_s}. "
f"Pass detector_name to {cls.__name__}() to pick one."
)
return detector_names.pop()
@staticmethod
def _source_matches(data, pat):
source_re = re.compile(pat)
for source in data.instrument_sources:
m = source_re.match(source)
if m:
yield source, int(m.group('modno'))
@classmethod
def _data_is_raw(cls, data, source: str):
if '/CORR/' in source:
# Since 2026/1, corrected data always uses /CORR/ in its
# source names.
return False
# For most detectors, raw data is uint16 & corrected is float32.
# Overridden for AGIPD, where output dtype is configurable.
kd = data[source, cls._main_data_key]
return np.issubdtype(kd.dtype, np.integer)
@classmethod
def _identify_sources(cls, data, detector_name, modules=None, raw=None):
if raw is True:
pat = re.escape(detector_name) + cls._source_raw_pat
source_to_modno = dict(cls._source_matches(data, pat))
if not all(cls._data_is_raw(data, s) for s in source_to_modno):
# Older corrected data used the same names as raw
raise ValueError(
f"Raw data was not found: {detector_name}/DET/... sources "
f"are from corrected data"
)
else:
# Prefer corrected data
pat = re.escape(detector_name) + cls._source_corr_pat
source_to_modno = dict(cls._source_matches(data, pat))
if not source_to_modno:
# Data named like raw may also be proc
pat = re.escape(detector_name) + cls._source_raw_pat
source_to_modno = dict(cls._source_matches(data, pat))
if any(cls._data_is_raw(data, s) for s in source_to_modno):
if raw is False:
raise SourceNameError(f'{detector_name}/CORR/...')
warn(
'Falling back to raw data for backwards compatibility. '
'Please pass raw=False to make this warning into an '
'error, or raw=True if you intend to work with raw '
'detector data.',
stacklevel=3
)
# raw=None -> legacy behaviour: prefer corrected but allow raw
if modules is not None:
source_to_modno = {s: n for (s, n) in source_to_modno.items()
if n in modules}
if not source_to_modno:
dc = '(DET|CORR)' if raw is None else 'DET' if raw else 'CORR'
raise SourceNameError(f'{detector_name}/{dc}/...')
return source_to_modno
@classmethod
def _select_trains(cls, data, mod_data_counts, min_modules):
modules_present = (mod_data_counts > 0).sum(axis=1)
mod_data_counts = mod_data_counts[modules_present >= min_modules]
ntrains = len(mod_data_counts)
if not ntrains:
raise ValueError("No data found with >= {} modules present"
.format(min_modules))
log.info("Found %d trains with data for at least %d modules",
ntrains, min_modules)
train_ids = mod_data_counts.index.values
return data.select_trains(by_id[train_ids])
@staticmethod
def _split_align_chunk(chunk, target_train_ids: np.ndarray, length_limit=np.inf):
"""
Split up a source chunk to align with parts of a joined array.
Chunk points to contiguous source data, but if this misses a train,
it might not correspond to a contiguous region in the output. This
yields pairs of (target_slice, source_slice) describing chunks that can
be copied/mapped to a similar block in the output.
Parameters
----------
chunk: read_machinery::DataChunk
Reference to a contiguous chunk of data to be mapped.
target_train_ids: numpy.ndarray
Train ID index for target array to align chunk data to. Train IDs may
occur more than once in here.
length_limit: int
Maximum length of slices (stop - start) to yield. Larger slices will
be split up into several pieces. Unlimited by default.
"""
# Expand the list of train IDs to one per frame
chunk_tids = np.repeat(chunk.train_ids, chunk.counts.astype(np.intp))
chunk_match_start = int(chunk.first)
while chunk_tids.size > 0:
# Look up where the start of this chunk fits in the target
tgt_start = (target_train_ids == chunk_tids[0]).nonzero()[0][0]
target_tids = target_train_ids[
tgt_start : tgt_start + len(chunk_tids)
]
assert target_tids.shape == chunk_tids.shape, \
f"{target_tids.shape} != {chunk_tids.shape}"
assert target_tids[0] == chunk_tids[0], \
f"{target_tids[0]} != {chunk_tids[0]}"
# How much of this chunk can be mapped in one go?
mismatches = (chunk_tids != target_tids).nonzero()[0]
if mismatches.size > 0:
n_match = mismatches[0]
else:
n_match = len(chunk_tids)
# Split the matched data if needed for length_limit
n_batches = max(math.ceil(n_match / length_limit), 1)
for i in range(n_batches):
start = i * n_match // n_batches
stop = (i + 1) * n_match // n_batches
yield (slice(tgt_start + start, tgt_start + stop),
slice(chunk_match_start + start, chunk_match_start + stop))
# Prepare remaining data in the chunk for the next match
chunk_match_start += n_match
chunk_tids = chunk_tids[n_match:]
@property
def train_ids(self):
return self.data.train_ids
@property
def train_id_chunks(self):
# Used to be used internally. Kept temporarily in case anyone else used it.
warn(
"detector.train_id_chunks is likely to be removed in the future. "
"Please contact da-support@xfel.eu if you're using it",
stacklevel=2
)
train_id_arr = np.asarray(self.data.train_ids)
split_indices = np.where(np.diff(train_id_arr) != 1)[0] + 1
return np.split(train_id_arr, split_indices)
@property
def train_id_to_ix(self):
# Used to be used internally. Kept temporarily in case anyone else used it.
warn(
"detector.train_id_to_ix is likely to be removed in the future. "
"Please contact da-support@xfel.eu if you're using it",
stacklevel=2
)
# Cumulative sum gives the end of each train, subtract to get start
return self.frame_counts.cumsum() - self.frame_counts
@property
def frames_per_train(self):
counts = set(self.frame_counts.unique()) - {0}
if len(counts) > 1:
raise ValueError(f"Varying number of frames per train: {counts}")
return counts.pop() * self._frames_per_entry
def __repr__(self):
# Show raw/proc
det = type(self).__name__
raw = all(self._data_is_raw(self.data, s) for s in self.source_to_modno)
rp = 'raw' if raw else 'proc'
return (f"<{det}: Data interface for detector {self.detector_name!r} "
f"- {rp} data with {len(self.source_to_modno)} modules>")
def select_trains(self, trains):
"""Select a subset of trains from this data as a new object.
Slice trains by position within this data::
sel = det.select_trains(np.s_[:5])
Or select trains by train ID, with a slice or a list::
from extra_data import by_id
sel1 = det.select_trains(by_id[142844490 : 142844495])
sel2 = det.select_trains(by_id[[142844490, 142844493, 142844494]])
"""
# Using a copy to bypass the source & train checks in __init__
res = copy(self)
res.data = self.data.select_trains(trains)
res.frame_counts = self.frame_counts[res.data.train_ids]
res.train_ids_perframe = np.repeat(
res.frame_counts.index.values, res.frame_counts.values.astype(np.intp)
)
return res
def split_trains(self, parts=None, trains_per_part=None, frames_per_part=None):
"""Split this data into chunks with a fraction of the trains each.
At least one of *parts*, *trains_per_part* or *frames_per_part* must be
specified. You can pass any combination of these.
Parameters
----------
parts: int
How many parts to split the data into. If trains_per_part is also
specified, this is a minimum, and it may make more parts.
It may also make fewer if there are fewer trains in the data.
trains_per_part: int
A maximum number of trains in each part. Parts will often have
fewer trains than this.
frames_per_part: int
A target number of frames in each part. Each chunk should have up
to this many frames, but chunks always contain complete trains,
so if this is less than one train, you may get single train chunks
with more frames. When ``frames_per_part`` is used, the final
chunk may be much smaller than the others.
"""
if {parts, trains_per_part, frames_per_part} == {None}:
raise ValueError(
"One of parts, trains_per_part, frames_per_part must be specified"
)
if frames_per_part is None:
for s in split_trains(len(self.train_ids), parts, trains_per_part):
yield self.select_trains(s)
else:
# frames_per_part was specified. We don't assume that the number
# of frames per train is constant, so we'll iterate over trains
# and cut off each chunk when we reach the relevant number.
if not self.train_ids:
return # No data to split
if trains_per_part is None:
trains_per_part = np.inf
if parts:
trains_per_part = min(trains_per_part, len(self.train_ids) // parts)
chunk_start = 0
ntrains = 1
nentries = self.frame_counts.iloc[0]
for frame_ct in self.frame_counts.iloc[1:]:
ntrains += 1
nentries += frame_ct
if (ntrains > trains_per_part) or (nentries * self._frames_per_entry > frames_per_part):
# We've got a full chunk
chunk_end = chunk_start + ntrains - 1
yield self.select_trains(np.s_[chunk_start:chunk_end])
chunk_start = chunk_end
ntrains = 1
nentries = frame_ct
# There will always be at least the last train left to yield
yield self.select_trains(np.s_[chunk_start:])
def get_array(self, key, *, fill_value=None, roi=(), astype=None):
"""Get a labelled array of detector data
Parameters
----------
key: str
The data to get, e.g. 'image.data' for pixel values.
fill_value: int or float, optional
Value to use for missing values. If None (default) the fill value
is 0 for integers and np.nan for floats.
roi: tuple
Specify e.g. ``np.s_[10:60, 100:200]`` to select pixels within each
module when reading data. The selection is applied to each individual
module, so it may only be useful when working with a single module.
astype: Type
Data type of the output array. If None (default) the dtype matches the
input array dtype
"""
return self[key].xarray(fill_value=fill_value, roi=roi, astype=astype)
def get_dask_array(self, key, fill_value=None, astype=None):
"""Get a labelled Dask array of detector data
Parameters
----------
key: str
The data to get, e.g. 'image.data' for pixel values.
fill_value: int or float, optional
Value to use for missing values. If None (default) the fill value is 0
for integers and np.nan for floats.
astype: Type
Data type of the output array. If None (default) the dtype matches the
input array dtype
"""
return self[key].dask_array(labelled=True, fill_value=fill_value, astype=astype)
def trains(self, require_all=True):
"""Iterate over trains for detector data.
Parameters
----------
require_all: bool
If True (default), skip trains where any of the selected detector
modules are missing data.
Yields
------
train_data: dict
A dictionary mapping key names (e.g. ``image.data``) to labelled
arrays.
"""
return MPxDetectorTrainIterator(self, require_all=require_all)
def data_availability(self, module_gaps=False):
"""Get an array indicating what image data is available
Returns a boolean array (modules, entries), True where a module has data
for a given train, False for missing data.
"""
return self[self._main_data_key].data_availability(module_gaps)
class XtdfDetectorBase(MultimodDetectorBase):
"""Common machinery for a group of detectors with similar data format
AGIPD, DSSC & LPD all store pulse-resolved data in an "image" group,
with both trains and pulses along the first dimension. This allows a
different number of frames to be stored for each train, which makes
access more complicated.
"""
n_modules = 16
_main_data_key = 'image.data'
_mask_data_key = 'image.mask'
def __getitem__(self, item):
if item.startswith('image.'):
return XtdfImageMultimodKeyData(self, item)
return super().__getitem__(item)
def masked_data(self, key=None, *, mask_bits=None, masked_value=np.nan):
"""Combine corrected data with the mask in the files
This provides an interface similar to ``det['image.data']``, but masking
out pixels with the mask from the correction pipeline.
Parameters
----------
key: str
The data key to look at, by default the main data key of the detector
(e.g. 'image.data').
mask_bits: int or list of ints
Reasons to exclude pixels, as a bitmask or a list of integers.
By default, all types of bad pixel are masked out.
masked_value: int, float
The replacement value to use for masked data. By default this is NaN.
"""
key = key or self._main_data_key
assert key.startswith('image.')
if self._mask_data_key not in self:
raise RuntimeError(
f"This data doesn't include a mask ({self._mask_data_key}). "
f"You might be using raw instead of corrected data."
)
if isinstance(mask_bits, Iterable):
mask_bits = self._combine_bitfield(mask_bits)
return XtdfMaskedKeyData(
self, key, mask_key=self._mask_data_key,
mask_bits=mask_bits, masked_value=masked_value
)
# Several methods below are overridden in LPD1M for parallel gain mode
@staticmethod
def _select_pulse_indices(pulses, counts):
"""Select pulses by index across a chunk of trains
Returns a boolean array of frames to include.
"""
sel_frames = np.zeros(counts.sum(), dtype=np.bool_)
cursor = 0
for count in counts:
sel_in_train = pulses.value
if isinstance(sel_in_train, np.ndarray):
# Ignore any indices after the end of the train
sel_in_train = sel_in_train[sel_in_train < count]
sel_frames[cursor:cursor + count][sel_in_train] = 1
cursor += count
return sel_frames
def _make_image_index(self, tids, inner_ids, inner_name='pulse'):
"""
Prepare indices for data per inner coordinate.
Parameters
----------
tids: np.array
Train id repeated for each inner coordinate.
inner_ids: np.array
Array of inner coordinate values.
inner_name: string
Name of the inner coordinate.
Returns
-------
pd.MultiIndex
MultiIndex of 'train_ids' x 'inner_ids'.
"""
# Overridden in LPD1M for parallel gain mode
return pd.MultiIndex.from_arrays(
[tids, inner_ids], names=['train', inner_name]
)
def _read_inner_ids(self, field='pulseId'):
"""Read pulse/cell IDs into a 2D array (frames, modules)
Overridden by LPD1M for parallel gain mode.
"""
inner_ids = np.full((
self.frame_counts.sum(), self.n_modules), NO_PULSE_ID, dtype=np.uint64
)
for source, modno in self.source_to_modno.items():
for chunk in self.data._find_data_chunks(source, 'image.' + field):
dset = chunk.dataset
unwanted_dim = (dset.ndim > 1) and (dset.shape[1] == 1)
for tgt_slice, chunk_slice in self._split_align_chunk(
chunk, self.train_ids_perframe
):
# Select the matching data and add it to pulse_ids
# In some cases, there's an extra dimension of length 1.
matched = chunk.dataset[chunk_slice]
if unwanted_dim:
matched = matched[:, 0]
inner_ids[tgt_slice, modno] = matched
return inner_ids
def _collect_inner_ids(self, field='pulseId'):
"""
Gather pulse/cell ID labels for all modules and check consistency.
Raises
------
Exception:
Some data has no pulse ID values for any module.
Exception:
Inconsistent pulse IDs between detector modules.
Returns
-------
inner_ids: np.array
Array of pulse/cell IDs per frame common for all detector modules.
"""
inner_ids = self._read_inner_ids(field)
# Sanity checks on pulse IDs
inner_ids_min: np.ndarray = inner_ids.min(axis=1)
if (inner_ids_min == NO_PULSE_ID).any():
raise Exception(f"Failed to find {field} for some data")
inner_ids[inner_ids == NO_PULSE_ID] = 0
if (inner_ids_min != inner_ids.max(axis=1)).any():
raise Exception(f"Inconsistent {field} for different modules")
# Pulse IDs make sense. Drop the modules dimension, giving one
# pulse ID for each frame.
return inner_ids_min
def get_array(self, key, pulses=np.s_[:], unstack_pulses=True, *,
fill_value=None, subtrain_index='pulseId', roi=(),
astype=None):
"""Get a labelled array of detector data
Parameters
----------
key: str
The data to get, e.g. 'image.data' for pixel values.
pulses: slice, array, by_id or by_index
Select the pulses to include from each train. by_id selects by pulse
ID, by_index by index within the data being read. The default includes
all pulses. Only used for per-pulse data.
unstack_pulses: bool
Whether to separate train and pulse dimensions.
fill_value: int or float, optional
Value to use for missing values. If None (default) the fill value is 0
for integers and np.nan for floats.
subtrain_index: str
Specify 'pulseId' (default) or 'cellId' to label the frames recorded
within each train. Pulse ID should allow this data to be matched with
other devices, but depends on how the detector was manually configured
when the data was taken. Cell ID refers to the memory cell used for
that frame in the detector hardware.
roi: tuple
Specify e.g. ``np.s_[10:60, 100:200]`` to select pixels within each
module when reading data. The selection is applied to each individual
module, so it may only be useful when working with a single module.
For AGIPD raw data, each module records a frame as a 3D array with 2
entries on the first dimension, for data & gain information, so
``roi=np.s_[0]`` will select only the data part of each frame.
astype: Type
data type of the output array. If None (default) the dtype matches the
input array dtype
"""
if subtrain_index not in {'pulseId', 'cellId'}:
raise ValueError("subtrain_index must be 'pulseId' or 'cellId'")
if not isinstance(roi, tuple):
roi = (roi,)
if key.startswith('image.'):
return self[key].select_pulses(pulses).xarray(
fill_value=fill_value, roi=roi, subtrain_index=subtrain_index,
astype=astype, unstack_pulses=unstack_pulses,
)
else:
return super().get_array(
key, fill_value=fill_value, roi=roi, astype=astype
)
def get_dask_array(self, key, subtrain_index='pulseId', fill_value=None,
astype=None):
"""Get a labelled Dask array of detector data
Dask does lazy, parallelised computing, and can work with large data
volumes. This method doesn't immediately load the data: that only
happens once you trigger a computation.
Parameters
----------
key: str
The data to get, e.g. 'image.data' for pixel values.
subtrain_index: str, optional
Specify 'pulseId' (default) or 'cellId' to label the frames recorded
within each train. Pulse ID should allow this data to be matched with
other devices, but depends on how the detector was manually configured
when the data was taken. Cell ID refers to the memory cell used for
that frame in the detector hardware.
fill_value: int or float, optional
Value to use for missing values. If None (default) the fill value is 0
for integers and np.nan for floats.
astype: Type, optional
data type of the output array. If None (default) the dtype matches the
input array dtype
"""
from xarray import DataArray
if subtrain_index not in {'pulseId', 'cellId'}:
raise ValueError("subtrain_index must be 'pulseId' or 'cellId'")
if key.startswith('image.'):
arr = self[key].dask_array(
labelled=True, subtrain_index=subtrain_index,
fill_value=fill_value, astype=astype
)
# Preserve the quirks of this method before refactoring
if self[key]._extraneous_dim:
arr = arr.expand_dims('tmp_name', axis=2)
frame_idx = arr.indexes['train_pulse'].set_names(
['trainId', subtrain_index], level=[0, -1]
)
dims = ['module', 'train_pulse'] + [f'dim_{i}' for i in range(arr.ndim - 2)]
return DataArray(arr.data, dims=dims, coords={
'train_pulse': frame_idx, 'module': arr.indexes['module'],
})
else:
return super().get_dask_array(key, fill_value=fill_value, astype=astype)
def trains(self, pulses=np.s_[:], require_all=True):
"""Iterate over trains for detector data.
Parameters
----------
pulses: slice, array, by_index or by_id
Select which pulses to include for each train.
The default is to include all pulses.
require_all: bool
If True (default), skip trains where any of the selected detector
modules are missing data.
Yields
------
train_data: dict
A dictionary mapping key names (e.g. ``image.data``) to labelled
arrays.
"""
return MPxDetectorTrainIterator(self, pulses, require_all=require_all)
def write_virtual_cxi(self, filename, fillvalues=None):
"""Write a virtual CXI file to access the detector data.
The virtual datasets in the file provide a view of the detector
data as if it was a single huge array, but without copying the data.
Creating and using virtual datasets requires HDF5 1.10.
Parameters
----------
filename: str
The file to be written. Will be overwritten if it already exists.
fillvalues: dict, optional
keys are datasets names (one of: data, gain, mask) and associated
fill value for missing data (default is np.nan for float arrays and
zero for integer arrays)
"""
XtdfCXIWriter(self).write(filename, fillvalues=fillvalues)
def write_frames(self, filename, trains, pulses):
"""Write selected detector frames to a new EuXFEL HDF5 file
trains and pulses should be 1D arrays of the same length, containing
train IDs and pulse IDs (corresponding to the pulse IDs recorded by
the detector). i.e. (trains[i], pulses[i]) identifies one frame.
"""
if (trains.ndim != 1) or (pulses.ndim != 1):
raise ValueError("trains & pulses must be 1D arrays")
inc_tp_ids = zip_trains_pulses(trains, pulses)
writer = FramesFileWriter(filename, self.data, inc_tp_ids)
try:
writer.write()
finally:
writer.file.close()
def zip_trains_pulses(trains, pulses):
"""Combine two similar arrays of train & pulse IDs as one struct array
"""
if trains.shape != pulses.shape:
raise ValueError(
f"Train & pulse arrays don't match ({trains.shape} != {pulses.shape})"
)
res = np.zeros(trains.shape, dtype=np.dtype([
('trainId', np.uint64), ('pulseId', np.uint64)
]))
res['trainId'] = trains
res['pulseId'] = pulses
return res
class MultimodKeyData:
def __init__(self, det: MultimodDetectorBase, key):
self.det = det
self.key = key
self.modno_to_keydata = {
m: det.data[s, key] for (m, s) in det.modno_to_source.items()
}
def _init_kwargs(self): # Extended in subclasses
return dict(det=self.det, key=self.key)
@property
def train_ids(self):
return self.det.train_ids
def train_id_coordinates(self):
return np.array(self.det.train_ids)
@property
def modules(self):
return sorted(self.modno_to_keydata)
@property
def _eg_keydata(self):
return self.modno_to_keydata[min(self.modno_to_keydata)]
@property
def ndim(self):
return self._eg_keydata.ndim + 1
def buffer_shape(self, module_gaps=False, roi=()):
"""Get the array shape for this data
If *module_gaps* is True, include space for modules which are missing
from the data. *roi* may be a tuple of slices defining a region of
interest on the inner dimensions of the data.
"""
module_dim = self.det.n_modules if module_gaps else len(self.modno_to_keydata)
return ((module_dim, len(self.train_ids))
# Shape of 1 frame for 1 module with the ROI applied:
+ roi_shape(self._eg_keydata.entry_shape, roi))
@property
def shape(self):
return self.buffer_shape()
@property
def dimensions(self):
return ['module', 'trainId'] + ['dim_%d' % i for i in range(self.ndim - 2)]
@property
def dtype(self):
return self._eg_keydata.dtype
# For select_trains() & split_trains() to work correctly with subclasses
def _with_selected_det(self, det_selected):
kw = self._init_kwargs()
kw.update(det=det_selected)
return type(self)(**kw)
def select_trains(self, trains):
return self._with_selected_det(self.det.select_trains(trains))
def __getitem__(self, item):
return self.select_trains(item)
__iter__ = None # Disable iteration
def split_trains(self, parts=None, trains_per_part=None, frames_per_part=None):
for det_split in self.det.split_trains(parts, trains_per_part, frames_per_part):
yield self._with_selected_det(det_split)
def ndarray(self, *, fill_value=None, out=None, roi=(), astype=None, module_gaps=False):
"""Get data as a plain NumPy array with no labels"""
train_ids = np.asarray(self.det.train_ids)
out_shape = self.buffer_shape(module_gaps, roi)
if out is None:
dtype = self._eg_keydata.dtype if astype is None else np.dtype(astype)
out = _out_array(out_shape, dtype, fill_value=fill_value)
elif out.shape != out_shape:
raise ValueError(f'requires output array of shape {out_shape}')
for i, (modno, kd) in enumerate(sorted(self.modno_to_keydata.items())):
mod_ix = (modno - self.det._modnos_start_at) if module_gaps else i
for chunk in kd._data_chunks:
for tgt_slice, chunk_slice in self.det._split_align_chunk(chunk, train_ids):
chunk.dataset.read_direct(
out[mod_ix, tgt_slice], source_sel=(chunk_slice,) + roi
)
return out
def _wrap_xarray(self, arr):
from xarray import DataArray
coords = {'module': self.modules, 'trainId': self.train_id_coordinates()}
return DataArray(arr, dims=self.dimensions, coords=coords)
def xarray(self, *, fill_value=None, roi=(), astype=None):
arr = self.ndarray(fill_value=fill_value, roi=roi, astype=astype)
return self._wrap_xarray(arr)
def dask_array(self, *, labelled=False, fill_value=None, astype=None):
from dask.delayed import delayed
from dask.array import concatenate, from_delayed
entry_size = (self.dtype.itemsize *
len(self.modno_to_keydata) * np.prod(self._eg_keydata.entry_shape)
)
# Aim for 1GB chunks, with an arbitrary maximum of 256 trains
split = self.split_trains(frames_per_part=min(1024 ** 3 / entry_size, 256))