-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcompaso_halo_catalog.py
1744 lines (1418 loc) · 79.4 KB
/
compaso_halo_catalog.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
"""
The ``compaso_halo_catalog`` module loads halo catalogs from CompaSO, Abacus's
on-the-fly halo finder. The module defines one class, ``CompaSOHaloCatalog``,
whose constructor takes the path to a halo catalog as an argument.
Users should use this class as the primary interface to load
and manipulate halo catalogs.
The halo catalogs and particle subsamples are stored on disk in
ASDF files and are loaded into memory as Astropy tables. Each
column of an Astropy table is essentially a Numpy array and can
be accessed with familiar Numpy-like syntax. More on Astropy
tables here: http://docs.astropy.org/en/stable/table/
Beyond just loading the halo catalog files into memory, this
module performs a few other manipulations. Many of the halo
catalog columns are stored in bit-packed formats (e.g.
floats are scaled to a ratio from 0 to 1 then packed in 16-bit
ints), so these columns are unpacked as they are loaded.
Furthermore, the halo catalogs for big simulations are divided
across a few dozen files. These files are transparently loaded
into one monolithic Astropy table if one passes a directory
to ``CompaSOHaloCatalog``; to save memory by loading only one file,
pass just that file as the argument to ``CompaSOHaloCatalog``.
Importantly, because ASDF and Astropy tables are both column-
oriented, it can be much faster to load only the subset of
halo catalog columns that one needs, rather than all 60-odd
columns. Use the ``fields`` argument to the ``CompaSOHaloCatalog``
constructor to specify a subset of fields to load. Similarly, the
particles can be quite large, and one can use the ``subsamples``
argument to restrict the particles to the subset one needs.
Some brief examples and technical details about the halo catalog
layout are presented below, followed by the full module API.
Examples of using this module to work with AbacusSummit data can
be found on the AbacusSummit website here:
https://abacussummit.readthedocs.io
Short Example
=============
>>> from abacusnbody.data.compaso_halo_catalog import CompaSOHaloCatalog
>>> # Load the RVs and PIDs for particle subsample A
>>> cat = CompaSOHaloCatalog('/storage/AbacusSummit/AbacusSummit_base_c000_ph000/halos/z0.100', subsamples=dict(A=True,pos=True))
>>> print(cat.halos[:5]) # cat.halos is an Astropy Table, print the first 5 rows
id npstartA npstartB ... sigmavrad_L2com sigmavtan_L2com rvcirc_max_L2com
-------- -------- -------- ... --------------- --------------- ----------------
25000000 0 2 ... 0.9473971 0.96568024 0.042019103
25000001 11 12 ... 0.86480814 0.8435805 0.046611086
48000000 18 15 ... 0.66734606 0.68342227 0.033434115
58000000 31 18 ... 0.52170926 0.5387341 0.042292822
58001000 38 23 ... 0.4689916 0.40759262 0.034498636
>>> print(cat.halos['N','x_com'][:5]) # print the position and mass of the first 5 halos
N x_com [3]
--- ------------------------
278 -998.88525 .. -972.95404
45 -998.9751 .. -972.88416
101 -999.7485 .. -947.8377
82 -998.904 .. -937.6313
43 -999.3252 .. -937.5813
>>> # Examine the particle subsamples associated with the 5th halo
>>> h5 = cat.halos[4]
>>> print(cat.subsamples['pos'][h5['npstartA']:h5['npstartA'] + h5['npoutA']])
pos [3]
------------------------
-999.3019 .. -937.5229
-999.33435 .. -937.5515
-999.38965 .. -937.58777
>>> # At a glance, the pos fields match that of the 5th halo above, so it appears we have indexed correctly!
Catalog Structure
=================
The catalogs are stored in a directory structure that looks like:
.. code-block:: none
- SimulationName/
- halos/
- z0.100/
- halo_info/
halo_info_000.asdf
halo_info_001.asdf
...
- halo_rv_A/
halo_rv_A_000.asdf
halo_rv_A_001.asdf
...
- <field & halo, rv & PID, subsample A & B directories>
- <other redshift directories, some with particle subsamples, others without>
The file numbering roughly corresponds to a planar chunk of the simulation
(all y and z for some range of x). The matching of the halo_info file numbering
to the particle file numbering is important; halo_info files index into the
corresponding particle files.
The halo catalogs are stored on disk in ASDF files (https://asdf.readthedocs.io/).
The ASDF files start with a human-readable header that describes
the data present in the file and metadata about the simulation
from which it came (redshift, cosmology, etc). The rest of
the file is binary blobs, each representing a column (i.e.
a halo property).
Internally, the ASDF binary portions are usually compressed. This should
be transparent to users, although you may be prompted to install the
blosc package if it is not present. Decompression should be fast,
at least 500 MB/s per core.
Particle Subsamples
===================
We define two disjoint sets of "subsample" particles, called "subsample A" and
"subsample B". Subsample A is a few percent of all particles, with subsample B
a few times larger than that. Particles membership in each group is a function
of PID and is thus consistent across redshift.
At most redshifts, we only output halo catalogs and halo subsample particle PIDs.
This aids with construction of merger trees. At a few redshifts, we provide
subsample particle positions as well as PIDs, for both halo particles and
non-halo particles, called "field" particles. Only halo particles (specifically,
:doc:`L1 particles<summit:compaso>`) may be loaded through this module; field
particles and L0 halo particles can be loaded by reading the particle files
directly with :ref:`abacusnbody.data:read_abacus module`.
Use the ``subsamples`` argument to the constructor to specify loading
subsample A and/or B, and which fields---pos, vel, pid---to load. Note that
if only one of pos & vel is specified, the IO amount is the same, because
the pos & vel are packed together in :ref:`RVint format<compaso:Bit-packed Formats>`.
But the memory usage and time to unpack will be lower.
Halo File Types
===============
Each file type (for halos, particles, etc) is grouped into a subdirectory.
These subdirectories are:
- ``halo_info/``
The primary halo catalog files. Contains stats like
CoM positions and velocities and moments of the particles.
Also indicates the index and count of subsampled particles in the
``halo_pid_A/B`` and ``halo_rv_A/B`` files.
- ``halo_pid_A/`` and ``halo_pid_B/``
The 64-bit particle IDs of particle subsamples A and B. The PIDs
contain information about the Lagrangian position of the particles,
whether they are tagged, and their local density.
The following subdirectories are only present for the redshifts for which
we output particle subsamples and not just halo catalogs:
- ``halo_rv_A/`` and ``halo_rv_B/``
The positions and velocities of the halo subsample particles, in "RVint"
format. The halo associations are recoverable with the indices in the
``halo_info`` files.
- ``field_rv_A/`` and ``field_rv_B/``
Same as ``halo_rv_<A|B>/``, but only for the field (non-halo) particles.
- ``field_pid_A/`` and ``field_pid_B/``
Same as ``halo_pid_<A|B>/``, but only for the field (non-halo) particles.
Bit-packed Formats
==================
The "RVint" format packs six fields (x,y,z, and vx,vy,vz) into three ints (12 bytes).
Positions are stored to 20 bits (global), and velocities 12 bits (max 6000 km/s).
The PIDs are 8 bytes and encode a local density estimate, tag bits for merger trees,
and a unique particle id, the last of which encodes the Lagrangian particle coordinate.
These are described in more detail on the :doc:`AbacusSummit Data Model page <summit:data-products>`.
Use the ``unpack_bits`` argument of the ``CompaSOHaloCatalog`` constructor to specify
which PID bit fields you want unpacked. Be aware that some of them might use a lot of
memory; e.g. the Lagrangian positions are three 4-byte floats per subsample particle.
Also be aware that some of the returned arrays use narrow int dtypes to save memory,
such as the ``lagr_idx`` field using ``int16``. It is easy to silently overflow such
narrow int types; make sure your operations stay within the type width and cast
if necessary.
Field Subset Loading
====================
Because the ASDF files are column-oriented, it is possible to load just one or a few
columns (halo catalog fields) rather than the whole file. This can save huge amounts
of IO, memory, and CPU time (the latter due to the decompression). Use the ``fields`` argument
to the ``CompaSOHaloCatalog`` constructor to specify the list of columns you want.
In detail, some columns are stored as ratios to other columns. For example, ``r90``
is stored as a ratio relative to ``r100``. So to properly unpack
``r90``, the ``r100`` column must also be read. ``CompaSOHaloCatalog`` knows about
these dependencies and will load the minimum set necessary to return the requested
columns to the user. However, this may result in more IO than expected. The ``verbose``
constructor flag or the ``dependency_info`` field of the ``CompaSOHaloCatalog``
object may be useful for diagnosing exactly what data is being loaded.
Despite the potential extra IO and CPU time, the extra memory usage is granular
at the level of individual files. In other words, when loading multiple files,
the concatenated array will never be constructed for columns that only exist for
dependency purposes.
Superslab (Chunk) Processing
============================
The halo catalogs are divided across multiple files, called "superslabs", which are
typically planar chunks of the simulation volume (all y,z for some range of x, with
a bit of overlap at the boundaries). Applications that can process the volume
superslab-by-superslab can save a substantial amount of memory compared to loading
the full volume. To load a single superslab, pass the corresponding ``halo_info_XXX.asdf``
file as the ``path`` argument:
.. code-block:: python
cat = CompaSOHaloCatalog('AbacusSummit_base_c000_ph000/halos/z0.100/halo_info/halo_info_000.asdf')
If your application needs one slab of padding, you can pass a list of files and proceed in a
rolling fashion:
.. code-block:: python
cat = CompaSOHaloCatalog(['AbacusSummit_base_c000_ph000/halos/z0.100/halo_info/halo_info_033.asdf',
'AbacusSummit_base_c000_ph000/halos/z0.100/halo_info/halo_info_000.asdf',
'AbacusSummit_base_c000_ph000/halos/z0.100/halo_info/halo_info_001.asdf'])
Superslab Filtering
===================
Another way to save memory is to use the ``filter_func`` argument. This function
will be called for each superslab, and must return a mask representing the rows
to keep. For example, to drop all halos with less than 100 particles, use:
.. code-block:: python
cat = CompaSOHaloCatalog(..., filter_func=lambda h: h['N'] >= 100)
Because this mask is applied on each superslab immediately after loading,
the full, unfiltered table is never constructed, thus saving memory.
The filtering adds some CPU time, but in many cases loading catalogs is
IO limited, so this won't add much overhead.
Multi-threaded Decompression
============================
The Blosc compression we use inside the ASDF files supports multi-threaded
decompression. We have packed AbacusSummit files with 4 Blosc blocks (each ~few MB)
per ASDF block, so 4 Blosc threads is probably the optimal value. This is the
default value, unless fewer cores are available (as determined by the process
affinity mask).
.. note::
Loading a CompaSOHaloCatalog will use 4 decompression threads by default.
You can control the number of decompression threads with:
.. code-block:: python
import abacusnbody.data.asdf
abacusnbody.data.asdf.set_nthreads(N)
"""
from glob import glob
import os
import os.path
from pathlib import PurePath
from os.path import join as pjoin, dirname, basename, isdir, isfile, normpath, abspath, samefile
import re
import gc
import warnings
from time import perf_counter as timer
from collections import defaultdict
# Stop astropy from trying to download time data; nodes on some clusters are not allowed to access the internet directly
from astropy.utils import iers
iers.conf.auto_download = False
import numpy as np
import numba as nb
import astropy.table
from astropy.table import Table
import asdf
import asdf.compression
try:
asdf.compression.validate('blsc')
except Exception as e:
raise Exception("Abacus ASDF extension not properly loaded! Try reinstalling abacusutils, or updating ASDF: `pip install asdf>=2.8`") from e
from . import bitpacked
# Default to 4 decompression threads, or fewer if fewer cores are available
DEFAULT_BLOSC_THREADS = 4
DEFAULT_BLOSC_THREADS = max(1, min(len(os.sched_getaffinity(0)), DEFAULT_BLOSC_THREADS))
from . import asdf as _asdf
_asdf.set_nthreads(DEFAULT_BLOSC_THREADS)
class CompaSOHaloCatalog:
"""
A halo catalog from Abacus's on-the-fly group finder.
"""
# TODO: optional progress meter for loading files
# TODO: generator mode over superslabs
def __init__(self, path, cleaned=True, subsamples=False, convert_units=True, unpack_bits=False,
fields='DEFAULT_FIELDS', verbose=False, cleandir=None,
filter_func=None, halo_lc=None,
**kwargs):
"""
Loads halos. The ``halos`` field of this object will contain
the halo records; and the ``subsamples`` field will contain
the corresponding halo/field subsample positions and velocities and their
ids (if requested via ``subsamples``). The ``header`` field contains
metadata about the simulation.
Whether a particle is tagged or not is returned when loading the
halo and field pids, as it is encoded for each in the 64-bit PID.
The local density of the particle is also encoded in the PIDs
and returned upon loading those.
Parameters
----------
path: path-like or list of path-like
The halo catalog directory, like ``MySimulation/halos/z1.000/``.
Or a single halo info file, or a list of halo info files.
Will accept ``halo_info`` dirs or "redshift" dirs
(e.g. ``z1.000/halo_info/`` or ``z1.000/``).
.. note::
To load cleaned catalogs, you do *not* need to pass a different
argument to the ``path`` directory. Use ``cleaned=True`` instead
and the path to the cleaning info will be detected automatically
(or see ``cleandir``).
cleaned: bool, optional
Loads the "cleaned" version of the halo catalogues. Always recommended.
Assumes there is a directory called ``cleaning/`` at the same level
as the top-level simulation directory (or see ``cleandir``).
Default: True.
False returns the out-of-the-box CompaSO halos. May be useful for specific
applications.
subsamples: bool or dict, optional
Load halo particle subsamples. True or False may be specified
to load all particles or none, or a dict to specify whether to
load subsample A and/or B, with pos, vel, and/or pid fields:
.. code-block:: none
subsamples=dict(A=True, B=True, pos=True, vel=True, pid=True)
The ``rv`` key may be used as shorthand to set both ``pos`` and ``vel``.
False (the default) loads nothing.
convert_units: bool, optional
Convert positions from unit-box units to BoxSize-box units,
velocities already come in km/s. Default: True.
unpack_bits: bool, or list of str, optional
Extract information from the PID field of each subsample particle
info about its Lagrangian position, whether it is tagged, and its
current local density. If False, only the particle ID part will
be extracted. Note that this per-particle information can be large.
Can be a list of str, in which case only those fields will be unpacked.
Field names are: ('pid', 'lagr_pos', 'tagged', 'density', 'lagr_idx').
Default: False.
fields: str or list of str, optional
A list of field names/halo properties to load. Selecting a small
subset of fields can be substantially faster than loading all fields
because the file IO will be limited to the desired fields.
See ``compaso_halo_catalog.user_dt`` or the :doc:`AbacusSummit Data Model page <summit:data-products>`
for a list of available fields. See ``compaso_halo_catalog.clean_dt`` for the list
of cleaned halo fields that will be loaded. 'all' will also load main progenitor
information, which could be slow.
Default: 'DEFAULT_FIELDS'
verbose: bool, optional
Print informational messages. Default: False
cleandir: str, optional
Where the halo catalog cleaning files are located (usually called ``cleaning/``).
Default of None will try to detect it automatically. Only has any effect if
using ``cleaned=True``.
filter_func: function, optional
A mask function to be applied to each superslab as it is loaded. The function
must take one argument (a halo table) and return a boolean array or similar
mask on the rows. Simple lambda expressions are particularly useful here;
for example, to load all halos with 100 particles or more, use:
.. code-block:: python
filter_func=lambda h: h['N'] >= 100
halo_lc: bool or None, optional
Whether the catalog is a halo light cone catalog, i.e. an output of the CompaSO
halo light cone pipeline. Default of None means to detect based on the catalog path.
"""
# Internally, we will use `load_subsamples` as the name of the `subsamples` arg to distinguish it from the `self.subsamples` table
load_subsamples = subsamples
del subsamples
if 'load_subsamples' in kwargs:
load_subsamples = kwargs.pop('load_subsamples')
warnings.warn('`load_subsamples` argument is deprecated; use `subsamples`', FutureWarning)
if 'cleaned_halos' in kwargs:
cleaned = kwargs.pop('cleaned_halos')
warnings.warn('`cleaned_halos` argument is deprecated; use `cleaned`', FutureWarning)
# `cleaned` and `self.cleaned` mean slightly different things.
# `cleaned` (local var) means to load the cleaning info files,
# `self.cleaned` means the catalog incorporates cleaning info, either because the user
# said `cleaned=True` or because this is a halo light cone catalog, which is already cleaned
self.cleaned = cleaned
if halo_lc == None:
halo_lc = self.is_path_halo_lc(path)
if verbose and halo_lc:
print('Detected halo light cone catalog.')
self.halo_lc = halo_lc
# If loading halo light cones, turn off cleaning and bit unpacking because done already
if halo_lc:
if not self.cleaned:
warnings.warn('`cleaned=False` was specified but halo light cones always incorporate cleaning')
cleaned = False
unpack_bits = False
self.cleaned = True
# Check no unknown args!
if kwargs:
raise ValueError(f'Unknown arguments to CompaSOHaloCatalog constructor: {list(kwargs)}')
# Parse `path` to determine what files to read
(self.groupdir,
self.cleandir,
self.superslab_inds,
self.halo_fns,
self.cleaned_halo_fns) = self._setup_file_paths(path, cleaned=cleaned, cleandir=cleandir, halo_lc=halo_lc)
# Figure out what subsamples the user is asking us to loads
(self.load_AB,
self.load_pidrv,
self.unpack_subsamples) = self._setup_load_subsamples(load_subsamples)
del load_subsamples # use the parsed values
# If using halo light cones, only have subsample A available
if halo_lc:
if self.unpack_subsamples:
self.load_AB = ['A']
# Parse `fields` and `cleaned_fields` to determine halo catalog fields to read
(self.fields,
self.cleaned_fields) = self._setup_fields(fields, cleaned=cleaned, load_AB=self.load_AB, halo_lc=halo_lc)
del fields # use self.fields
self.data_key = 'data'
self.convert_units = convert_units # let's save, user might want to check later
self.verbose = verbose
self.filter_func = filter_func
unpack_bits = self._setup_unpack_bits(unpack_bits)
# End parameter parsing, begin opening files
# Open the first file, just to grab the header
with asdf.open(self.halo_fns[0], lazy_load=True, copy_arrays=False) as af:
# will also be available as self.halos.meta
self.header = af['header']
# For any applications that propagate the header, record whether they used cleaned halos
self.header['cleaned_halos'] = self.cleaned
# If we are using cleaned haloes, want to also grab header information regarding number of preceding timesteps
if cleaned:
with asdf.open(self.cleaned_halo_fns[0], lazy_load=True, copy_arrays=False) as af:
self.header['TimeSliceRedshiftsPrev'] = af['header']['TimeSliceRedshiftsPrev']
self.header['NumTimeSliceRedshiftsPrev'] = len(af['header']['TimeSliceRedshiftsPrev'])
# Read and unpack the catalog into self.halos
self._setup_halo_field_loaders()
N_halo_per_file = self._read_halo_info(self.halo_fns, self.fields,
cleaned_fns=self.cleaned_halo_fns, cleaned_fields=self.cleaned_fields,
halo_lc=halo_lc,
)
self.subsamples = Table() # empty table, to be filled with PIDs and RVs in the loading functions below
self.numhalos = N_halo_per_file
# reindex subsamples if this is an L1 redshift
# halo subsamples have not yet been reindexed
self._reindexed = {'A': False, 'B': False}
self._reindexed_merge = {'A': False, 'B': False}
if cleaned:
self._updated_indices = {'A': False, 'B': False}
# Updating subsamples indices needs to be done only once, and only right
# at the end (i.e. after all pid/pos/vel/rv have been read)
# Define `self.subsamples_to_load` as a way to track what still needs to be loaded
self.subsamples_to_load = self.load_pidrv.copy()
# Loading the particle information
# B.H. unpack_pid
if "pid" in self.load_pidrv:
self.subsamples_to_load.remove('pid')
self._load_pids(unpack_bits, N_halo_per_file, cleaned=cleaned, halo_lc=halo_lc)
# B.H. unpacked_pos and vel
if 'pos' in self.load_pidrv or 'vel' in self.load_pidrv:
for k in ['pos','vel']:
if k in self.subsamples_to_load:
self.subsamples_to_load.remove(k)
# unpack_which = None will still read the RVs but will keep them in rvint
unpack_which = self.load_pidrv if self.unpack_subsamples else None
self._load_RVs(N_halo_per_file, cleaned=cleaned, unpack_which=unpack_which, halo_lc=halo_lc)
# Don't need this any more
del self.subsamples_to_load
# If we're reading in cleaned haloes, N should be updated
if cleaned:
self.halos.rename_column('N_total', 'N')
if verbose:
print('\n'+str(self))
gc.collect()
def _setup_file_paths(self, path, cleaned=True, cleandir=None, halo_lc=False):
'''Figure out what files the user is asking for
'''
# For the moment, coerce pathlib to str
if isinstance(path, PurePath):
path = str(path)
if type(path) is str:
path = [path] # dir or file
else:
# if list, must be all files
for p in path:
if os.path.exists(p) and not isfile(p):
raise ValueError(f'If passing a list of paths, all paths must be files, not dirs. Path "{p}" is not a file.')
for p in path:
if not os.path.exists(p):
raise FileNotFoundError(f'Path "{p}" does not exist!')
path = [abspath(p) for p in path]
# Allow users to pass halo_info dirs, even though redshift dirs remain canoncial
for i,p in enumerate(path):
if basename(p) == 'halo_info':
path[i] = abspath(pjoin(p,os.pardir))
# Can't mix files from different catalogs!
if isfile(path[0]):
groupdir = dirname(dirname(path[0]))
if halo_lc:
groupdir = dirname(path[0])
for p in path:
if not samefile(groupdir, dirname(dirname(p))) and not halo_lc:
raise ValueError("Can't mix files from different catalogs!")
halo_fns = path # path is list of one or more files
for i,p in enumerate(path):
for j,q in enumerate(path[i+1:]):
if samefile(p,q):
raise ValueError(f'Cannot pass duplicate halo_info files! Found duplicate "{p}" and at indices {i} and {i+j+1}')
else:
groupdir = path[0] # path is a singlet of one dir
if halo_lc: # naming convention differs for the light cone catalogs
globpat = pjoin(groupdir, 'lc_halo_info*.asdf')
else:
globpat = pjoin(groupdir, 'halo_info', 'halo_info_*')
halo_fns = sorted(glob(globpat))
if len(halo_fns) == 0:
raise FileNotFoundError(f'No halo_info files found! Search pattern was: "{globpat}"')
if halo_lc: # halo light cones files aggregate all superslabs into a single file
superslab_inds = np.array([0])
else:
superslab_inds = np.array([int(hfn.split('_')[-1].strip('.asdf')) for hfn in halo_fns])
if cleaned:
pathsplit = groupdir.split(os.path.sep)
del pathsplit[-2] # remove halos/, leaving .../SimName/z0.000
s = -2
if not cleandir:
cleandir = os.path.sep + pjoin(*pathsplit[:s], 'cleaning')
if not isdir(cleandir) and 'small' in pathsplit[-2]:
s = -3
cleandir_small = os.path.sep + pjoin(*pathsplit[:s], 'cleaning')
if not isdir(cleandir_small):
raise FileNotFoundError(f'Could not find cleaning info dir. Tried:\n"{cleandir}"\n"{cleandir_small}"\nTo load the uncleaned catalog, use `cleaned=False`.')
cleandir = cleandir_small
cleandir = pjoin(cleandir, *pathsplit[s:]) # TODO ugly
cleaned_halo_fns = [pjoin(cleandir, 'cleaned_halo_info', 'cleaned_halo_info_%03d.asdf'%(ext)) for ext in superslab_inds]
for fn in cleaned_halo_fns:
if not isfile(fn):
raise FileNotFoundError(f'Cleaning info not found. File path was: "{fn}". To load the uncleaned catalog, use `cleaned=False`.')
else:
cleandir = None
cleaned_halo_fns = []
return groupdir, cleandir, superslab_inds, halo_fns, cleaned_halo_fns
def _setup_unpack_bits(self, unpack_bits):
# validate unpack_bits
if type(unpack_bits) is str:
unpack_bits = [unpack_bits]
if unpack_bits not in (True,False):
try:
for _f in unpack_bits:
assert _f in bitpacked.PID_FIELDS
except:
raise ValueError(f'`unpack_bits` must be True, False, or one of: "{bitpacked.PID_FIELDS}"')
return unpack_bits
def _setup_load_subsamples(self, load_subsamples):
'''
Figure out if the user wants A, B, pid, pos, vel.
Will be returned as lists of strings in `load_AB` and `load_pidrv`.
`unpack_subsamples` is for pipelining, to keep things in rvint.
'''
if load_subsamples == False:
# stub
load_AB = []
load_pidrv = []
unpack_subsamples = True
else:
# If user has not specified which subsamples, then assume user wants to load everything
if load_subsamples == True:
load_subsamples = dict(A=True, B=True, rv=True, pid=True)
if type(load_subsamples) == dict:
load_AB = [k for k in 'AB' if load_subsamples.get(k)] # ['A', 'B']
# Check for conflicts between rv, pos, vel. Must be done before list-ifying to distinguish False and not given.
if 'rv' in load_subsamples:
if 'pos' in load_subsamples or 'vel' in load_subsamples:
raise ValueError('Cannot pass `rv` and `pos` or `vel` in `load_subsamples`.')
load_pidrv = [k for k in load_subsamples if k in ('pid','pos','vel','rv') and load_subsamples.get(k)] # ['pid', 'pos', 'vel']
unpack_subsamples = load_subsamples.pop('unpack',True)
# set some intelligent defaults
if load_pidrv and not load_AB:
warnings.warn(f'Loading of {load_pidrv} was requested but neither subsample A nor B was specified. Assuming subsample A. Can specify with `load_subsamples=dict(A=True)`.')
load_AB = ['A']
elif not load_pidrv and load_AB:
if load_subsamples.get('pos') is not False:
load_pidrv += ['pos']
if load_subsamples.get('vel') is not False:
load_pidrv += ['vel']
if not load_pidrv:
warnings.warn(f'Loading of subsample {load_AB} was requested but none of `pos`, `vel`, `rv`, `pid` was specified. Assuming `rv`. Can specify with `load_subsamples=dict(rv=True)`.')
load_pidrv = ['rv']
if load_subsamples.pop('field',False):
raise ValueError('Loading field particles through CompaSOHaloCatalog is not supported. Read the particle files directly with `abacusnbody.data.read_abacus.read_asdf()`.')
# Pop all known keys, so if anything is left, that's an error!
for k in ['A', 'B', 'rv', 'pid', 'pos', 'vel', 'unpack']:
load_subsamples.pop(k,None)
if load_subsamples:
raise ValueError(f'Unrecognized keys in `load_subsamples`: {list(load_subsamples)}')
elif type(load_subsamples) == str:
# This section is deprecated, will remove in mid-2021
warnings.warn('Passing a string to `load_subsamples` is deprecated; use a dict instead, like: `load_subsamples=dict(A=True, rv=True)`', FutureWarning)
# Validate the user's `load_subsamples` option and figure out what subsamples we need to load
subsamp_match = re.fullmatch(r'(?P<AB>(A|B|AB))(_(?P<hf>halo|field))?_(?P<pidrv>all|pid|rv)', load_subsamples)
if not subsamp_match:
raise ValueError(f'Value "{load_subsamples}" for argument `load_subsamples` not understood')
load_AB = subsamp_match.group('AB')
load_halofield = subsamp_match.group('hf')
load_halofield = [load_halofield] if load_halofield else ['halo','field'] # default is both
load_pidrv = subsamp_match.group('pidrv')
load_pidrv = subsamp_match.group('pidrv')
if load_pidrv == 'all':
load_pidrv = ['pid','rv']
if type(load_pidrv) == str:
# Turn this into a list so that the .remove() operation below doesn't complain
load_pidrv = [load_pidrv]
if 'field' in load_halofield:
raise ValueError('Loading field particles through CompaSOHaloCatalog is not supported. Read the particle files directly with `abacusnbody.data.read_abacus.read_asdf()`.')
unpack_subsamples = True
if 'rv' in load_pidrv:
load_pidrv.remove('rv')
load_pidrv += ['pos', 'vel']
return load_AB, load_pidrv, unpack_subsamples
def _setup_fields(self, fields, cleaned=True, load_AB=[], halo_lc=False):
'''Determine the halo catalog fields to load based on user input
'''
if fields == 'DEFAULT_FIELDS':
fields = list(user_dt.names)
if cleaned:
fields += list(clean_dt.names)
if halo_lc:
fields += list(halo_lc_dt.names)
if fields == 'all':
fields = list(user_dt.names)
if cleaned:
fields += list(clean_dt_progen.names)
if halo_lc:
fields += list(halo_lc_dt.names)
if type(fields) == str:
fields = [fields]
# Convert any other iter, like tuple
fields = list(fields)
# Minimum requirement for cleaned haloes
if cleaned:
# If we load cleaned, 'N' no longer has meaning
if 'N' in fields:
fields.remove('N')
if 'N_total' not in fields:
fields += ['N_total']
# Let's split `fields` so that there is a separate set of `cleaned_fields`
cleaned_fields = []
if cleaned:
for item in list(clean_dt_progen.names):
if item in fields:
fields.remove(item)
cleaned_fields += [item]
# B.H. Remove fields that are not recorded for the light cone catalogs
if halo_lc:
for item in list(fields):
# TODO: this will silently drop misspellings
if 'L2' not in item and item not in halo_lc_dt.names:
fields.remove(item)
if cleaned:
# If the user has not asked to load npstart{AB}_merge columns, we need to do so ourselves for indexing
for AB in load_AB:
if 'npstart'+AB not in fields:
fields += ['npstart'+AB]
if 'npout'+AB not in fields:
fields += ['npout'+AB]
if 'npstart'+AB+'_merge' not in cleaned_fields:
cleaned_fields += ['npstart'+AB+'_merge']
if 'npout'+AB+'_merge' not in cleaned_fields:
cleaned_fields += ['npout'+AB+'_merge']
return fields, cleaned_fields
def _read_halo_info(self, halo_fns, fields, cleaned_fns=None, cleaned_fields=None, halo_lc=False):
if not cleaned_fields:
cleaned_fields = []
if not cleaned_fns:
cleaned_fns = []
else:
assert len(cleaned_fns) == len(halo_fns)
# Open all the files, validate them, and count the halos
# Lazy load, but don't use mmap
afs = [asdf.open(hfn, lazy_load=True, copy_arrays=True) for hfn in halo_fns]
cleaned_afs = [asdf.open(hfn, lazy_load=True, copy_arrays=True) for hfn in cleaned_fns]
N_halo_per_file = np.array([len(af[self.data_key][list(af[self.data_key].keys())[0]]) for af in afs])
for _N,caf in zip(N_halo_per_file,cleaned_afs):
assert len(caf[self.data_key][next(iter(caf[self.data_key]))]) == _N # check cleaned/regular file consistency
N_halos = N_halo_per_file.sum()
# Make an empty table for the concatenated, unpacked values
# Note that np.empty is being smart here and creating 2D arrays when the dtype is a vector
cols = {}
for col in fields:
if col in halo_lc_dt.names:
cols[col] = np.empty(N_halos, dtype=halo_lc_dt[col])
else:
cols[col] = np.empty(N_halos, dtype=user_dt[col])
for col in cleaned_fields:
cols[col] = np.empty(N_halos, dtype=clean_dt_progen[col])
all_fields = fields + cleaned_fields
# Figure out what raw columns we need to read based on the fields the user requested
# TODO: provide option to drop un-requested columns
raw_dependencies, fields_with_deps, extra_fields = self._get_halo_fields_dependencies(all_fields)
# save for informational purposes
if not hasattr(self, 'dependency_info'):
self.dependency_info = defaultdict(list)
self.dependency_info['raw_dependencies'] += raw_dependencies
self.dependency_info['fields_with_deps'] += fields_with_deps
self.dependency_info['extra_fields'] += extra_fields
if self.verbose:
# TODO: going to be repeated in output
print(f'{len(fields)} halo catalog fields ({len(cleaned_fields)} cleaned) requested. '
f'Reading {len(raw_dependencies)} fields from disk. '
f'Computing {len(extra_fields)} intermediate fields.')
if self.halo_lc:
print('\nFor more information on the halo light cone catalog fields, see https://abacussummit.readthedocs.io/en/latest/data-products.html#halo-light-cone-catalogs')
self.halos = Table(cols, copy=False)
self.halos.meta.update(self.header)
# If we're loading main progenitor info, do this:
# TODO: this shows the limits of querying the types from a numpy dtype, should query from a function
r = re.compile('.*mainprog')
prog_fields = list(filter(r.match, cleaned_fields))
for fields in prog_fields:
if fields in ['v_L2com_mainprog', 'haloindex_mainprog']:
continue
else:
self.halos.replace_column(fields, np.empty(N_halos, dtype=(clean_dt_progen[fields], self.header['NumTimeSliceRedshiftsPrev'])))
# Unpack the cats into the concatenated array
# The writes would probably be more efficient if the outer loop was over column
# and the inner was over cats, but wow that would be ugly
N_written = 0
for i,af in enumerate(afs):
caf = cleaned_afs[i] if cleaned_afs else None
# This is where the IO on the raw columns happens
# There are some fields that we'd prefer to directly read into the concatenated table,
# but ASDF doesn't presently support that, so this is the best we can do
rawhalos = {}
for field in raw_dependencies:
src = caf if field in clean_dt_progen.names else af
rawhalos[field] = src[self.data_key][field]
rawhalos = Table(data=rawhalos, copy=False)
af.close()
if caf:
caf.close()
# `halos` will be a "pointer" to the next open space in the master table
halos = self.halos[N_written:N_written+len(rawhalos)]
# For temporary (extra) columns, only need to construct the per-file version
for field in extra_fields:
src = clean_dt_progen if field in clean_dt_progen.names else user_dt
halos.add_column(np.empty(len(rawhalos), dtype=src[col]), name=field, copy=False)
# halos[field][:] = np.nan # for debugging
loaded_fields = []
for field in fields_with_deps:
if field in loaded_fields:
continue
loaded_fields += self._load_halo_field(halos, rawhalos, field)
if self.filter_func:
# N_total from the cleaning replaces N. For filtering purposes, allow the user to use 'N'
halos.rename_column('N_total', 'N')
mask = self.filter_func(halos)
nmask = mask.sum()
halos[:nmask] = halos[mask]
del mask
N_superslab = nmask
else:
N_superslab = len(halos)
N_written += N_superslab
N_halo_per_file[i] = N_superslab
del halos, rawhalos
del af, caf, src
afs[i] = None
if cleaned_afs:
cleaned_afs[i] = None
gc.collect()
# Now the filtered length
self.halos = self.halos[:N_written]
if N_written < N_halos:
# Release virtual memory if we didn't fill the whole allocation
for col in cols:
s = list(cols[col].shape)
s[0] = N_written
oldaddr = cols[col].ctypes.data
cols[col].resize(s, refcheck=False)
if cols[col].ctypes.data != oldaddr:
warnings.warn('Resize resulted in copy')
N_halos = len(self.halos)
return N_halo_per_file
def _setup_halo_field_loaders(self):
# Loaders is a dict of regex -> lambda
# The lambda is responsible for unpacking the rawhalos field
# The first regex that matches will be used, so they must be precise
self.halo_field_loaders = {}
if self.convert_units:
box = self.header['BoxSize']
# TODO: correct velocity units? There is an earlier comment claiming that velocities are already in km/s
zspace_to_kms = self.header['VelZSpace_to_kms']
else:
box = 1.
zspace_to_kms = 1.
# The first argument to the following lambdas is the match object from re.match()
# We will use m[0] to access the full match (i.e. the full field name)
# Other indices, like m['com'], will access the sub-match with that group name
# r10,r25,r33,r50,r67,r75,r90,r95,r98
pat = re.compile(r'(?:r\d{1,2}|rvcirc_max)(?P<com>_(?:L2)?com)')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]+'_i16']*raw['r100'+m['com']]/INT16SCALE*box
# sigmavMin, sigmavMaj, sigmavrad, sigmavtan
pat = re.compile(r'(?P<stem>sigmav(?:Min|Maj|rad|tan))(?P<com>_(?:L2)?com)')
def _sigmav_loader(m,raw,halos):
stem = m['stem'].replace('Maj','Max')
return raw[stem+'_to_sigmav3d'+m['com']+'_i16']*raw['sigmav3d'+m['com']]/INT16SCALE*box
self.halo_field_loaders[pat] = _sigmav_loader
# sigmavMid
pat = re.compile(r'sigmavMid(?P<com>_(?:L2)?com)')
self.halo_field_loaders[pat] = lambda m,raw,halos: np.sqrt(raw['sigmav3d'+m['com']]*raw['sigmav3d'+m['com']]*box**2 \
- halos['sigmavMaj'+m['com']]**2 - halos['sigmavMin'+m['com']]**2)
# sigmar
pat = re.compile(r'sigmar(?P<com>_(?:L2)?com)')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]+'_i16']*raw['r100'+m['com']].reshape(-1,1)/INT16SCALE*box
# sigman
pat = re.compile(r'sigman(?P<com>_(?:L2)?com)')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]+'_i16']/INT16SCALE*box
# x,r100 (box-scaled fields)
pat = re.compile(r'(x|r100)(?P<com>_(?:L2)?com)')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]]*box
# v,sigmav,sigmav3d,meanSpeed,sigmav3d_r50,meanSpeed_r50,vcirc_max (vel-scaled fields)
pat = re.compile(r'(v|sigmav3d|meanSpeed|sigmav3d_r50|meanSpeed_r50|vcirc_max)(?P<com>_(?:L2)?com)')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]]*zspace_to_kms
# id,npstartA,npstartB,npoutA,npoutB,ntaggedA,ntaggedB,N,L2_N,L0_N (raw/passthrough fields)
# If ASDF could read into a user-provided array, could avoid these copies
pat = re.compile(r'id|npstartA|npstartB|npoutA|npoutB|ntaggedA|ntaggedB|N|L2_N|L0_N|N_total|N_merge|npstartA_merge|npstartB_merge|npoutA_merge|npoutB_merge|npoutA_L0L1|npoutB_L0L1|is_merged_to|N_mainprog|vcirc_max_L2com_mainprog|sigmav3d_L2com_mainprog|haloindex|haloindex_mainprog|v_L2com_mainprog')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]]
# SO_central_particle,SO_radius (and _L2max) (box-scaled fields)
pat = re.compile(r'SO(?:_L2max)?(?:_central_particle|_radius)')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]]*box
# SO_central_density (and _L2max)
pat = re.compile(r'SO(?:_L2max)?(?:_central_density)')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]]
# loader for halo light cone catalog specific fields
pat = re.compile(r'index_halo|pos_avg|vel_avg|redshift_interp|N_interp')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]]
# loader for halo light cone catalog field `origin`
pat = re.compile(r'origin')
self.halo_field_loaders[pat] = lambda m,raw,halos: raw[m[0]]%3
# loader for halo light cone catalog fields: interpolated position and velocity
pat = re.compile(r'(?P<pv>pos|vel)_interp')
def lc_interp_loader(m, raw, halos):
columns = {}
interped = (raw['origin'] // 3).astype(bool)
if m[0] == 'pos_interp' or 'pos_interp' in halos.colnames:
columns['pos_interp'] = np.where(interped[:, None], raw['pos_avg'], raw['pos_interp'])
if m[0] == 'vel_interp' or 'vel_interp' in halos.colnames:
columns['vel_interp'] = np.where(interped[:, None], raw['vel_avg'], raw['vel_interp'])
return columns
self.halo_field_loaders[pat] = lc_interp_loader
# eigvecs loader
pat = re.compile(r'(?P<rnv>sigma(?:r|n|v)_eigenvecs)(?P<which>Min|Mid|Maj)(?P<com>_(?:L2)?com)')
def eigvecs_loader(m,raw,halos):
minor,middle,major = unpack_euler16(raw[m['rnv']+m['com']+'_u16'])
columns = {}