-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02_codegen.jl
3414 lines (2807 loc) · 123 KB
/
02_codegen.jl
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
### A Pluto.jl notebook ###
# v0.20.4
using Markdown
using InteractiveUtils
# ╔═╡ 65c19790-a9a8-11ee-06de-ab8cb360a743
let
using Printf, PlutoLinks, Libdl
using ChaosTools, DataFrames, DataFramesMeta, DelimitedFiles, DifferentialEquations, Interpolations, LinearAlgebra, PlutoUI, QuadGK, SpecialFunctions, Symbolics, TikzPictures, Trapz, Unitful, UnitfulAstro
end
# ╔═╡ 37653018-aaf5-42d1-a938-e05a44f18918
# ╠═╡ skip_as_script = true
#=╠═╡
TableOfContents(title="Code generation", depth=4)
╠═╡ =#
# ╔═╡ f028697a-0534-4ccd-8282-1b9a3d8e284b
# ╠═╡ skip_as_script = true
#=╠═╡
md"# Code generation"
╠═╡ =#
# ╔═╡ 4b65fd9c-bd69-4e97-a28c-357c6a9c7bda
# ╠═╡ skip_as_script = true
#=╠═╡
md"### Load the model"
╠═╡ =#
# ╔═╡ a0ca487a-8a51-48cb-acc0-7b318c793d09
const MODEL = @ingredients("./01_model.jl");
# ╔═╡ 33e83e53-1df4-48a9-85fd-17b50c1b1be6
# ╠═╡ skip_as_script = true
#=╠═╡
md"## Paths"
╠═╡ =#
# ╔═╡ 0c6f9d84-30d5-4b4d-8efd-f7414205aa5e
begin
const GEN_FILES = mkpath("./generated_files")
const C_FILES = mkpath(joinpath(GEN_FILES, "c_files"))
# Cosmology
const HUBBLE_CONSTANT = 0.102201 # Hubble constant in Gyr^-1
const OMEGA_0 = 0.307 # The cosmological density parameter for matter
const OMEGA_L = 0.693 # The cosmological density parameter for the cosmological constant
const H0 = 0.6777 # Hubble constant ("little h")
# Paths to the interpolation tables
const ETA_D_TABLE = joinpath(GEN_FILES, "interpolation_tables/eta_d.txt")
const ETA_I_TABLE = joinpath(GEN_FILES, "interpolation_tables/eta_i.txt")
const R_TABLE = joinpath(GEN_FILES, "interpolation_tables/R_Zsn.txt")
const TIME_TABLE = joinpath(GEN_FILES, "interpolation_tables/times.txt")
# Paths to the C libraries (DLLs or SOs)
@static if Sys.iswindows()
const lib_path = joinpath(C_FILES, "lib.dll")
elseif Sys.islinux()
const lib_path = joinpath(C_FILES, "lib.so")
end
end;
# ╔═╡ 73503ce5-c8b4-4f1d-a95c-cc7a307fdb8f
# ╠═╡ skip_as_script = true
#=╠═╡
md"## Header file"
╠═╡ =#
# ╔═╡ 2017166e-2932-48f3-a9e2-f5423f018742
# ╠═╡ skip_as_script = true
#=╠═╡
#####################################################################################
# Write the header file to `path`
#####################################################################################
function write_header_file(path::Union{String,Nothing})::Union{String,Nothing}
header = """
#ifndef EL_SFR_H
#define EL_SFR_H
/* T [internal_units] * T_MYR = T [Myr] */
#define T_MYR (All.UnitTime_in_s / All.HubbleParam / SEC_PER_MEGAYEAR)
/* RHO [internal_units] * RHO_COSMO = RHO [cm^(-3)] */
#define RHO_COSMO (All.UnitDensity_in_cgs * All.HubbleParam * All.HubbleParam * All.cf_a3inv / PROTONMASS)
/* M [internal_units] * M_COSMO = M [Mₒ] */
#define M_COSMO (All.UnitMass_in_g / SOLAR_MASS)
/* Interpolation tables */
#define ETA_NROWS $(length(MODEL.Q_ages) + 1) // Number of rows in the η tables
#define ETA_NCOLS $(length(MODEL.Q_metals) + 1) // Number of columns in the η tables
#define R_NROWS $(length(MODEL.sy_metals)) // Number of rows in the R table
#define R_NCOLS 3 // Number of columns in the R table
/* Paths */
static char *ETA_D_TABLE_PATH = "../code/src/el_sfr/tables/eta_d.txt";
static char *ETA_I_TABLE_PATH = "../code/src/el_sfr/tables/eta_i.txt";
static char *R_TABLE_PATH = "../code/src/el_sfr/tables/R_Zsn.txt";
/* ODE constants */
/* ϵff = $(@sprintf("%.4f", MODEL.ϵff)) (stellar formation efficiency) */
/* Zsun = $(@sprintf("%.4f", MODEL.Zsun)) (solar metallicity) */
/* Cρ = $(@sprintf("%.4f", MODEL.Cρ)) (clumping factor) */
#define N_EQU $(MODEL.N_EQU) /* Number of equations */
#define ODE_CS $(@sprintf("%.7e", MODEL.c_star)) /* [Myr * cm^(-3/2)] */
#define ODE_CR $(@sprintf("%.7e", MODEL.c_rec)) /* [Myr * cm^(-3)] */
#define ODE_CC $(@sprintf("%.7e", MODEL.c_cond)) /* [Myr * cm^(-3)] */
#define ZEFF $(@sprintf("%.4e", MODEL.Zeff)) /* 1e-3 Zₒ */
typedef struct DataTable
{
double *data; // Values of the table
int n_rows; // Number of rows in the table
int n_cols; // Number of columns in the table
} data_table;
#ifdef RHO_PDF
/*
* Density PDF according to Burkhart (2018)
* https://doi.org/10.3847/1538-4357/aad002
*
* We used the following parameters (all dimensionless):
*
* divisions = $(MODEL.PDF_PARAMS.divisions)
* range of ln(rho/rho_0) = $(MODEL.PDF_PARAMS.deviation)
* α (power law slope) = $(MODEL.PDF_PARAMS.α)
* b (turbulent forcing parameter) = $(MODEL.PDF_PARAMS.b)
* Ms (mach number) = $(MODEL.PDF_PARAMS.Ms)
*/
#define DIVISIONS $(MODEL.PDF_PARAMS.divisions)
/* Integrated PDF of the interstellar gas density */
static const double PDF[] = {
$(
[
"\t$(@sprintf("%.10f", MODEL.MASS_FRAC[i])),\n" for
i in 1:MODEL.PDF_PARAMS.divisions
]...
)
};
/* Density factor: ρ = ρ₀ * F_RHO */
static const double F_RHO[] = {
$(
[
"\t$(@sprintf("%.10f", MODEL.F_POINTS[i])),\n" for
i in 1:MODEL.PDF_PARAMS.divisions
]...
)
};
#else /* #ifdef RHO_PDF */
#define DIVISIONS 1
static const double PDF[] = {
1.0,
};
static const double F_RHO[] = {
1.0,
};
#endif /* #ifdef RHO_PDF */
void *read_ftable(const char *file_path, const int n_rows, const int n_cols);
double rate_of_star_formation(const int index, double x);
#endif /* #ifdef EL_SFR_H */
"""
if isnothing(path)
return header
else
mkpath(dirname(path))
open(path, "w") do file
write(file, header)
end
return nothing
end
end;
╠═╡ =#
# ╔═╡ be89676f-0e5a-48c5-b8e3-61b2d7b892a5
#=╠═╡
write_header_file(joinpath(C_FILES, "el_sfr.h"))
╠═╡ =#
# ╔═╡ 7e5980f4-2bcc-4c42-a244-5a8e45df9ae1
# ╠═╡ skip_as_script = true
#=╠═╡
md"## Jacobian"
╠═╡ =#
# ╔═╡ 85d9b763-ded9-4e95-be86-e519abe904d9
# ╠═╡ skip_as_script = true
#=╠═╡
#####################################################################################
# Write the Jacobian to the el_sfr.c file in `path`
#####################################################################################
function write_jacobian(path::String)::Nothing
# Boilerplate
head = """
\n*
* Evaluate the Jacobian matrix of the model, using the following variables:
*
* Ionized gas fraction: fi(t) = Mi(t) / MC --> y[0]
* Atomic gas fraction: fa(t) = Ma(t) / MC --> y[1]
* Molecular gas fraction: fm(t) = Mm(t) / MC --> y[2]
* Stellar fraction: fs(t) = Ms(t) / MC --> y[3]
*
* where MC = Mi(t) + Ma(t) + Mm(t) + Ms(t) is the total density of the gas cell,
* and each equation has units of Myr^(-1).
*
* \\param[in] t Unused variable to comply with the `gsl_odeiv2_driver_alloc_y_new()` API.
* \\param[in] y Values of the variables at which the Jacobian will be evaluated.
* \\param[out] dfdy Where the results of evaluating the Jacobian will be stored.
* \\param[out] dfdt Where the results of evaluating the time derivatives will be stored.
* \\param[in] parameters Parameters for the Jacobian.
*
* \\return Constant `GSL_SUCCESS`, to confirm that the computation was successful.
*/
static int jacobian(double t, const double y[], double *dfdy, double dfdt[], void *parameters)
{
(void)(t);
/*
* Destructure the parameters
*
* rho_C: Total cell density [mp * cm⁻³]
* Z: Metallicity [dimensionless]
* eta_d: Photodissociation efficiency of Hydrogen molecules [dimensionless]
* eta_i: Photoionization efficiency of Hydrogen atoms [dimensionless]
* R: Mass recycling fraction [dimensionless]
*/
double *p = (double *)parameters;
double rho_C = p[0];
double Z = p[1];
double eta_d = p[2];
double eta_i = p[3];
double R = p[4];
gsl_matrix_view dfdy_mat = gsl_matrix_view_array(dfdy, $(MODEL.N_EQU), $(MODEL.N_EQU));
gsl_matrix *m = &dfdy_mat.matrix;
double aux_var = AUX_VAR;
"""
tail = """
dfdt[0] = 0;
dfdt[1] = 0;
dfdt[2] = 0;
dfdt[3] = 0;
return GSL_SUCCESS;
"""
# Create C version of the jacobian
@variables S_t S_ic[1:MODEL.N_EQU] S_parameters[1:MODEL.N_PAR]
S_dydt = Vector{Num}(undef, MODEL.N_EQU)
MODEL.system!(S_dydt, S_ic, S_parameters, S_t)
# Compute the Jacobian symbolically
jac = Symbolics.jacobian(S_dydt, S_ic)
# Regex patterns
aux_var_pattern = r"sqrt\((.*?)rho_C\)"
block_pattern = r"(?<=\{\n )(.*?)(?=\n\}\n)"
jacobian_patern = r"(?<=Evaluate the Jacobian of the systems of equations.)((?s:.)*?)(?=\})"
matrix = ""
@inbounds for i in 1:MODEL.N_EQU
@inbounds for j in 1:MODEL.N_EQU
# Transform the symbolic expresions into C functions
c_function = build_function(
jac[i, j],
S_ic,
S_parameters,
S_t;
target=Symbolics.CTarget(),
)
# Replacements for correct formatting
matrix *= replace(
match(block_pattern, c_function).match,
"du[0] =" => "\tgsl_matrix_set(m, $(i-1), $(j-1),",
";" => ");\n",
)
end
matrix = replace(
matrix,
"RHS1" => "y",
"RHS2[0]" => "rho_C",
"RHS2[1]" => "Z",
"RHS2[2]" => "eta_d",
"RHS2[3]" => "eta_i",
"RHS2[4]" => "R",
"-1 * " => "- ",
"1 " => "1.0 ",
) * "\n"
end
jacobian_string = head * matrix * tail
aux_var_str = match(aux_var_pattern, jacobian_string).match
jacobian_string = replace(
jacobian_string,
aux_var_pattern => "aux_var",
"AUX_VAR" => aux_var_str,
"+ -" => "-",
)
file_with_jacobian = replace(
read(path, String),
jacobian_patern => jacobian_string,
)
write(path, file_with_jacobian)
return nothing
end;
╠═╡ =#
# ╔═╡ 8d718f6f-1ace-4d5a-8c9d-6b1994cb014d
# ╠═╡ skip_as_script = true
#=╠═╡
write_jacobian(joinpath(C_FILES, "el_sfr.c"))
╠═╡ =#
# ╔═╡ e36e8f05-138f-4a8f-be3a-23edbac61304
# ╠═╡ skip_as_script = true
#=╠═╡
md"## Dynamic libraries"
╠═╡ =#
# ╔═╡ a1e9bf3b-8bf9-4425-a57c-61876cfdaa7a
# ╠═╡ skip_as_script = true
#=╠═╡
#####################################################################################
# Compilation of dynamic C libraries for Windows (DLLs) or Linux (SOs)
#####################################################################################
function compile_libraries(path::String)::Nothing
opt_cmd = `gcc -Wall -Wno-unused-variable -fpic -shared -Ofast -march=native -mtune=native -flto`
in_out_cmd = `$(path)/el_sfr.c -o $(lib_path)`
gsl_cmd = `-IC:/msys64/mingw64/include -LC:/msys64/mingw64/lib -lgsl -lgslcblas -lm`
run(`$(opt_cmd) -D EL_SFR -D TESTING $(in_out_cmd) $(gsl_cmd)`)
return nothing
end;
╠═╡ =#
# ╔═╡ c90f69cf-399e-4831-818d-f6d34036b641
# ╠═╡ skip_as_script = true
#=╠═╡
compile_libraries(C_FILES)
╠═╡ =#
# ╔═╡ d4af2366-fa8d-4280-9057-15699d585daa
# ╠═╡ skip_as_script = true
#=╠═╡
md"### GSL ODE solver"
╠═╡ =#
# ╔═╡ 6dbbe165-1177-405d-a3cf-661cf96b265e
#####################################################################################
# Integrate the ODEs using GNU scientific library (GSL)
#####################################################################################
function integrate_with_c(
eta_d_table::String,
eta_i_table::String,
R_table::String,
library::Ptr{Nothing},
)::Function
# Load C functions
integrate_ode = Libdl.dlsym(library, :integrate_ode)
interpolate1D = Libdl.dlsym(library, :interpolate1D)
interpolate2D = Libdl.dlsym(library, :interpolate2D)
# Construct main Julia function
#
# ICs (`ic`):
#
# fi: Ionized gas fraction (of the total cell mass) [dimensionless]
# fa: Atomic gas fraction (of the total cell mass) [dimensionless]
# fm: Molecular gas fraction (of the total cell mass) [dimensionless]
# fs: Stellar fraction (of the total cell mass) [dimensionless]
#
# Parameters (`base_params`):
#
# rho_C: Total cell density [mp * cm⁻³]
# Z: Metallicity [dimensionless]
#
# Integration time (`it`):
#
# it: Integration time in Myr
function integration(
ic::Vector{Float64},
base_params::Vector{Float64},
it::Float64,
)::Vector{Float64}
fractions = zeros(Float64, MODEL.N_EQU)
ρ_cell = base_params[1]
Z = base_params[2]
log_age = log10(it * 10^6)
ηd = @ccall $interpolate2D(
log_age::Cdouble,
Z::Cdouble,
eta_d_table::Cstring,
)::Cdouble
η_ion = @ccall $interpolate2D(
log_age::Cdouble,
Z::Cdouble,
eta_i_table::Cstring,
)::Cdouble
R = @ccall $interpolate1D(
Z::Cdouble,
R_table::Cstring,
length(MODEL.sy_metals)::Cint,
3::Cint,
)::Cdouble
parameters = [ρ_cell, Z, ηd, η_ion, R]
@ccall $integrate_ode(
ic::Ptr{Cdouble},
parameters::Ptr{Cdouble},
it::Cdouble,
fractions::Ptr{Cdouble},
)::Cvoid
return fractions
end
return integration
end;
# ╔═╡ 5eadbd03-da0b-48e1-9027-bc3243389a8d
# ╠═╡ skip_as_script = true
#=╠═╡
md"## Interpolation tables"
╠═╡ =#
# ╔═╡ 65b56c83-f48a-4df5-8e52-326e40c56e78
# ╠═╡ skip_as_script = true
#=╠═╡
md"### Photodissociation efficiency"
╠═╡ =#
# ╔═╡ 8019b753-0c2d-41c9-bed6-01f21635ad81
# ╠═╡ skip_as_script = true
#=╠═╡
#####################################################################################
# Write tables to interpolate η_diss(Z) and η_ion(Z)
#
# Each file is named after the corresponding η
#
# path: Where to store the resulting files
#####################################################################################
function write_η_tables_t_max(path::String)::Nothing
# Allocate memory for the ηs
η_diss = Matrix{Float64}(undef, length(MODEL.Q_metals), 2)
η_ion = Matrix{Float64}(undef, length(MODEL.Q_metals), 2)
η_diss[:, 1] .= [MODEL.Q_metals...]
η_ion[:, 1] .= [MODEL.Q_metals...]
# Set the values of the axes, with an extra point,
# to integrate from age 0 onwards
ages = [0.0, exp10.(MODEL.Q_ages)...] .* u"yr"
@inbounds for (i, Zmet) in pairs(MODEL.Q_metals)
sub_df = @subset(MODEL.Q_by_imf[MODEL.IMF], :Zmet .== Zmet)
q_diss = sub_df[!, :Q_diss]
Q_diss = [q_diss[1], q_diss...]
η_diss[i, 2] = uconvert(
Unitful.NoUnits,
trapz(ages, Q_diss) * MODEL.c_diss,
)
q_ion = sub_df[!, :Q_ion]
Q_ion = [q_ion[1], q_ion...]
η_ion[i, 2] = uconvert(
Unitful.NoUnits,
trapz(ages, Q_ion) * MODEL.c_ion,
)
end
dir = mkpath(path)
writedlm(joinpath(dir, "eta_d.txt"), η_diss, ' ')
writedlm(joinpath(dir, "eta_i.txt"), η_ion, ' ')
return nothing
end;
╠═╡ =#
# ╔═╡ 9a3f2c8a-355a-4470-8c62-aec7e860c383
# ╠═╡ skip_as_script = true
#=╠═╡
write_η_tables_t_max(joinpath(GEN_FILES, "interpolation_tables_t_max"))
╠═╡ =#
# ╔═╡ 0db83126-5520-4438-9f6b-2a6839559787
#####################################################################################
# Write tables to interpolate η_diss(stellar_age, Z) and η_ion(stellar_age, Z)
#
# Each file is named after the corresponding η
#
# path: Where to store the resulting files
#####################################################################################
function write_η_tables(path::String)::Nothing
# Allocate memory for the ηs
η_diss = Matrix{Float64}(
undef,
length(MODEL.Q_ages) + 1, length(MODEL.Q_metals) + 1,
)
η_ion = Matrix{Float64}(
undef,
length(MODEL.Q_ages) + 1, length(MODEL.Q_metals) + 1,
)
η_diss[:, 1] .= [0.0, MODEL.Q_ages...]
η_ion[:, 1] .= [0.0, MODEL.Q_ages...]
η_diss[1, :] .= [0.0, MODEL.Q_metals...]
η_ion[1, :] .= [0.0, MODEL.Q_metals...]
@inbounds for (i, log_age) in pairs(MODEL.Q_ages)
@inbounds for (j, Zmet) in pairs(MODEL.Q_metals)
sub_df = @subset(
MODEL.Q_by_imf[MODEL.IMF],
:Zmet .== Zmet,
:log_age .<= log_age,
)
# Set the values of the axes, with an extra point,
# to integrate from age 0 onwards
ages = [0.0, exp10.(sub_df[!, :log_age])...] .* u"yr"
q_diss = sub_df[!, :Q_diss]
Q_diss = [q_diss[1], q_diss...]
η_diss[i + 1, j + 1] = uconvert(
Unitful.NoUnits,
trapz(ages, Q_diss) * MODEL.c_diss,
)
q_ion = sub_df[!, :Q_ion]
Q_ion = [q_ion[1], q_ion...]
η_ion[i + 1, j + 1] = uconvert(
Unitful.NoUnits,
trapz(ages, Q_ion) * MODEL.c_ion,
)
end
end
dir = mkpath(path)
writedlm(joinpath(dir, "eta_d.txt"), η_diss, ' ')
writedlm(joinpath(dir, "eta_i.txt"), η_ion, ' ')
return nothing
end;
# ╔═╡ 93d71685-815f-4faf-bff8-3bb35945d2bf
write_η_tables(joinpath(GEN_FILES, "interpolation_tables"))
# ╔═╡ 5db32b26-0485-4929-89ec-34c09450555e
# ╠═╡ skip_as_script = true
#=╠═╡
md"### Mass recycling"
╠═╡ =#
# ╔═╡ 871a53c5-82aa-4a4e-9627-c759901e7a89
# ╠═╡ skip_as_script = true
#=╠═╡
#####################################################################################
# Write a table to interpolate R(Z) and Zsn(Z)
#
# The columns are : Z | R | Zsn
#
# path: Where to store the resulting file
#####################################################################################
function write_R_table(path::String)::Nothing
m_low = ustrip(u"Msun", MODEL.M_LOW)
m_high = ustrip(u"Msun", MODEL.M_HIGH)
m_ir = ustrip(u"Msun", MODEL.M_IR)
imf_func = MODEL.imf_funcs[MODEL.IMF][2]
Rs = similar(MODEL.sy_metals)
Zsns = similar(MODEL.sy_metals)
norm = quadgk(m -> m * imf_func(m), m_low, m_high)[1] * u"Msun^2"
sub_df = @subset(
MODEL.sy_data,
:model .== MODEL.yield_model_keys[MODEL.Y_MODEL],
m_ir .* u"Msun" .< :s_m .< m_high .* u"Msun",
)
@inbounds for (i, Z) in pairs(MODEL.sy_metals)
data = @subset(sub_df, :s_Z .== Z)
stellar_mass = data[:, :s_m]
remnant_mass = data[!, :m_rem]
remnant_metal = data[!, :zf_rem]
R_int = trapz(
stellar_mass,
(stellar_mass .- remnant_mass) .* imf_func.(stellar_mass),
)
Zsn_int = trapz(
stellar_mass,
stellar_mass .* remnant_metal .* imf_func.(stellar_mass),
)
Rs[i] = R_int / norm
Zsns[i] = Zsn_int / R_int
end
dir = mkpath(path)
writedlm(joinpath(dir, "R_Zsn.txt"), [MODEL.sy_metals;; Rs;; Zsns])
return nothing
end;
╠═╡ =#
# ╔═╡ d85d8c28-7475-4c26-8bcc-5331fcd06a50
# ╠═╡ skip_as_script = true
#=╠═╡
write_R_table(joinpath(GEN_FILES, "interpolation_tables"))
╠═╡ =#
# ╔═╡ 451d1da4-e7f9-4e49-921f-ed5c83d7c0ad
md"### Times"
# ╔═╡ b944291c-b596-44ac-8d05-9ea7f95debd1
function energyIntegrand(
a::Real,
omega_0::Float64,
omega_l::Float64,
h0::Float64,
)::Float64
# Return 0 if `a` = 0, as the integrand goes to 0 in the limit a -> 0.
!iszero(a) || return 0.0
# Compute Ω_K (curvature)
omega_K = 1.0 - omega_0 - omega_l
# Compute the energy function
E = omega_0 / (a * a * a) + omega_K / (a * a) + omega_l
# Compute the hubble constant in Gyr^-1
H = h0 * HUBBLE_CONSTANT * a
# Return the integrand, in Gyr
return 1.0 / (H * sqrt(E))
end;
# ╔═╡ 3ffec921-db42-4e4e-b840-0109c61f2a84
#####################################################################################
# Write a table to interpolate t(a)
# where t is the physical time in Myr and a the scale factor
#
# The columns are : a | t
#
# path: Where to store the resulting file
#####################################################################################
function write_time_table(
path::String;
ai::Float64=0.0209400379,
af::Float64=1.0,
steps::Int=500,
time_unit::Unitful.Units=u"Myr",
)::Nothing
f = x -> energyIntegrand(x, OMEGA_0, OMEGA_L, H0)
scale_factors = range(ai, af, steps)
times = ustrip.(
time_unit,
[quadgk(f, 0.0, a)[1] * u"Gyr" for a in scale_factors],
)
dir = mkpath(path)
writedlm(joinpath(dir, "times.txt"), [scale_factors;; times])
return nothing
end;
# ╔═╡ 12857745-dec7-4204-a9a5-2ca68ee6eaf9
write_time_table(joinpath(GEN_FILES, "interpolation_tables"))
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
ChaosTools = "608a59af-f2a3-5ad4-90b4-758bdf3122a7"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
DataFramesMeta = "1313f7d8-7da2-5740-9ea0-a2ca25f37964"
DelimitedFiles = "8bb1440f-4735-579b-a4ab-409b98df4dab"
DifferentialEquations = "0c46a032-eb83-5123-abaf-570d42b7fbaa"
Interpolations = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
PlutoLinks = "0ff47ea0-7a50-410d-8455-4348d5de0420"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
QuadGK = "1fd47b50-473d-5c70-9696-f719f8f3bcdc"
SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b"
Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7"
TikzPictures = "37f6aa50-8035-52d0-81c2-5a1d08754b2d"
Trapz = "592b5752-818d-11e9-1e9a-2b8ca4a44cd1"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
UnitfulAstro = "6112ee07-acf9-5e0f-b108-d242c714bf9f"
[compat]
ChaosTools = "~3.2.1"
DataFrames = "~1.7.0"
DataFramesMeta = "~0.15.3"
DelimitedFiles = "~1.9.1"
DifferentialEquations = "~7.14.0"
Interpolations = "~0.15.1"
PlutoLinks = "~0.1.6"
PlutoUI = "~0.7.60"
QuadGK = "~2.11.2"
SpecialFunctions = "~2.5.0"
Symbolics = "~6.11.0"
TikzPictures = "~3.5.0"
Trapz = "~2.0.3"
Unitful = "~1.22.0"
UnitfulAstro = "~1.2.1"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.11.3"
manifest_format = "2.0"
project_hash = "7fba8104164987577d67eeb6e996d72747158afb"
[[deps.ADTypes]]
git-tree-sha1 = "eea5d80188827b35333801ef97a40c2ed653b081"
uuid = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
version = "1.9.0"
weakdeps = ["ChainRulesCore", "EnzymeCore"]
[deps.ADTypes.extensions]
ADTypesChainRulesCoreExt = "ChainRulesCore"
ADTypesEnzymeCoreExt = "EnzymeCore"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.5.0"
weakdeps = ["ChainRulesCore", "Test"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
AbstractFFTsTestExt = "Test"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "6e1d2a35f2f90a4bc7c2ed98079b2ba09c35b83a"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.3.2"
[[deps.AbstractTrees]]
git-tree-sha1 = "2d9c9a55f9c93e8887ad391fbae72f8ef55e1177"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.4.5"
[[deps.Accessors]]
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"]
git-tree-sha1 = "0ba8f4c1f06707985ffb4804fdad1bf97b233897"
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
version = "0.1.41"
[deps.Accessors.extensions]
AxisKeysExt = "AxisKeys"
IntervalSetsExt = "IntervalSets"
LinearAlgebraExt = "LinearAlgebra"
StaticArraysExt = "StaticArrays"
StructArraysExt = "StructArrays"
TestExt = "Test"
UnitfulExt = "Unitful"
[deps.Accessors.weakdeps]
AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Requires = "ae029012-a4dd-5104-9daa-d747884805df"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "50c3c56a52972d78e8be9fd135bfb91c9574c140"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "4.1.1"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.AliasTables]]
deps = ["PtrArrays", "Random"]
git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff"
uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"
version = "1.1.3"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.2"
[[deps.ArnoldiMethod]]
deps = ["LinearAlgebra", "Random", "StaticArrays"]
git-tree-sha1 = "d57bd3762d308bded22c3b82d033bff85f6195c6"
uuid = "ec485272-7323-5ecc-a04f-4719b315124d"
version = "0.4.0"
[[deps.ArrayInterface]]
deps = ["Adapt", "LinearAlgebra"]
git-tree-sha1 = "017fcb757f8e921fb44ee063a7aafe5f89b86dd1"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "7.18.0"
[deps.ArrayInterface.extensions]
ArrayInterfaceBandedMatricesExt = "BandedMatrices"
ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices"
ArrayInterfaceCUDAExt = "CUDA"
ArrayInterfaceCUDSSExt = "CUDSS"
ArrayInterfaceChainRulesCoreExt = "ChainRulesCore"
ArrayInterfaceChainRulesExt = "ChainRules"
ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore"
ArrayInterfaceReverseDiffExt = "ReverseDiff"
ArrayInterfaceSparseArraysExt = "SparseArrays"
ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore"
ArrayInterfaceTrackerExt = "Tracker"
[deps.ArrayInterface.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e"
ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2"
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.ArrayLayouts]]
deps = ["FillArrays", "LinearAlgebra"]
git-tree-sha1 = "492681bc44fac86804706ddb37da10880a2bd528"
uuid = "4c555306-a7a7-4459-81d9-ec55ddd5c99a"
version = "1.10.4"
weakdeps = ["SparseArrays"]
[deps.ArrayLayouts.extensions]
ArrayLayoutsSparseArraysExt = "SparseArrays"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
version = "1.11.0"
[[deps.AxisAlgorithms]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"]
git-tree-sha1 = "01b8ccb13d68535d73d2b0c23e39bd23155fb712"
uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950"
version = "1.1.0"
[[deps.BandedMatrices]]
deps = ["ArrayLayouts", "FillArrays", "LinearAlgebra", "PrecompileTools"]
git-tree-sha1 = "a2c85f53ddcb15b4099da59867868bd40f005579"
uuid = "aae01518-5342-5314-be14-df237901396f"
version = "1.7.5"
weakdeps = ["SparseArrays"]
[deps.BandedMatrices.extensions]
BandedMatricesSparseArraysExt = "SparseArrays"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
version = "1.11.0"
[[deps.Bijections]]
git-tree-sha1 = "d8b0439d2be438a5f2cd68ec158fe08a7b2595b7"
uuid = "e2ed5e7c-b2de-5872-ae92-c73ca462fb04"
version = "0.1.9"
[[deps.BitTwiddlingConvenienceFunctions]]
deps = ["Static"]
git-tree-sha1 = "f21cfd4950cb9f0587d5067e69405ad2acd27b87"
uuid = "62783981-4cbd-42fc-bca8-16325de8dc4b"
version = "0.1.6"
[[deps.BoundaryValueDiffEq]]
deps = ["ADTypes", "Adapt", "ArrayInterface", "BandedMatrices", "ConcreteStructs", "DiffEqBase", "FastAlmostBandedMatrices", "FastClosures", "ForwardDiff", "LinearAlgebra", "LinearSolve", "Logging", "NonlinearSolve", "OrdinaryDiffEq", "PreallocationTools", "PrecompileTools", "Preferences", "RecursiveArrayTools", "Reexport", "SciMLBase", "Setfield", "SparseArrays", "SparseDiffTools"]
git-tree-sha1 = "22f36cc7199c3b0f34979c6925cf8ec05281409f"
uuid = "764a87c0-6b3e-53db-9096-fe964310641d"
version = "5.10.0"
[deps.BoundaryValueDiffEq.extensions]
BoundaryValueDiffEqODEInterfaceExt = "ODEInterface"
[deps.BoundaryValueDiffEq.weakdeps]
ODEInterface = "54ca160b-1b9f-5127-a996-1867f4bc2a2c"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "1b96ea4a01afe0ea4090c5c8039690672dd13f2e"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.9+0"
[[deps.CEnum]]
git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.5.0"
[[deps.CPUSummary]]
deps = ["CpuId", "IfElse", "PrecompileTools", "Static"]
git-tree-sha1 = "5a97e67919535d6841172016c9530fd69494e5ec"
uuid = "2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9"
version = "0.2.6"
[[deps.CRlibm]]
deps = ["CRlibm_jll"]
git-tree-sha1 = "32abd86e3c2025db5172aa182b982debed519834"
uuid = "96374032-68de-5a5b-8d9e-752f78720389"
version = "1.0.1"
[[deps.CRlibm_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e329286945d0cfc04456972ea732551869af1cfc"
uuid = "4e9b3aee-d8a1-5a3d-ad8b-7d824db253f0"
version = "1.0.1+0"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "009060c9a6168704143100f36ab08f06c2af4642"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.18.2+1"
[[deps.Calculus]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "9cb23bbb1127eefb022b022481466c0f1127d430"
uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9"
version = "0.5.2"