forked from 21cmfast/21cmFAST
/
wrapper.py
3699 lines (3155 loc) · 142 KB
/
wrapper.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
############################################################################
# Modified versions of DarkHistory for 21cmFAST
#
# Copyright (C) 2022 Gaetan Facchinetti
# gaetan.facchinetti@ulb.be
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>
#
#
# This code is largely based on the original wrapper.py of 21cmFAST
#
# # MIT License
# #
# # Copyright (c) 2019, 21cmFAST Collaboration
# #
# # Permission is hereby granted, free of charge, to any person obtaining a copy
# # of this software and associated documentation files (the "Software"), to deal
# # in the Software without restriction, including without limitation the rights
# # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# # copies of the Software, and to permit persons to whom the Software is
# # furnished to do so, subject to the following conditions:
# #
# # The above copyright notice and this permission notice shall be included in all
# # copies or substantial portions of the Software.
# #
# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# # SOFTWARE.
##################################################################################
"""
The main wrapper for the underlying 21cmFAST C-code.
The module provides both low- and high-level wrappers, using the very low-level machinery
in :mod:`~py21cmfast._utils`, and the convenient input and output structures from
:mod:`~py21cmfast.inputs` and :mod:`~py21cmfast.outputs`.
This module provides a number of:
* Low-level functions which simplify calling the background C functions which populate
these output objects given the input classes.
* High-level functions which provide the most efficient and simplest way to generate the
most commonly desired outputs.
**Low-level functions**
The low-level functions provided here ease the production of the aforementioned output
objects. Functions exist for each low-level C routine, which have been decoupled as far
as possible. So, functions exist to create :func:`initial_conditions`,
:func:`perturb_field`, :class:`ionize_box` and so on. Creating a brightness temperature
box (often the desired final output) would generally require calling each of these in
turn, as each depends on the result of a previous function. Nevertheless, each function
has the capability of generating the required previous outputs on-the-fly, so one can
instantly call :func:`ionize_box` and get a self-consistent result. Doing so, while
convenient, is sometimes not *efficient*, especially when using inhomogeneous
recombinations or the spin temperature field, which intrinsically require consistent
evolution of the ionization field through redshift. In these cases, for best efficiency
it is recommended to either use a customised manual approach to calling these low-level
functions, or to call a higher-level function which optimizes this process.
Finally, note that :mod:`py21cmfast` attempts to optimize the production of the large amount of
data via on-disk caching. By default, if a previous set of data has been computed using
the current input parameters, it will be read-in from a caching repository and returned
directly. This behaviour can be tuned in any of the low-level (or high-level) functions
by setting the `write`, `direc`, `regenerate` and `match_seed` parameters (see docs for
:func:`initial_conditions` for details). The function :func:`~query_cache` can be used
to search the cache, and return empty datasets corresponding to each (and these can then be
filled with the data merely by calling ``.read()`` on any data set). Conversely, a
specific data set can be read and returned as a proper output object by calling the
:func:`~py21cmfast.cache_tools.readbox` function.
**High-level functions**
As previously mentioned, calling the low-level functions in some cases is non-optimal,
especially when full evolution of the field is required, and thus iteration through a
series of redshift. In addition, while :class:`InitialConditions` and
:class:`PerturbedField` are necessary intermediate data, it is *usually* the resulting
brightness temperature which is of most interest, and it is easier to not have to worry
about the intermediate steps explicitly. For these typical use-cases, two high-level
functions are available: :func:`run_coeval` and :func:`run_lightcone`, whose purpose
should be self-explanatory. These will optimally run all necessary intermediate
steps (using cached results by default if possible) and return all datasets of interest.
Examples
--------
A typical example of using this module would be the following.
>>> import py21cmfast as p21
Get coeval cubes at redshift 7,8 and 9, without spin temperature or inhomogeneous
recombinations:
>>> coeval = p21.run_coeval(
>>> redshift=[7,8,9],
>>> cosmo_params=p21.CosmoParams(hlittle=0.7),
>>> user_params=p21.UserParams(HII_DIM=100)
>>> )
Get coeval cubes at the same redshift, with both spin temperature and inhomogeneous
recombinations, pulled from the natural evolution of the fields:
>>> all_boxes = p21.run_coeval(
>>> redshift=[7,8,9],
>>> user_params=p21.UserParams(HII_DIM=100),
>>> flag_options=p21.FlagOptions(INHOMO_RECO=True),
>>> do_spin_temp=True
>>> )
Get a self-consistent lightcone defined between z1 and z2 (`z_step_factor` changes the
logarithmic steps between redshift that are actually evaluated, which are then
interpolated onto the lightcone cells):
>>> lightcone = p21.run_lightcone(redshift=z2, max_redshift=z2, z_step_factor=1.03)
"""
from importlib import find_loader
import logging
import numpy as np
import os
import warnings
from astropy import units
from astropy.cosmology import z_at_value
from copy import deepcopy
from scipy.interpolate import interp1d
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Union
from ._cfg import config
from ._utils import (
OutputStruct,
StructWrapper,
_check_compatible_inputs,
_process_exitcode,
)
from .c_21cmfast import ffi, lib
from .inputs import AstroParams, CosmoParams, FlagOptions, UserParams, global_params, ExoticEnergyInjected
from .outputs import (
BrightnessTemp,
Coeval,
HaloField,
InitialConditions,
IonizedBox,
LightCone,
PerturbedField,
PerturbHaloField,
TsBox,
_OutputStructZ,
)
logger = logging.getLogger(__name__)
#####################################################################################
## New in Exo21cmFAST
## Import what is necessary to use DarkHistory
import sys
_DARKHISTORY_NOT_FOUND_ = False
try:
from . import dh_tools as dep_21 # Tools to use DH inside 21cmFAST
import DarkHistory.darkhistory.physics as phys
except:
_DARKHISTORY_NOT_FOUND_ = True
#####################################################################################
from .c_21cmfast import ffi
def _configure_inputs(
defaults: list,
*datasets,
ignore: list = ["redshift"],
flag_none: [list, None] = None,
):
"""Configure a set of input parameter structs.
This is useful for basing parameters on a previous output.
The logic is this: the struct _cannot_ be present and different in both defaults and
a dataset. If it is present in _either_ of them, that will be returned. If it is
present in _neither_, either an error will be raised (if that item is in `flag_none`)
or it will pass.
Parameters
----------
defaults : list of 2-tuples
Each tuple is (key, val). Keys are input struct names, and values are a default
structure for that input.
datasets : list of :class:`~_utils.OutputStruct`
A number of output datasets to cross-check, and draw parameter values from.
ignore : list of str
Attributes to ignore when ensuring that parameter inputs are the same.
flag_none : list
A list of parameter names for which ``None`` is not an acceptable value.
Raises
------
ValueError :
If an input parameter is present in both defaults and the dataset, and is different.
OR if the parameter is present in neither defaults not the datasets, and it is
included in `flag_none`.
"""
# First ensure all inputs are compaible in their parameters
_check_compatible_inputs(*datasets, ignore=ignore)
if flag_none is None:
flag_none = []
output = [0] * len(defaults)
for i, (key, val) in enumerate(defaults):
# Get the value of this input from the datasets
data_val = None
for dataset in datasets:
if dataset is not None and hasattr(dataset, key):
data_val = getattr(dataset, key)
break
# If both data and default have values
if not (val is None or data_val is None or data_val == val):
raise ValueError(
"%s has an inconsistent value with %s"
% (key, dataset.__class__.__name__)
)
else:
if val is not None:
output[i] = val
elif data_val is not None:
output[i] = data_val
elif key in flag_none:
raise ValueError(
"For %s, a value must be provided in some manner" % key
)
else:
output[i] = None
return output
def configure_redshift(redshift, *structs):
"""
Check and obtain a redshift from given default and structs.
Parameters
----------
redshift : float
The default redshift to use
structs : list of :class:`~_utils.OutputStruct`
A number of output datasets from which to find the redshift.
Raises
------
ValueError :
If both `redshift` and *all* structs have a value of `None`, **or** if any of them
are different from each other (and not `None`).
"""
zs = {s.redshift for s in structs if s is not None and hasattr(s, "redshift")}
zs = list(zs)
if len(zs) > 1 or (len(zs) == 1 and redshift is not None and zs[0] != redshift):
raise ValueError("Incompatible redshifts in inputs")
elif len(zs) == 1:
return zs[0]
elif redshift is None:
raise ValueError(
"Either redshift must be provided, or a data set containing it."
)
else:
return redshift
def _verify_types(**kwargs):
"""Ensure each argument has a type of None or that matching its name."""
for k, v in kwargs.items():
for j, kk in enumerate(
["init", "perturb", "ionize", "spin_temp", "halo_field", "pt_halos"]
):
if kk in k:
break
cls = [
InitialConditions,
PerturbedField,
IonizedBox,
TsBox,
HaloField,
PerturbHaloField,
][j]
if v is not None and not isinstance(v, cls):
raise ValueError(f"{k} must be an instance of {cls.__name__}")
def _call_c_simple(fnc, *args):
"""Call a simple C function that just returns an object.
Any such function should be defined such that the last argument is an int pointer generating
the status.
"""
# Parse the function to get the type of the last argument
cdata = str(ffi.addressof(lib, fnc.__name__))
kind = cdata.split("(")[-1].split(")")[0].split(",")[-1]
result = ffi.new(kind)
status = fnc(*args, result)
_process_exitcode(status, fnc, args)
return result[0]
def _get_config_options(
direc, regenerate, write, hooks
) -> Tuple[str, bool, Dict[Callable, Dict[str, Any]]]:
direc = str(os.path.expanduser(config["direc"] if direc is None else direc))
hooks = hooks or {}
if callable(write) and write not in hooks:
hooks[write] = {"direc": direc}
if not hooks:
if write is None:
write = config["write"]
if not callable(write) and write:
hooks["write"] = {"direc": direc}
return (
direc,
bool(config["regenerate"] if regenerate is None else regenerate),
hooks,
)
def get_all_fieldnames(
arrays_only=True, lightcone_only=False, as_dict=False
) -> Union[Dict[str, str], Set[str]]:
"""Return all possible fieldnames in output structs.
Parameters
----------
arrays_only : bool, optional
Whether to only return fields that are arrays.
lightcone_only : bool, optional
Whether to only return fields from classes that evolve with redshift.
as_dict : bool, optional
Whether to return results as a dictionary of ``quantity: class_name``.
Otherwise returns a set of quantities.
"""
classes = [cls(redshift=0) for cls in _OutputStructZ._implementations()]
if not lightcone_only:
classes.append(InitialConditions())
attr = "pointer_fields" if arrays_only else "fieldnames"
if as_dict:
return {
name: cls.__class__.__name__
for cls in classes
for name in getattr(cls, attr)
}
else:
return {name for cls in classes for name in getattr(cls, attr)}
# ======================================================================================
# WRAPPING FUNCTIONS
# ======================================================================================
def construct_fftw_wisdoms(*, user_params=None, cosmo_params=None):
"""Construct all necessary FFTW wisdoms.
Parameters
----------
user_params : :class:`~inputs.UserParams`
Parameters defining the simulation run.
"""
user_params = UserParams(user_params)
cosmo_params = CosmoParams(cosmo_params)
# Run the C code
if user_params.USE_FFTW_WISDOM:
return lib.CreateFFTWWisdoms(user_params(), cosmo_params())
else:
return 0
def compute_tau(*, redshifts, global_xHI, user_params=None, cosmo_params=None):
"""Compute the optical depth to reionization under the given model.
Parameters
----------
redshifts : array-like
Redshifts defining an evolution of the neutral fraction.
global_xHI : array-like
The mean neutral fraction at `redshifts`.
user_params : :class:`~inputs.UserParams`
Parameters defining the simulation run.
cosmo_params : :class:`~inputs.CosmoParams`
Cosmological parameters.
Returns
-------
tau : float
The optional depth to reionization
Raises
------
ValueError :
If `redshifts` and `global_xHI` have inconsistent length or if redshifts are not
in ascending order.
"""
user_params = UserParams(user_params)
cosmo_params = CosmoParams(cosmo_params)
if len(redshifts) != len(global_xHI):
raise ValueError("redshifts and global_xHI must have same length")
if not np.all(np.diff(redshifts) > 0):
raise ValueError("redshifts and global_xHI must be in ascending order")
# Convert the data to the right type
redshifts = np.array(redshifts, dtype="float32")
global_xHI = np.array(global_xHI, dtype="float32")
z = ffi.cast("float *", ffi.from_buffer(redshifts))
xHI = ffi.cast("float *", ffi.from_buffer(global_xHI))
# Run the C code
return lib.ComputeTau(user_params(), cosmo_params(), len(redshifts), z, xHI)
def compute_luminosity_function(
*,
redshifts,
user_params=None,
cosmo_params=None,
astro_params=None,
flag_options=None,
nbins=100,
mturnovers=None,
mturnovers_mini=None,
component=0,
):
"""Compute a the luminosity function over a given number of bins and redshifts.
Parameters
----------
redshifts : array-like
The redshifts at which to compute the luminosity function.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
astro_params : :class:`~AstroParams`, optional
The astrophysical parameters defining the course of reionization.
flag_options : :class:`~FlagOptions`, optional
Some options passed to the reionization routine.
nbins : int, optional
The number of luminosity bins to produce for the luminosity function.
mturnovers : array-like, optional
The turnover mass at each redshift for massive halos (ACGs).
Only required when USE_MINI_HALOS is True.
mturnovers_mini : array-like, optional
The turnover mass at each redshift for minihalos (MCGs).
Only required when USE_MINI_HALOS is True.
component : int, optional
The component of the LF to be calculated. 0, 1 an 2 are for the total,
ACG and MCG LFs respectively, requiring inputs of both mturnovers and
mturnovers_MINI (0), only mturnovers (1) or mturnovers_MINI (2).
Returns
-------
Muvfunc : np.ndarray
Magnitude array (i.e. brightness). Shape [nredshifts, nbins]
Mhfunc : np.ndarray
Halo mass array. Shape [nredshifts, nbins]
lfunc : np.ndarray
Number density of haloes corresponding to each bin defined by `Muvfunc`.
Shape [nredshifts, nbins].
"""
user_params = UserParams(user_params)
cosmo_params = CosmoParams(cosmo_params)
astro_params = AstroParams(astro_params)
flag_options = FlagOptions(
flag_options, USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES
)
redshifts = np.array(redshifts, dtype="float32")
if flag_options.USE_MINI_HALOS:
if component in [0, 1]:
if mturnovers is None:
logger.warning(
"calculating ACG LFs with mini-halo feature requires users to "
"specify mturnovers!"
)
return None, None, None
mturnovers = np.array(mturnovers, dtype="float32")
if len(mturnovers) != len(redshifts):
logger.warning(
"mturnovers(%d) does not match the length of redshifts (%d)"
% (len(mturnovers), len(redshifts))
)
return None, None, None
if component in [0, 2]:
if mturnovers_mini is None:
logger.warning(
"calculating MCG LFs with mini-halo feature requires users to "
"specify mturnovers_MINI!"
)
return None, None, None
mturnovers_mini = np.array(mturnovers_mini, dtype="float32")
if len(mturnovers_mini) != len(redshifts):
logger.warning(
"mturnovers_MINI(%d) does not match the length of redshifts (%d)"
% (len(mturnovers), len(redshifts))
)
return None, None, None
else:
mturnovers = (
np.zeros(len(redshifts), dtype="float32") + 10 ** astro_params.M_TURN
)
component = 1
if component == 0:
lfunc = np.zeros(len(redshifts) * nbins)
Muvfunc = np.zeros(len(redshifts) * nbins)
Mhfunc = np.zeros(len(redshifts) * nbins)
lfunc.shape = (len(redshifts), nbins)
Muvfunc.shape = (len(redshifts), nbins)
Mhfunc.shape = (len(redshifts), nbins)
c_Muvfunc = ffi.cast("double *", ffi.from_buffer(Muvfunc))
c_Mhfunc = ffi.cast("double *", ffi.from_buffer(Mhfunc))
c_lfunc = ffi.cast("double *", ffi.from_buffer(lfunc))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
1,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers)),
c_Muvfunc,
c_Mhfunc,
c_lfunc,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
1,
len(redshifts),
),
)
lfunc_MINI = np.zeros(len(redshifts) * nbins)
Muvfunc_MINI = np.zeros(len(redshifts) * nbins)
Mhfunc_MINI = np.zeros(len(redshifts) * nbins)
lfunc_MINI.shape = (len(redshifts), nbins)
Muvfunc_MINI.shape = (len(redshifts), nbins)
Mhfunc_MINI.shape = (len(redshifts), nbins)
c_Muvfunc_MINI = ffi.cast("double *", ffi.from_buffer(Muvfunc_MINI))
c_Mhfunc_MINI = ffi.cast("double *", ffi.from_buffer(Mhfunc_MINI))
c_lfunc_MINI = ffi.cast("double *", ffi.from_buffer(lfunc_MINI))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
2,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers_mini)),
c_Muvfunc_MINI,
c_Mhfunc_MINI,
c_lfunc_MINI,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
2,
len(redshifts),
),
)
# redo the Muv range using the faintest (most likely MINI) and the brightest (most likely massive)
lfunc_all = np.zeros(len(redshifts) * nbins)
Muvfunc_all = np.zeros(len(redshifts) * nbins)
Mhfunc_all = np.zeros(len(redshifts) * nbins * 2)
lfunc_all.shape = (len(redshifts), nbins)
Muvfunc_all.shape = (len(redshifts), nbins)
Mhfunc_all.shape = (len(redshifts), nbins, 2)
for iz in range(len(redshifts)):
Muvfunc_all[iz] = np.linspace(
#np.min([Muvfunc.min(), Muvfunc_MINI.min()]),
#np.max([Muvfunc.max(), Muvfunc_MINI.max()]),
-24, -4, nbins,
)
lfunc_all[iz] = np.log10(
10
** (
interp1d(Muvfunc[iz], lfunc[iz], fill_value="extrapolate")(
Muvfunc_all[iz]
)
)
+ 10
** (
interp1d(
Muvfunc_MINI[iz], lfunc_MINI[iz], fill_value="extrapolate"
)(Muvfunc_all[iz])
)
)
Mhfunc_all[iz] = np.array(
[
interp1d(Muvfunc[iz], Mhfunc[iz], fill_value="extrapolate")(
Muvfunc_all[iz]
),
interp1d(
Muvfunc_MINI[iz], Mhfunc_MINI[iz], fill_value="extrapolate"
)(Muvfunc_all[iz]),
],
).T
lfunc_all[lfunc_all <= -30] = np.nan
return Muvfunc_all, Mhfunc_all, lfunc_all
elif component == 1:
lfunc = np.zeros(len(redshifts) * nbins)
Muvfunc = np.zeros(len(redshifts) * nbins)
Mhfunc = np.zeros(len(redshifts) * nbins)
lfunc.shape = (len(redshifts), nbins)
Muvfunc.shape = (len(redshifts), nbins)
Mhfunc.shape = (len(redshifts), nbins)
c_Muvfunc = ffi.cast("double *", ffi.from_buffer(Muvfunc))
c_Mhfunc = ffi.cast("double *", ffi.from_buffer(Mhfunc))
c_lfunc = ffi.cast("double *", ffi.from_buffer(lfunc))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
1,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers)),
c_Muvfunc,
c_Mhfunc,
c_lfunc,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
1,
len(redshifts),
),
)
lfunc[lfunc <= -30] = np.nan
return Muvfunc, Mhfunc, lfunc
elif component == 2:
lfunc_MINI = np.zeros(len(redshifts) * nbins)
Muvfunc_MINI = np.zeros(len(redshifts) * nbins)
Mhfunc_MINI = np.zeros(len(redshifts) * nbins)
lfunc_MINI.shape = (len(redshifts), nbins)
Muvfunc_MINI.shape = (len(redshifts), nbins)
Mhfunc_MINI.shape = (len(redshifts), nbins)
c_Muvfunc_MINI = ffi.cast("double *", ffi.from_buffer(Muvfunc_MINI))
c_Mhfunc_MINI = ffi.cast("double *", ffi.from_buffer(Mhfunc_MINI))
c_lfunc_MINI = ffi.cast("double *", ffi.from_buffer(lfunc_MINI))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
2,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers_mini)),
c_Muvfunc_MINI,
c_Mhfunc_MINI,
c_lfunc_MINI,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
2,
len(redshifts),
),
)
lfunc_MINI[lfunc_MINI <= -30] = np.nan
return Muvfunc_MINI, Mhfunc_MINI, lfunc_MINI
else:
logger.warning("What is component %d ?" % component)
return None, None, None
def _init_photon_conservation_correction(
*, user_params=None, cosmo_params=None, astro_params=None, flag_options=None
):
user_params = UserParams(user_params)
cosmo_params = CosmoParams(cosmo_params)
astro_params = AstroParams(astro_params)
flag_options = FlagOptions(
flag_options, USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES
)
return lib.InitialisePhotonCons(
user_params(), cosmo_params(), astro_params(), flag_options()
)
def _calibrate_photon_conservation_correction(
*, redshifts_estimate, nf_estimate, NSpline
):
# Convert the data to the right type
redshifts_estimate = np.array(redshifts_estimate, dtype="float64")
nf_estimate = np.array(nf_estimate, dtype="float64")
z = ffi.cast("double *", ffi.from_buffer(redshifts_estimate))
xHI = ffi.cast("double *", ffi.from_buffer(nf_estimate))
logger.debug(f"PhotonCons nf estimates: {nf_estimate}")
return lib.PhotonCons_Calibration(z, xHI, NSpline)
def _calc_zstart_photon_cons():
# Run the C code
return _call_c_simple(lib.ComputeZstart_PhotonCons)
def _get_photon_nonconservation_data():
"""
Access C global data representing the photon-nonconservation corrections.
.. note:: if not using ``PHOTON_CONS`` (in :class:`~FlagOptions`), *or* if the
initialisation for photon conservation has not been performed yet, this
will return None.
Returns
-------
dict :
z_analytic: array of redshifts defining the analytic ionized fraction
Q_analytic: array of analytic ionized fractions corresponding to `z_analytic`
z_calibration: array of redshifts defining the ionized fraction from 21cmFAST without
recombinations
nf_calibration: array of calibration ionized fractions corresponding to `z_calibration`
delta_z_photon_cons: the change in redshift required to calibrate 21cmFAST, as a function
of z_calibration
nf_photoncons: the neutral fraction as a function of redshift
"""
# Check if photon conservation has been initialised at all
if not lib.photon_cons_allocated:
return None
arbitrary_large_size = 2000
data = np.zeros((6, arbitrary_large_size))
IntVal1 = np.array(np.zeros(1), dtype="int32")
IntVal2 = np.array(np.zeros(1), dtype="int32")
IntVal3 = np.array(np.zeros(1), dtype="int32")
c_z_at_Q = ffi.cast("double *", ffi.from_buffer(data[0]))
c_Qval = ffi.cast("double *", ffi.from_buffer(data[1]))
c_z_cal = ffi.cast("double *", ffi.from_buffer(data[2]))
c_nf_cal = ffi.cast("double *", ffi.from_buffer(data[3]))
c_PC_nf = ffi.cast("double *", ffi.from_buffer(data[4]))
c_PC_deltaz = ffi.cast("double *", ffi.from_buffer(data[5]))
c_int_NQ = ffi.cast("int *", ffi.from_buffer(IntVal1))
c_int_NC = ffi.cast("int *", ffi.from_buffer(IntVal2))
c_int_NP = ffi.cast("int *", ffi.from_buffer(IntVal3))
# Run the C code
errcode = lib.ObtainPhotonConsData(
c_z_at_Q,
c_Qval,
c_int_NQ,
c_z_cal,
c_nf_cal,
c_int_NC,
c_PC_nf,
c_PC_deltaz,
c_int_NP,
)
_process_exitcode(errcode, lib.ObtainPhotonConsData, ())
ArrayIndices = [
IntVal1[0],
IntVal1[0],
IntVal2[0],
IntVal2[0],
IntVal3[0],
IntVal3[0],
]
data_list = [
"z_analytic",
"Q_analytic",
"z_calibration",
"nf_calibration",
"nf_photoncons",
"delta_z_photon_cons",
]
return {name: d[:index] for name, d, index in zip(data_list, data, ArrayIndices)}
def initial_conditions(
*,
user_params=None,
cosmo_params=None,
random_seed=None,
regenerate=None,
write=None,
direc=None,
hooks: Optional[Dict[Callable, Dict[str, Any]]] = None,
**global_kwargs,
) -> InitialConditions:
r"""
Compute initial conditions.
Parameters
----------
user_params : :class:`~UserParams` instance, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams` instance, optional
Defines the cosmological parameters used to compute initial conditions.
regenerate : bool, optional
Whether to force regeneration of data, even if matching cached data is found.
This is applied recursively to any potential sub-calculations. It is ignored in
the case of dependent data only if that data is explicitly passed to the function.
write : bool, optional
Whether to write results to file (i.e. cache). This is recursively applied to
any potential sub-calculations.
hooks
Any extra functions to apply to the output object. This should be a dictionary
where the keys are the functions, and the values are themselves dictionaries of
parameters to pass to the function. The function signature should be
``(output, **params)``, where the ``output`` is the output object.
direc : str, optional
The directory in which to search for the boxes and write them. By default, this
is the directory given by ``boxdir`` in the configuration file,
``~/.21cmfast/config.yml``. This is recursively applied to any potential
sub-calculations.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~InitialConditions`
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
user_params = UserParams(user_params)
cosmo_params = CosmoParams(cosmo_params)
# Initialize memory for the boxes that will be returned.
boxes = InitialConditions(user_params=user_params, cosmo_params=cosmo_params, random_seed=random_seed)
# Construct FFTW wisdoms. Only if required
construct_fftw_wisdoms(user_params=user_params, cosmo_params=cosmo_params)
# First check whether the boxes already exist.
if not regenerate:
try:
boxes.read(direc)
logger.info(f"Existing init_boxes found and read in (seed={boxes.random_seed}).")
return boxes
except OSError:
pass
return boxes.compute(hooks=hooks)
def perturb_field(
*,
redshift,
init_boxes=None,
user_params=None,
cosmo_params=None,
random_seed=None,
regenerate=None,
write=None,
direc=None,
hooks: Optional[Dict[Callable, Dict[str, Any]]] = None,
**global_kwargs,
) -> PerturbedField:
r"""
Compute a perturbed field at a given redshift.
Parameters
----------
redshift : float
The redshift at which to compute the perturbed field.
init_boxes : :class:`~InitialConditions`, optional
If given, these initial conditions boxes will be used, otherwise initial conditions will
be generated. If given,
the user and cosmo params will be set from this object.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~PerturbedField`
Other Parameters
----------------
regenerate, write, direc, random_seed:
See docs of :func:`initial_conditions` for more information.
Examples
--------
The simplest method is just to give a redshift::
>>> field = perturb_field(7.0)
>>> print(field.density)
Doing so will internally call the :func:`~initial_conditions` function. If initial conditions
have already been
calculated, this can be avoided by passing them:
>>> init_boxes = initial_conditions()
>>> field7 = perturb_field(7.0, init_boxes)
>>> field8 = perturb_field(8.0, init_boxes)
The user and cosmo parameter structures are by default inferred from the ``init_boxes``,
so that the following is