-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathreader.py
1528 lines (1235 loc) · 55.1 KB
/
reader.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
"""
Collection of classes and functions to help reading HDF5 file generated at
The European XFEL.
Copyright (c) 2017, European X-Ray Free-Electron Laser Facility GmbH
All rights reserved.
You should have received a copy of the 3-Clause BSD License along with this
program. If not, see <https://opensource.org/licenses/BSD-3-Clause>
"""
from collections import defaultdict
from collections.abc import Iterable
import datetime
import fnmatch
import h5py
from itertools import groupby
import logging
from multiprocessing import Pool
import numpy as np
from operator import index
import os
import os.path as osp
import re
import signal
import sys
import tempfile
import time
from typing import Tuple
from warnings import warn
from .exceptions import (
SourceNameError, PropertyNameError, TrainIDError, MultiRunError,
)
from .keydata import KeyData
from .read_machinery import (
DETECTOR_SOURCE_RE,
FilenameInfo,
by_id,
by_index,
select_train_ids,
split_trains,
find_proposal,
glob_wildcards_re,
)
from .run_files_map import RunFilesMap
from .sourcedata import SourceData
from . import locality, voview
from .file_access import FileAccess
from .utils import available_cpu_cores
__all__ = [
'H5File',
'RunDirectory',
'open_run',
'FileAccess',
'DataCollection',
'by_id',
'by_index',
'SourceNameError',
'PropertyNameError',
]
log = logging.getLogger(__name__)
RUN_DATA = 'RUN'
INDEX_DATA = 'INDEX'
METADATA = 'METADATA'
class DataCollection:
"""An assemblage of data generated at European XFEL
Data consists of *sources* which each have *keys*. It is further
organised by *trains*, which are identified by train IDs.
You normally get an instance of this class by calling :func:`H5File`
for a single file or :func:`RunDirectory` for a directory.
"""
def __init__(
self, files, sources_data=None, train_ids=None, ctx_closes=False, *,
inc_suspect_trains=True, is_single_run=False,
):
self.files = list(files)
self.ctx_closes = ctx_closes
self.inc_suspect_trains = inc_suspect_trains
self.is_single_run = is_single_run
if train_ids is None:
if inc_suspect_trains:
tid_sets = [f.train_ids for f in files]
else:
tid_sets = [f.valid_train_ids for f in files]
train_ids = sorted(set().union(*tid_sets))
self.train_ids = train_ids
if sources_data is None:
files_by_sources = defaultdict(list)
for f in self.files:
for source in f.control_sources:
files_by_sources[source, 'CONTROL'].append(f)
for source in f.instrument_sources:
files_by_sources[source, 'INSTRUMENT'].append(f)
sources_data = {
src: SourceData(src,
sel_keys=None,
train_ids=train_ids,
files=files,
section=section,
inc_suspect_trains=self.inc_suspect_trains,
)
for ((src, section), files) in files_by_sources.items()
}
self._sources_data = sources_data
# Throw an error if we have conflicting data for the same source
self._check_source_conflicts()
self.control_sources = frozenset({
name for (name, sd) in self._sources_data.items()
if sd.section == 'CONTROL'
})
self.instrument_sources = frozenset({
name for (name, sd) in self._sources_data.items()
if sd.section == 'INSTRUMENT'
})
@staticmethod
def _open_file(path, cache_info=None):
try:
fa = FileAccess(path, _cache_info=cache_info)
except Exception as e:
return osp.basename(path), str(e)
else:
return osp.basename(path), fa
@classmethod
def from_paths(
cls, paths, _files_map=None, *, inc_suspect_trains=True,
is_single_run=False, parallelize=True
):
files = []
uncached = []
def handle_open_file_attempt(fname, fa):
if isinstance(fa, FileAccess):
files.append(fa)
else:
print(f"Skipping file {fname}", file=sys.stderr)
print(f" (error was: {fa})", file=sys.stderr)
for path in paths:
cache_info = _files_map and _files_map.get(path)
if cache_info and ('flag' in cache_info):
filename, fa = cls._open_file(path, cache_info=cache_info)
handle_open_file_attempt(filename, fa)
else:
uncached.append(path)
if uncached:
def initializer():
# prevent child processes from receiving KeyboardInterrupt
signal.signal(signal.SIGINT, signal.SIG_IGN)
# Open the files either in parallel or serially
if parallelize:
nproc = min(available_cpu_cores(), len(uncached))
with Pool(processes=nproc, initializer=initializer) as pool:
for fname, fa in pool.imap_unordered(cls._open_file, uncached):
handle_open_file_attempt(fname, fa)
else:
for path in uncached:
handle_open_file_attempt(*cls._open_file(path))
if not files:
raise Exception("All HDF5 files specified are unusable")
return cls(
files, ctx_closes=True, inc_suspect_trains=inc_suspect_trains,
is_single_run=is_single_run,
)
@classmethod
def from_path(cls, path, *, inc_suspect_trains=True):
files = [FileAccess(path)]
return cls(
files, ctx_closes=True, inc_suspect_trains=inc_suspect_trains,
is_single_run=True
)
def __enter__(self):
if not self.ctx_closes:
raise Exception(
"Only DataCollection objects created by opening "
"files directly can be used in a 'with' statement, "
"not those created by selecting from or merging "
"others."
)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Close the files if this collection was created by opening them.
if self.ctx_closes:
for file in self.files:
file.close()
@property
def selection(self):
# This was previously a regular attribute, which code may have relied on.
return {src: srcdata.sel_keys for src, srcdata in self._sources_data.items()}
@property
def _source_index(self):
warn(
"DataCollection._source_index will be removed. "
"Contact [email protected] if you need to discuss alternatives.",
stacklevel=2
)
return {src: srcdata.files for src, srcdata in self._sources_data.items()}
@property
def all_sources(self):
return self.control_sources | self.instrument_sources
@property
def detector_sources(self):
return set(filter(DETECTOR_SOURCE_RE.match, self.instrument_sources))
def _check_field(self, source, key):
if source not in self.all_sources:
raise SourceNameError(source)
if key not in self[source]:
raise PropertyNameError(key, source)
def keys_for_source(self, source):
"""Get a set of key names for the given source
If you have used :meth:`select` to filter keys, only selected keys
are returned.
Only one file is used to find the keys. Within a run, all files should
have the same keys for a given source, but if you use :meth:`union` to
combine two runs where the source was configured differently, the
result can be unpredictable.
"""
return self._get_source_data(source).keys()
# Leave old name in case anything external was using it:
_keys_for_source = keys_for_source
def _get_key_data(self, source, key):
return self._get_source_data(source)[key]
def _get_source_data(self, source):
if source not in self._sources_data:
raise SourceNameError(source)
return self._sources_data[source]
def __getitem__(self, item):
if isinstance(item, tuple) and len(item) == 2:
return self._get_key_data(*item)
elif isinstance(item, str):
return self._get_source_data(item)
raise TypeError("Expected data[source, key]")
def get_entry_shape(self, source, key):
"""Get the shape of a single data entry for the given source & key"""
return self._get_key_data(source, key).entry_shape
def get_dtype(self, source, key):
"""Get the numpy data type for the given source & key"""
return self._get_key_data(source, key).dtype
def _check_data_missing(self, tid) -> bool:
"""Return True if a train does not have data for all sources"""
for source in self.control_sources:
file, _ = self._find_data(source, tid)
if file is None:
return True
for source in self.instrument_sources:
file, pos = self._find_data(source, tid)
if file is None:
return True
groups = {k.partition('.')[0] for k in self.keys_for_source(source)}
for group in groups:
_, counts = file.get_index(source, group)
if counts[pos] == 0:
return True
return False
def trains(self, devices=None, train_range=None, *, require_all=False,
flat_keys=False):
"""Iterate over all trains in the data and gather all sources.
::
run = Run('/path/to/my/run/r0123')
for train_id, data in run.select("*/DET/*", "image.data").trains():
mod0 = data["FXE_DET_LPD1M-1/DET/0CH0:xtdf"]["image.data"]
Parameters
----------
devices: dict or list, optional
Filter data by sources and keys.
Refer to :meth:`select` for how to use this.
train_range: by_id or by_index object, optional
Iterate over only selected trains, by train ID or by index.
Refer to :meth:`select_trains` for how to use this.
require_all: bool
False (default) returns any data available for the requested trains.
True skips trains which don't have all the selected data;
this only makes sense if you make a selection with *devices*
or :meth:`select`.
flat_keys: bool
False (default) returns nested dictionaries in each
iteration indexed by source and then key. True returns a
flat dictionary indexed by (source, key) tuples.
Yields
------
tid : int
The train ID of the returned train
data : dict
The data for this train, keyed by device name
"""
dc = self
if devices is not None:
dc = dc.select(devices)
if train_range is not None:
dc = dc.select_trains(train_range)
return iter(TrainIterator(dc, require_all=require_all,
flat_keys=flat_keys))
def train_from_id(self, train_id, devices=None, *, flat_keys=False):
"""Get train data for specified train ID.
Parameters
----------
train_id: int
The train ID
devices: dict or list, optional
Filter data by sources and keys.
Refer to :meth:`select` for how to use this.
flat_keys: bool
False (default) returns a nested dict indexed by source and then key.
True returns a flat dictionary indexed by (source, key) tuples.
Returns
-------
tid : int
The train ID of the returned train
data : dict
The data for this train, keyed by device name
Raises
------
KeyError
if `train_id` is not found in the run.
"""
if train_id not in self.train_ids:
raise TrainIDError(train_id)
if devices is not None:
return self.select(devices).train_from_id(train_id)
res = {}
for source in self.control_sources:
source_data = res[source] = {
'metadata': {'source': source, 'timestamp.tid': train_id}
}
file, pos = self._find_data(source, train_id)
if file is None:
continue
for key in self.keys_for_source(source):
path = '/CONTROL/{}/{}'.format(source, key.replace('.', '/'))
source_data[key] = file.file[path][pos]
for source in self.instrument_sources:
source_data = res[source] = {
'metadata': {'source': source, 'timestamp.tid': train_id}
}
file, pos = self._find_data(source, train_id)
if file is None:
continue
for key in self.keys_for_source(source):
group = key.partition('.')[0]
firsts, counts = file.get_index(source, group)
first, count = firsts[pos], counts[pos]
if not count:
continue
path = '/INSTRUMENT/{}/{}'.format(source, key.replace('.', '/'))
if count == 1:
source_data[key] = file.file[path][first]
else:
source_data[key] = file.file[path][first : first + count]
if flat_keys:
# {src: {key: data}} -> {(src, key): data}
res = {(src, key): v for src, source_data in res.items()
for (key, v) in source_data.items()}
return train_id, res
def train_from_index(self, train_index, devices=None, *, flat_keys=False):
"""Get train data of the nth train in this data.
Parameters
----------
train_index: int
Index of the train in the file.
devices: dict or list, optional
Filter data by sources and keys.
Refer to :meth:`select` for how to use this.
flat_keys: bool
False (default) returns a nested dict indexed by source and then key.
True returns a flat dictionary indexed by (source, key) tuples.
Returns
-------
tid : int
The train ID of the returned train
data : dict
The data for this train, keyed by device name
"""
train_id = self.train_ids[train_index]
return self.train_from_id(int(train_id), devices=devices, flat_keys=flat_keys)
def get_data_counts(self, source, key):
"""Get a count of data points in each train for the given data field.
Returns a pandas series with an index of train IDs.
Parameters
----------
source: str
Source name, e.g. "SPB_DET_AGIPD1M-1/DET/7CH0:xtdf"
key: str
Key of parameter within that device, e.g. "image.data".
"""
return self._get_key_data(source, key).data_counts()
def get_series(self, source, key):
"""Return a pandas Series for a 1D data field defined by source & key.
See :meth:`.KeyData.series` for details.
"""
return self._get_key_data(source, key).series()
def get_dataframe(self, fields=None, *, timestamps=False):
"""Return a pandas dataframe for given data fields.
::
df = run.get_dataframe(fields=[
("*_XGM/*", "*.i[xy]Pos"),
("*_XGM/*", "*.photonFlux")
])
This links together multiple 1-dimensional datasets as columns in a
table.
Parameters
----------
fields : dict or list, optional
Select data sources and keys to include in the dataframe.
Selections are defined by lists or dicts as in :meth:`select`.
timestamps : bool
If false (the default), exclude the timestamps associated with each
control data field.
"""
import pandas as pd
if fields is not None:
return self.select(fields).get_dataframe(timestamps=timestamps)
series = []
for source in self.all_sources:
for key in self.keys_for_source(source):
if (not timestamps) and key.endswith('.timestamp'):
continue
series.append(self.get_series(source, key))
return pd.concat(series, axis=1)
def get_array(self, source, key, extra_dims=None, roi=(), name=None):
"""Return a labelled array for a data field defined by source and key.
see :meth:`.KeyData.xarray` for details.
"""
if isinstance(roi, by_index):
roi = roi.value
return self._get_key_data(source, key).xarray(
extra_dims=extra_dims, roi=roi, name=name)
def get_dask_array(self, source, key, labelled=False):
"""Get a Dask array for a data field defined by source and key.
see :meth:`.KeyData.dask_array` for details.
"""
return self._get_key_data(source, key).dask_array(labelled=labelled)
def get_run_value(self, source, key):
"""Get a single value from the RUN section of data files.
RUN records each property of control devices as a snapshot at the
beginning of the run. This includes properties which are not saved
continuously in CONTROL data.
This method is intended for use with data from a single run. If you
combine data from multiple runs, it will raise MultiRunError.
Parameters
----------
source: str
Control device name, e.g. "HED_OPT_PAM/CAM/SAMPLE_CAM_4".
key: str
Key of parameter within that device, e.g. "triggerMode".
"""
if not self.is_single_run:
raise MultiRunError
if source not in self.control_sources:
raise SourceNameError(source)
# Arbitrary file - should be the same across a run
fa = self._sources_data[source].files[0]
ds = fa.file['RUN'][source].get(key.replace('.', '/'))
if isinstance(ds, h5py.Group):
# Allow for the .value suffix being omitted
ds = ds.get('value')
if not isinstance(ds, h5py.Dataset):
raise PropertyNameError(key, source)
val = ds[0]
if isinstance(val, bytes): # bytes -> str
return val.decode('utf-8', 'surrogateescape')
return val
def get_run_values(self, source) -> dict:
"""Get a dict of all RUN values for the given source
This includes keys which are also in CONTROL.
Parameters
----------
source: str
Control device name, e.g. "HED_OPT_PAM/CAM/SAMPLE_CAM_4".
"""
if not self.is_single_run:
raise MultiRunError
if source not in self.control_sources:
raise SourceNameError(source)
# Arbitrary file - should be the same across a run
fa = self._sources_data[source].files[0]
res = {}
def visitor(path, obj):
if isinstance(obj, h5py.Dataset):
val = obj[0]
if isinstance(val, bytes):
val = val.decode('utf-8', 'surrogateescape')
res[path.replace('/', '.')] = val
fa.file['RUN'][source].visititems(visitor)
return res
def union(self, *others):
"""Join the data in this collection with one or more others.
This can be used to join multiple sources for the same trains,
or to extend the same sources with data for further trains.
The order of the datasets doesn't matter.
Returns a new :class:`DataCollection` object.
"""
sources_data_multi = defaultdict(list)
# DataCollection union of format version = 0.5 (no run/proposal # in
# files) is not considered a single run.
proposal_nos = set()
run_nos = set()
for dc in (self,) + others:
md = dc.run_metadata() if dc.is_single_run else {}
proposal_nos.add(md.get("proposalNumber", -1))
run_nos.add(md.get("runNumber", -1))
for source, srcdata in dc._sources_data.items():
sources_data_multi[source].append(srcdata)
sources_data = {src: src_datas[0].union(*src_datas[1:])
for src, src_datas in sources_data_multi.items()}
same_run = (
len(proposal_nos) == 1 and (-1 not in proposal_nos)
and len(run_nos) == 1 and (-1 not in run_nos)
)
train_ids = sorted(set().union(*[sd.train_ids for sd in sources_data.values()]))
files = set().union(*[sd.files for sd in sources_data.values()])
return DataCollection(
files, sources_data=sources_data, train_ids=train_ids,
inc_suspect_trains=self.inc_suspect_trains,
is_single_run=same_run,
)
def _expand_selection(self, selection):
if isinstance(selection, dict):
# {source: {key1, key2}}
# {source: set()} or {source: None} -> all keys for this source
res = {}
for source, in_keys in selection.items():
if source not in self.all_sources:
raise SourceNameError(source)
# Empty dict was accidentally allowed and tested; keep it
# working just in case.
if in_keys == {}:
in_keys = set()
if in_keys is not None and not isinstance(in_keys, set):
raise TypeError(
f"keys in selection dict should be a set or None (got "
f"{in_keys!r})"
)
res[source] = self._sources_data[source].select_keys(in_keys)
return res
elif isinstance(selection, Iterable):
# selection = [('src_glob', 'key_glob'), ...]
sources_data_multi = defaultdict(list)
for (src_glob, key_glob) in selection:
for source, keys in self._select_glob(src_glob, key_glob).items():
sources_data_multi[source].append(
self._sources_data[source].select_keys(keys)
)
return {src: src_datas[0].union(*src_datas[1:])
for src, src_datas in sources_data_multi.items()}
elif isinstance(selection, DataCollection):
return self._expand_selection(selection.selection)
elif isinstance(selection, KeyData):
src = selection.source
return {src: self._sources_data[src].select_keys({selection.key})}
else:
raise TypeError("Unknown selection type: {}".format(type(selection)))
def _select_glob(self, source_glob, key_glob):
source_re = re.compile(fnmatch.translate(source_glob))
key_re = re.compile(fnmatch.translate(key_glob))
if key_glob.endswith(('.value', '*')):
ctrl_key_glob = key_glob
ctrl_key_re = key_re
else:
# Add .value suffix for keys of CONTROL sources
ctrl_key_glob = key_glob + '.value'
ctrl_key_re = re.compile(fnmatch.translate(ctrl_key_glob))
matched = {}
for source in self.all_sources:
if not source_re.match(source):
continue
if key_glob == '*':
# When the selection refers to all keys, make sure this
# is restricted to the current selection of keys for
# this source.
if self.selection[source] is None:
matched[source] = None
else:
matched[source] = self.selection[source]
elif glob_wildcards_re.search(key_glob) is None:
# Selecting a single key (no wildcards in pattern)
# This check should be faster than scanning all keys:
k = ctrl_key_glob if source in self.control_sources else key_glob
if k in self._sources_data[source]:
matched[source] = {k}
else:
r = ctrl_key_re if source in self.control_sources else key_re
keys = set(filter(r.match, self.keys_for_source(source)))
if keys:
matched[source] = keys
if not matched:
raise ValueError("No matches for pattern {}"
.format((source_glob, key_glob)))
return matched
def select(self, seln_or_source_glob, key_glob='*', require_all=False):
"""Select a subset of sources and keys from this data.
There are four possible ways to select data:
1. With two glob patterns (see below) for source and key names::
# Select data in the image group for any detector sources
sel = run.select('*/DET/*', 'image.*')
2. With an iterable of (source, key) glob patterns::
# Select image.data and image.mask for any detector sources
sel = run.select([('*/DET/*', 'image.data'), ('*/DET/*', 'image.mask')])
Data is included if it matches any of the pattern pairs.
3. With a dict of source names mapped to sets of key names
(or empty sets to get all keys)::
# Select image.data from one detector source, and all data from one XGM
sel = run.select({'SPB_DET_AGIPD1M-1/DET/0CH0:xtdf': {'image.data'},
'SA1_XTD2_XGM/XGM/DOOCS': set()})
Unlike the others, this option *doesn't* allow glob patterns.
It's a more precise but less convenient option for code that knows
exactly what sources and keys it needs.
4. With an existing DataCollection or KeyData object::
# Select the same data contained in another DataCollection
prev_run.select(sel)
The optional `require_all` argument restricts the trains to those for
which all selected sources and keys have at least one data entry. By
default, all trains remain selected.
Returns a new :class:`DataCollection` object for the selected data.
.. note::
'Glob' patterns may be familiar from selecting files in a Unix shell.
``*`` matches anything, so ``*/DET/*`` selects sources with "/DET/"
anywhere in the name. There are several kinds of wildcard:
- ``*``: anything
- ``?``: any single character
- ``[xyz]``: one character, "x", "y" or "z"
- ``[0-9]``: one digit character
- ``[!xyz]``: one character, *not* x, y or z
Anything else in the pattern must match exactly. It's case-sensitive,
so "x" does not match "X".
"""
if isinstance(seln_or_source_glob, str):
seln_or_source_glob = [(seln_or_source_glob, key_glob)]
sources_data = self._expand_selection(seln_or_source_glob)
if require_all:
# Select only those trains for which all selected sources
# and keys have data, i.e. have a count > 0 in their
# respective INDEX section.
train_ids = self.train_ids
for source, srcdata in sources_data.items():
for group in srcdata._index_group_names():
# Empty list would be converted to np.float64 array.
source_tids = np.empty(0, dtype=np.uint64)
for f in self._sources_data[source].files:
valid = True if self.inc_suspect_trains else f.validity_flag
# Add the trains with data in each file.
_, counts = f.get_index(source, group)
source_tids = np.union1d(
f.train_ids[valid & (counts > 0)], source_tids
)
# Remove any trains previously selected, for which this
# selected source and key group has no data.
train_ids = np.intersect1d(train_ids, source_tids)
sources_data = {
src: srcdata._only_tids(train_ids)
for src, srcdata in sources_data.items()
}
train_ids = list(train_ids) # Convert back to a list.
else:
train_ids = self.train_ids
files = set().union(*[sd.files for sd in sources_data.values()])
return DataCollection(
files, sources_data, train_ids=train_ids,
inc_suspect_trains=self.inc_suspect_trains,
is_single_run=self.is_single_run
)
def deselect(self, seln_or_source_glob, key_glob='*'):
"""Select everything except the specified sources and keys.
This takes the same arguments as :meth:`select`, but the sources and
keys you specify are dropped from the selection.
Returns a new :class:`DataCollection` object for the remaining data.
"""
if isinstance(seln_or_source_glob, str):
seln_or_source_glob = [(seln_or_source_glob, key_glob)]
deselection = self._expand_selection(seln_or_source_glob)
# Subtract deselection from selection on self
sources_data = {}
for source, srcdata in self._sources_data.items():
if source not in deselection:
sources_data[source] = srcdata
continue
desel_keys = deselection[source].sel_keys
if desel_keys is None:
continue # Drop the entire source
remaining_keys = srcdata.keys() - desel_keys
if remaining_keys:
sources_data[source] = srcdata.select_keys(remaining_keys)
files = set().union(*[sd.files for sd in sources_data.values()])
return DataCollection(
files, sources_data=sources_data, train_ids=self.train_ids,
inc_suspect_trains=self.inc_suspect_trains,
is_single_run=self.is_single_run,
)
def select_trains(self, train_range):
"""Select a subset of trains from this data.
Choose a slice of trains by train ID::
from extra_data import by_id
sel = run.select_trains(by_id[142844490:142844495])
Or select a list of trains::
sel = run.select_trains(by_id[[142844490, 142844493, 142844494]])
Or select trains by index within this collection::
sel = run.select_trains(np.s_[:5])
Returns a new :class:`DataCollection` object for the selected trains.
Raises
------
ValueError
If given train IDs do not overlap with the trains in this data.
"""
new_train_ids = select_train_ids(self.train_ids, train_range)
sources_data = {
src: srcdata._only_tids(new_train_ids)
for src, srcdata in self._sources_data.items()
}
files = set().union(*[sd.files for sd in sources_data.values()])
return DataCollection(
files, sources_data=sources_data, train_ids=new_train_ids,
inc_suspect_trains=self.inc_suspect_trains,
is_single_run=self.is_single_run,
)
def split_trains(self, parts=None, trains_per_part=None):
"""Split this data into chunks with a fraction of the trains each.
Either *parts* or *trains_per_part* must be specified.
This returns an iterator yielding new :class:`DataCollection` objects.
The parts will have similar sizes, e.g. splitting 11 trains
with ``trains_per_part=8`` will produce 5 & 6 trains, not 8 & 3.
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.
"""
for s in split_trains(len(self.train_ids), parts, trains_per_part):
yield self.select_trains(s)
def _check_source_conflicts(self):
"""Check for data with the same source and train ID in different files.
"""
sources_with_conflicts = set()
files_conflict_cache = {}
def files_have_conflict(files):
fset = frozenset({f.filename for f in files})
if fset not in files_conflict_cache:
if self.inc_suspect_trains:
tids = np.concatenate([f.train_ids for f in files])
else:
tids = np.concatenate([f.valid_train_ids for f in files])
files_conflict_cache[fset] = len(np.unique(tids)) != len(tids)
return files_conflict_cache[fset]
for source, srcdata in self._sources_data.items():
if files_have_conflict(srcdata.files):
sources_with_conflicts.add(source)
if sources_with_conflicts:
raise ValueError("{} sources have conflicting data "
"(same train ID in different files): {}".format(
len(sources_with_conflicts), ", ".join(sources_with_conflicts)
))
def _expand_trainids(self, counts, trainIds):
n = min(len(counts), len(trainIds))
return np.repeat(trainIds[:n], counts.astype(np.intp)[:n])
def _find_data_chunks(self, source, key):
"""Find contiguous chunks of data for the given source & key
Yields DataChunk objects.
"""
return self._get_key_data(source, key)._data_chunks
def _find_data(self, source, train_id) -> Tuple[FileAccess, int]:
for f in self._sources_data[source].files:
ixs = (f.train_ids == train_id).nonzero()[0]
if self.inc_suspect_trains and ixs.size > 0:
return f, ixs[0]
for ix in ixs:
if f.validity_flag[ix]:
return f, ix
return None, None
def __repr__(self):
return f"<extra_data.DataCollection for {len(self.all_sources)} " \
f"sources and {len(self.train_ids)} trains>"
def info(self, details_for_sources=()):
"""Show information about the selected data.
"""
details_sources_re = [re.compile(fnmatch.translate(p))
for p in details_for_sources]
# time info
train_count = len(self.train_ids)
if train_count == 0:
first_train = last_train = '-'
span_txt = '0.0'
else:
first_train = self.train_ids[0]
last_train = self.train_ids[-1]
seconds, deciseconds = divmod((last_train - first_train + 1), 10)
span_txt = '{}.{}'.format(datetime.timedelta(seconds=seconds),
int(deciseconds))
detector_modules = {}
for source in self.detector_sources:
name, modno = DETECTOR_SOURCE_RE.match(source).groups((1, 2))
detector_modules[(name, modno)] = source
# A run should only have one detector, but if that changes, don't hide it
detector_name = ','.join(sorted(set(k[0] for k in detector_modules)))
# disp
print('# of trains: ', train_count)
print('Duration: ', span_txt)
print('First train ID:', first_train)
print('Last train ID: ', last_train)
print()
print("{} detector modules ({})".format(
len(self.detector_sources), detector_name
))
if len(detector_modules) > 0: