cooling.c 48.1 KB
Newer Older
Matthieu Schaller's avatar
Matthieu Schaller committed
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
/*******************************************************************************
 * This file is part of SWIFT.
 * Copyright (c) 2017 Matthieu Schaller (matthieu.schaller@durham.ac.uk)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser 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 Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/
/**
 * @file src/cooling/COLIBRE/cooling.c
 * @brief COLIBRE cooling functions
 */

/* Config parameters. */
#include "../config.h"

/* Some standard headers. */
#include <float.h>
#include <hdf5.h>
#include <math.h>
#include <time.h>

/* Local includes. */
#include "adiabatic_index.h"
#include "chemistry.h"
#include "cooling.h"
#include "cooling_rates.h"
#include "cooling_struct.h"
#include "cooling_subgrid.h"
#include "cooling_tables.h"
#include "entropy_floor.h"
#include "error.h"
#include "exp10.h"
#include "hydro.h"
#include "interpolate.h"
#include "io_properties.h"
#include "parser.h"
#include "part.h"
#include "physical_constants.h"
#include "space.h"
#include "units.h"

/* Maximum number of iterations for
 * bisection integration schemes */
static const int bisection_max_iterations = 150;

/* Tolerances for termination criteria. */
static const float explicit_tolerance = 0.05;
static const float bisection_tolerance = 1.0e-6;
static const double bracket_factor = 1.5;

/**
 * @brief Common operations performed on the cooling function at a
 * given time-step or redshift. Predominantly used to read cooling tables
 * above and below the current redshift, if not already read in.
 *
 * Also calls the additional H reionisation energy injection if need be.
 *
 * @param cosmo The current cosmological model.
 * @param cooling The #cooling_function_data used in the run.
 * @param s The space data, including a pointer to array of particles
 */
void cooling_update(const struct cosmology *cosmo,
                    struct cooling_function_data *cooling, struct space *s) {

  /* Extra energy for reionization? */
  if (!cooling->H_reion_done) {

    /* Does this timestep straddle Hydrogen reionization? If so, we need to
     * input extra heat */
    if (cosmo->z <= cooling->H_reion_z && cosmo->z_old > cooling->H_reion_z) {

      if (s == NULL) error("Trying to do H reionization on an empty space!");

      /* Inject energy to all particles */
      cooling_Hydrogen_reionization(cooling, cosmo, s);

      /* Flag that reionization happened */
      cooling->H_reion_done = 1;
    }
  }
}

/**
 * @brief Compute the internal energy of a #part based on the cooling function
 * but for a given temperature.
 *
 * @param phys_const #phys_const data structure.
 * @param hydro_props The properties of the hydro scheme.
 * @param us The internal system of units.
 * @param cosmo #cosmology data structure.
 * @param cooling #cooling_function_data struct.
 * @param p #part data.
 * @param xp Pointer to the #xpart data.
 * @param T temperature of the gas (internal units).
 */
float cooling_get_internalenergy_for_temperature(
    const struct phys_const *phys_const, const struct hydro_props *hydro_props,
    const struct unit_system *us, const struct cosmology *cosmo,
    const struct cooling_function_data *cooling, const struct part *p,
    const struct xpart *xp, const float T) {

#ifdef SWIFT_DEBUG_CHECKS
  if (cooling->Redshifts == NULL)
    error(
        "Cooling function has not been initialised. Did you forget the "
        "--temperature runtime flag?");
#endif

  /* Get the Hydrogen mass fraction */
  float const *metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Convert Hydrogen mass fraction into Hydrogen number density */
  const float rho = hydro_get_physical_density(p, cosmo);
  const double n_H = rho * XH / phys_const->const_proton_mass;
  const double n_H_cgs = n_H * cooling->number_density_to_cgs;

  /* Get this particle's metallicity ratio to solar.
   *
   * Note that we do not need the individual element's ratios that
   * the function also computes. */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* compute hydrogen number density, metallicity and redshift indices and
   * offsets  */

  float d_red, d_met, d_n_H;
  int red_index, met_index, n_H_index;

  get_index_1d(cooling->Redshifts, colibre_cooling_N_redshifts, cosmo->z,
               &red_index, &d_red);
  get_index_1d(cooling->Metallicity, colibre_cooling_N_metallicity, logZZsol,
               &met_index, &d_met);
  get_index_1d(cooling->nH, colibre_cooling_N_density, log10(n_H_cgs),
               &n_H_index, &d_n_H);

  /* Compute the log10 of the temperature by interpolating the table */
  const double log_10_U =
      colibre_convert_temp_to_u(log10(T), cosmo->z, n_H_index, d_n_H, met_index,
                                d_met, red_index, d_red, cooling);

  /* Undo the log! */
  return exp10(log_10_U);
}

/**
 * @brief Compute the temperature of a #part based on the cooling function.
 *
 * The temperature returned is consistent with the cooling rates.
 *
 * @param phys_const #phys_const data structure.
 * @param hydro_props The properties of the hydro scheme.
 * @param us The internal system of units.
 * @param cosmo #cosmology data structure.
 * @param cooling #cooling_function_data struct.
 * @param p #part data.
 * @param xp Pointer to the #xpart data.
 */
float cooling_get_temperature(const struct phys_const *phys_const,
                              const struct hydro_props *hydro_props,
                              const struct unit_system *us,
                              const struct cosmology *cosmo,
                              const struct cooling_function_data *cooling,
                              const struct part *p, const struct xpart *xp) {

#ifdef SWIFT_DEBUG_CHECKS
  if (cooling->Redshifts == NULL)
    error(
        "Cooling function has not been initialised. Did you forget the "
        "--temperature runtime flag?");
#endif

  /* Get physical internal energy */
  const float u = hydro_get_physical_internal_energy(p, xp, cosmo);
  const double u_cgs = u * cooling->internal_energy_to_cgs;

  /* Get the Hydrogen mass fraction */
  float const *metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Convert Hydrogen mass fraction into Hydrogen number density */
  const float rho = hydro_get_physical_density(p, cosmo);
  const double n_H = rho * XH / phys_const->const_proton_mass;
  const double n_H_cgs = n_H * cooling->number_density_to_cgs;

  /* Get this particle's metallicity ratio to solar.
   *
   * Note that we do not need the individual element's ratios that
   * the function also computes. */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* compute hydrogen number density, metallicity and redshift indices and
   * offsets  */

  float d_red, d_met, d_n_H;
  int red_index, met_index, n_H_index;

  get_index_1d(cooling->Redshifts, colibre_cooling_N_redshifts, cosmo->z,
               &red_index, &d_red);
  get_index_1d(cooling->Metallicity, colibre_cooling_N_metallicity, logZZsol,
               &met_index, &d_met);
  get_index_1d(cooling->nH, colibre_cooling_N_density, log10(n_H_cgs),
               &n_H_index, &d_n_H);

  /* Compute the log10 of the temperature by interpolating the table */
  const double log_10_T =
      colibre_convert_u_to_temp(log10(u_cgs), cosmo->z, n_H_index, d_n_H,
                                met_index, d_met, red_index, d_red, cooling);

  /* Undo the log! */
  return exp10(log_10_T);
}

/**
 * @brief Bisection integration scheme
 *
 * @param u_ini_cgs Internal energy at beginning of hydro step in CGS.
 * @param n_H_cgs Hydrogen number density in CGS.
 * @param redshift Current redshift.
 * @param n_H_index Particle hydrogen number density index.
 * @param d_n_H Particle hydrogen number density offset.
 * @param met_index Particle metallicity index.
 * @param d_met Particle metallicity offset.
 * @param red_index Redshift index.
 * @param d_red Redshift offset.
 * @param Lambda_He_reion_cgs Cooling rate coming from He reionization.
 * @param ratefact_cgs Multiplication factor to get a cooling rate.
 * @param cooling #cooling_function_data structure.
 * @param abundance_ratio Array of ratios of metal abundance to solar.
 * @param dt_cgs timestep in CGS.
 * @param ID ID of the particle (for debugging).
 */
static INLINE double bisection_iter(
    const double u_ini_cgs, const double n_H_cgs, const double redshift,
    int n_H_index, float d_n_H, int met_index, float d_met, int red_index,
    float d_red, double Lambda_He_reion_cgs, double ratefact_cgs,
    const struct cooling_function_data *cooling,
    const float abundance_ratio[colibre_cooling_N_elementtypes], double dt_cgs,
    long long ID) {

  /* Bracketing */
  double u_lower_cgs = max(u_ini_cgs, cooling->umin_cgs);
  double u_upper_cgs = max(u_ini_cgs, cooling->umin_cgs);

  /*************************************/
  /* Let's get a first guess           */
  /*************************************/

  double LambdaNet_cgs =
      Lambda_He_reion_cgs +
      colibre_cooling_rate(log10(u_ini_cgs), redshift, n_H_cgs, abundance_ratio,
                           n_H_index, d_n_H, met_index, d_met, red_index, d_red,
                           cooling, 0, 0, 0, 0);

  /*************************************/
  /* Let's try to bracket the solution */
  /*************************************/

  if (LambdaNet_cgs < 0) {

    /* we're cooling! */
    u_lower_cgs = max(u_lower_cgs / bracket_factor, cooling->umin_cgs);
    u_upper_cgs = max(u_upper_cgs * bracket_factor, cooling->umin_cgs);

    /* Compute a new rate */
    LambdaNet_cgs =
        Lambda_He_reion_cgs +
        colibre_cooling_rate(log10(u_lower_cgs), redshift, n_H_cgs,
                             abundance_ratio, n_H_index, d_n_H, met_index,
                             d_met, red_index, d_red, cooling, 0, 0, 0, 0);

    int i = 0;
    while (u_lower_cgs - u_ini_cgs - LambdaNet_cgs * ratefact_cgs * dt_cgs >
               0 &&
           i < bisection_max_iterations) {

      u_lower_cgs = max(u_lower_cgs / bracket_factor, cooling->umin_cgs);
      u_upper_cgs = max(u_upper_cgs / bracket_factor, cooling->umin_cgs);

      /* Compute a new rate */
      LambdaNet_cgs =
          Lambda_He_reion_cgs +
          colibre_cooling_rate(log10(u_lower_cgs), redshift, n_H_cgs,
                               abundance_ratio, n_H_index, d_n_H, met_index,
                               d_met, red_index, d_red, cooling, 0, 0, 0, 0);

      /* If the energy is below or equal the minimum energy and we are still
       * cooling, return the minimum energy */
      if ((u_lower_cgs <= cooling->umin_cgs) && (LambdaNet_cgs < 0.))
        return cooling->umin_cgs;

      i++;
    }

    if (i >= bisection_max_iterations) {
      error(
          "particle %llu exceeded max iterations searching for bounds when "
          "cooling \n more info: n_H_cgs = %.4e, u_ini_cgs = %.4e, redshift = "
          "%.4f\n"
          "n_H_index = %i, d_n_H = %.4f\n"
          "met_index = %i, d_met = %.4f, red_index = %i, d_red = %.4f, initial "
          "Lambda = %.4e",
          ID, n_H_cgs, u_ini_cgs, redshift, n_H_index, d_n_H, met_index, d_met,
          red_index, d_red,
          colibre_cooling_rate(log10(u_ini_cgs), redshift, n_H_cgs,
                               abundance_ratio, n_H_index, d_n_H, met_index,
                               d_met, red_index, d_red, cooling, 0, 0, 0, 0));
    }
  } else {

    /* we are heating! */
    u_lower_cgs /= bracket_factor;
    u_upper_cgs *= bracket_factor;

    /* Compute a new rate */
    LambdaNet_cgs =
        Lambda_He_reion_cgs +
        colibre_cooling_rate(log10(u_upper_cgs), redshift, n_H_cgs,
                             abundance_ratio, n_H_index, d_n_H, met_index,
                             d_met, red_index, d_red, cooling, 0, 0, 0, 0);

    int i = 0;
    while (u_upper_cgs - u_ini_cgs - LambdaNet_cgs * ratefact_cgs * dt_cgs <
               0 &&
           i < bisection_max_iterations) {

      u_lower_cgs *= bracket_factor;
      u_upper_cgs *= bracket_factor;

      /* Compute a new rate */
      LambdaNet_cgs =
          Lambda_He_reion_cgs +
          colibre_cooling_rate(log10(u_upper_cgs), redshift, n_H_cgs,
                               abundance_ratio, n_H_index, d_n_H, met_index,
                               d_met, red_index, d_red, cooling, 0, 0, 0, 0);
      i++;
    }

    if (i >= bisection_max_iterations) {
      message("Aborting...");
      message("particle %llu", ID);
      message("n_H_cgs = %.4e", n_H_cgs);
      message("u_ini_cgs = %.4e", u_ini_cgs);
      message("redshift = %.4f", redshift);
      message("indices nH, met, red = %i, %i, %i", n_H_index, met_index,
              red_index);
      message("index weights nH, met, red = %.4e, %.4e, %.4e", d_n_H, d_met,
              d_red);
      fflush(stdout);
      message(
          "cooling rate = %.4e",
          colibre_cooling_rate(log10(u_ini_cgs), redshift, n_H_cgs,
                               abundance_ratio, n_H_index, d_n_H, met_index,
                               d_met, red_index, d_red, cooling, 0, 0, 0, 0));
      error(
          "particle %llu exceeded max iterations searching for bounds when "
          "cooling",
          ID);
    }
  }

  /********************************************/
  /* We now have an upper and lower bound.    */
  /* Let's iterate by reducing the bracketing */
  /********************************************/

  /* bisection iteration */
  int i = 0;
  double u_next_cgs;

  do {

    /* New guess */
    u_next_cgs = 0.5 * (u_lower_cgs + u_upper_cgs);

    /* New rate */
    LambdaNet_cgs =
        Lambda_He_reion_cgs +
        colibre_cooling_rate(log10(u_next_cgs), redshift, n_H_cgs,
                             abundance_ratio, n_H_index, d_n_H, met_index,
                             d_met, red_index, d_red, cooling, 0, 0, 0, 0);

    /* Where do we go next? */
    if (u_next_cgs - u_ini_cgs - LambdaNet_cgs * ratefact_cgs * dt_cgs > 0.0) {
      u_upper_cgs = u_next_cgs;
    } else {
      u_lower_cgs = u_next_cgs;
    }

    i++;
  } while (fabs(u_upper_cgs - u_lower_cgs) / u_next_cgs > bisection_tolerance &&
           i < bisection_max_iterations);

  if (i >= bisection_max_iterations)
    error("Particle id %llu failed to converge", ID);

  return u_upper_cgs;
}

/**
 * @brief Apply the cooling function to a particle.
 *
 * We want to compute u_new such that u_new = u_old + dt * du/dt(u_new, X),
 * where X stands for the metallicity, density and redshift. These are
 * kept constant.
 *
 * We first compute du/dt(u_old). If dt * du/dt(u_old) is small enough, we
 * use an explicit integration and use this as our solution.
 *
 * Otherwise, we try to find a solution to the implicit time-integration
 * problem. This leads to the root-finding problem:
 *
 * f(u_new) = u_new - u_old - dt * du/dt(u_new, X) = 0
 *
 * A bisection scheme is used.
 * This is done by first bracketing the solution and then iterating
 * towards the solution by reducing the window down to a certain tolerance.
 * Note there is always at least one solution since
 * f(+inf) is < 0 and f(-inf) is > 0.
 *
 * @param phys_const The physical constants in internal units.
 * @param us The internal system of units.
 * @param cosmo The current cosmological model.
 * @param hydro_properties the hydro_props struct
 * @param floor_props Properties of the entropy floor.
 * @param cooling The #cooling_function_data used in the run.
 * @param p Pointer to the particle data.
 * @param xp Pointer to the extended particle data.
 * @param dt The cooling time-step of this particle.
 * @param dt_therm The hydro time-step of this particle.
 * @param time Time since Big Bang
 */
void cooling_cool_part(const struct phys_const *phys_const,
                       const struct unit_system *us,
                       const struct cosmology *cosmo,
                       const struct hydro_props *hydro_properties,
                       const struct entropy_floor_properties *floor_props,
                       const struct cooling_function_data *cooling,
                       struct part *p, struct xpart *xp, const float dt,
                       const float dt_therm, const double time) {

  /* No cooling happens over zero time */
  if (dt == 0.) {

    /* But we still set the subgrid properties to a valid state */
    cooling_set_subgrid_properties(phys_const, us, cosmo, hydro_properties,
                                   floor_props, cooling, p, xp);

    return;
  }

#ifdef SWIFT_DEBUG_CHECKS
  if (cooling->Redshifts == NULL)
    error(
        "Cooling function has not been initialised. Did you forget the "
        "--cooling runtime flag?");
#endif

  /* Get internal energy at the last kick step */
  const float u_start = hydro_get_physical_internal_energy(p, xp, cosmo);

  /* Get the change in internal energy due to hydro forces */
  const float hydro_du_dt = hydro_get_physical_internal_energy_dt(p, cosmo);

  /* Get internal energy at the end of the next kick step (assuming dt does not
   * increase) */
  double u_0 = (u_start + hydro_du_dt * dt_therm);

  /* Check for minimal energy */
  u_0 = max(u_0, hydro_properties->minimal_internal_energy);

  /* Convert to CGS units */
  const double u_0_cgs = u_0 * cooling->internal_energy_to_cgs;
  const double dt_cgs = dt * units_cgs_conversion_factor(us, UNIT_CONV_TIME);

  /* Change in redshift over the course of this time-step
     (See cosmology theory document for the derivation) */
  const double delta_redshift = -dt * cosmo->H * cosmo->a_inv;

  /* Get this particle's abundance ratios compared to solar
   * Note that we need to add S and Ca that are in the tables but not tracked
   * by the particles themselves.
   * The order is [H, He, C, N, O, Ne, Mg, Si, S, Ca, Fe, OA] */
  float abundance_ratio[colibre_cooling_N_elementtypes];
  float logZZsol = abundance_ratio_to_solar(p, cooling, abundance_ratio);

  /* Get the Hydrogen and Helium mass fractions */
  float const *metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* convert Hydrogen mass fraction into Hydrogen number density */
  const double n_H =
      hydro_get_physical_density(p, cosmo) * XH / phys_const->const_proton_mass;
  const double n_H_cgs = n_H * cooling->number_density_to_cgs;

  /* ratefact = n_H * n_H / rho; Might lead to round-off error: replaced by
   * equivalent expression  below */
  const double ratefact_cgs = n_H_cgs * (XH * cooling->inv_proton_mass_cgs);

  /* compute hydrogen number density, metallicity and redshift indices and
   * offsets (These are fixed for any value of u, so no need to recompute them)
   */

  float d_red, d_met, d_n_H;
  int red_index, met_index, n_H_index;

  get_index_1d(cooling->Redshifts, colibre_cooling_N_redshifts, cosmo->z,
               &red_index, &d_red);
  get_index_1d(cooling->Metallicity, colibre_cooling_N_metallicity, logZZsol,
               &met_index, &d_met);
  get_index_1d(cooling->nH, colibre_cooling_N_density, log10(n_H_cgs),
               &n_H_index, &d_n_H);

  /* Start by computing the cooling (heating actually) rate from Helium
     re-ionization as this needs to be added on no matter what */

  /* Get helium and hydrogen reheating term */
  const double Helium_reion_heat_cgs =
      eagle_helium_reionization_extraheat(cosmo->z, delta_redshift, cooling);

  /* Convert this into a rate */
  const double Lambda_He_reion_cgs =
      Helium_reion_heat_cgs / (dt_cgs * ratefact_cgs);

  /* Let's compute the internal energy at the end of the step */
  double u_final_cgs;

  /* First try an explicit integration (note we ignore the derivative) */
  const double LambdaNet_cgs =
      Lambda_He_reion_cgs +
      colibre_cooling_rate(log10(u_0_cgs), cosmo->z, n_H_cgs, abundance_ratio,
                           n_H_index, d_n_H, met_index, d_met, red_index, d_red,
                           cooling, 0, 0, 0, 0);

  /* if cooling rate is small, take the explicit solution */
  if (fabs(ratefact_cgs * LambdaNet_cgs * dt_cgs) <
      explicit_tolerance * u_0_cgs) {

    u_final_cgs = u_0_cgs + ratefact_cgs * LambdaNet_cgs * dt_cgs;

  } else {

    u_final_cgs =
        bisection_iter(u_0_cgs, n_H_cgs, cosmo->z, n_H_index, d_n_H, met_index,
                       d_met, red_index, d_red, Lambda_He_reion_cgs,
                       ratefact_cgs, cooling, abundance_ratio, dt_cgs, p->id);
  }

  /* Convert back to internal units */
  double u_final = u_final_cgs * cooling->internal_energy_from_cgs;

  /* We now need to check that we are not going to go below any of the limits */

  /* Absolute minimum */
  const double u_minimal = hydro_properties->minimal_internal_energy;
  u_final = max(u_final, u_minimal);

  /* Limit imposed by the entropy floor */
  const double A_floor = entropy_floor(p, cosmo, floor_props);
  const double rho_physical = hydro_get_physical_density(p, cosmo);
  const double u_floor =
      gas_internal_energy_from_entropy(rho_physical, A_floor);
  u_final = max(u_final, u_floor);

  /* Expected change in energy over the next kick step
     (assuming no change in dt) */
  const double delta_u = u_final - max(u_start, u_floor);

  /* Determine if we are in the slow- or rapid-cooling regime,
   * by comparing dt / t_cool to the rapid_cooling_threshold.
   *
   * Note that dt / t_cool = fabs(delta_u) / u_start. */
  const double dt_over_t_cool = fabs(delta_u) / max(u_start, u_floor);

  /* If rapid_cooling_threshold < 0, always use the slow-cooling
   * regime. */
  if ((cooling->rapid_cooling_threshold >= 0.0) &&
      (dt_over_t_cool >= cooling->rapid_cooling_threshold)) {

    /* Rapid-cooling regime. */

    /* Update the particle's u and du/dt */
    hydro_set_physical_internal_energy(p, xp, cosmo, u_final);
    hydro_set_drifted_physical_internal_energy(p, cosmo, u_final);
    hydro_set_physical_internal_energy_dt(p, cosmo, 0.);

  } else {

    /* Slow-cooling regime. */

    /* Update du/dt so that we can subsequently drift internal energy. */
    const float cooling_du_dt = delta_u / dt_therm;

    /* Update the internal energy time derivative */
    hydro_set_physical_internal_energy_dt(p, cosmo, cooling_du_dt);
  }

  /* Store the radiated energy */
  xp->cooling_data.radiated_energy -= hydro_get_mass(p) * (u_final - u_0);

  /* set subgrid properties and hydrogen fractions */
  cooling_set_subgrid_properties(phys_const, us, cosmo, hydro_properties,
                                 floor_props, cooling, p, xp);
}

/**
 * @brief Computes the cooling time-step.
 *
 * The time-step is not set by the properties of cooling.
 *
 * @param cooling The #cooling_function_data used in the run.
 * @param phys_const #phys_const data struct.
 * @param us The internal system of units.
 * @param cosmo #cosmology struct.
 * @param hydro_props the properties of the hydro scheme.
 * @param p #part data.
 * @param xp extended particle data.
 */
__attribute__((always_inline)) INLINE float cooling_timestep(
    const struct cooling_function_data *cooling,
    const struct phys_const *phys_const, const struct cosmology *cosmo,
    const struct unit_system *us, const struct hydro_props *hydro_props,
    const struct part *p, const struct xpart *xp) {

  return FLT_MAX;
}

/**
 * @brief Sets the cooling properties of the (x-)particles to a valid start
 * state.
 *
 * @param phys_const #phys_const data structure.
 * @param us The internal system of units.
650
 * @param hydro_props The properties of the hydro scheme.
Matthieu Schaller's avatar
Matthieu Schaller committed
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
 * @param cosmo #cosmology data structure.
 * @param cooling #cooling_function_data struct.
 * @param p #part data.
 * @param xp Pointer to the #xpart data.
 */
__attribute__((always_inline)) INLINE void cooling_first_init_part(
    const struct phys_const *phys_const, const struct unit_system *us,
    const struct hydro_props *hydro_props, const struct cosmology *cosmo,
    const struct cooling_function_data *cooling, struct part *p,
    struct xpart *xp) {

  xp->cooling_data.radiated_energy = 0.f;
  p->cooling_data.subgrid_temp = -1.f;
  p->cooling_data.subgrid_dens = -1.f;
}

/**
 * @brief Compute the fraction of Hydrogen that is in HI based
 * on the pressure of the gas.
 *
 * For particles on the entropy floor, we use pressure equilibrium to
 * infer the properties of the particle.
 *
 * @param us The internal system of units.
 * @param phys_const The physical constants.
 * @param hydro_props The properties of the hydro scheme.
 * @param cosmo The cosmological model.
 * @param floor_props The properties of the entropy floor.
 * @param cooling The properties of the cooling scheme.
 * @param p The #part.
 * @param xp The #xpart.
 */
float cooling_get_subgrid_HI_fraction(
    const struct unit_system *us, const struct phys_const *phys_const,
    const struct cosmology *cosmo, const struct hydro_props *hydro_props,
    const struct entropy_floor_properties *floor_props,
    const struct cooling_function_data *cooling, const struct part *p,
    const struct xpart *xp) {

  /* Get the EOS temperature from the entropy floor */
  const float T_EOS = entropy_floor_temperature(p, cosmo, floor_props);
  const float log10_T_EOS_max =
      log10f(max(T_EOS, FLT_MIN)) + cooling->dlogT_EOS;

  /* Get the particle's temperature */
  const float T = cooling_get_temperature(phys_const, hydro_props, us, cosmo,
                                          cooling, p, xp);
  const float log10_T = log10f(T);

700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
  /* Physical density of this particle */
  const float rho_phys = hydro_get_physical_density(p, cosmo);

  /* Get the total metallicity in units of solar */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* Get the Hydrogen abundance */
  const float *const metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Get the particle pressure */
  const float P_phys = hydro_get_physical_pressure(p, cosmo);

  return compute_subgrid_HI_fraction(cooling, phys_const, floor_props, cosmo,
                                     rho_phys, logZZsol, XH, P_phys, log10_T,
                                     log10_T_EOS_max);
Matthieu Schaller's avatar
Matthieu Schaller committed
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
}

/**
 * @brief Compute the fraction of Hydrogen that is in HII based
 * on the pressure of the gas.
 *
 * For particles on the entropy floor, we use pressure equilibrium to
 * infer the properties of the particle.
 *
 * @param us The internal system of units.
 * @param phys_const The physical constants.
 * @param hydro_props The properties of the hydro scheme.
 * @param cosmo The cosmological model.
 * @param floor_props The properties of the entropy floor.
 * @param cooling The properties of the cooling scheme.
 * @param p The #part.
 * @param xp The #xpart.
 */
float cooling_get_subgrid_HII_fraction(
    const struct unit_system *us, const struct phys_const *phys_const,
    const struct cosmology *cosmo, const struct hydro_props *hydro_props,
    const struct entropy_floor_properties *floor_props,
    const struct cooling_function_data *cooling, const struct part *p,
    const struct xpart *xp) {

  /* Get the EOS temperature from the entropy floor */
  const float T_EOS = entropy_floor_temperature(p, cosmo, floor_props);
  const float log10_T_EOS_max =
      log10f(max(T_EOS, FLT_MIN)) + cooling->dlogT_EOS;

  /* Get the particle's temperature */
  const float T = cooling_get_temperature(phys_const, hydro_props, us, cosmo,
                                          cooling, p, xp);
  const float log10_T = log10f(T);

753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
  /* Physical density of this particle */
  const float rho_phys = hydro_get_physical_density(p, cosmo);

  /* Get the total metallicity in units of solar */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* Get the Hydrogen abundance */
  const float *const metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Get the particle pressure */
  const float P_phys = hydro_get_physical_pressure(p, cosmo);

Matthieu Schaller's avatar
Matthieu Schaller committed
768
  return compute_subgrid_HII_fraction(cooling, phys_const, floor_props, cosmo,
769
770
                                      rho_phys, logZZsol, XH, P_phys, log10_T,
                                      log10_T_EOS_max);
Matthieu Schaller's avatar
Matthieu Schaller committed
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
}

/**
 * @brief Compute the fraction of Hydrogen that is in H2 based
 * on the pressure of the gas.
 *
 * For particles on the entropy floor, we use pressure equilibrium to
 * infer the properties of the particle.
 *
 * @param us The internal system of units.
 * @param phys_const The physical constants.
 * @param hydro_props The properties of the hydro scheme.
 * @param cosmo The cosmological model.
 * @param floor_props The properties of the entropy floor.
 * @param cooling The properties of the cooling scheme.
 * @param p The #part.
 * @param xp The #xpart.
 */
float cooling_get_subgrid_H2_fraction(
    const struct unit_system *us, const struct phys_const *phys_const,
    const struct cosmology *cosmo, const struct hydro_props *hydro_props,
    const struct entropy_floor_properties *floor_props,
    const struct cooling_function_data *cooling, const struct part *p,
    const struct xpart *xp) {

  /* Get the EOS temperature from the entropy floor */
  const float T_EOS = entropy_floor_temperature(p, cosmo, floor_props);
  const float log10_T_EOS_max =
      log10f(max(T_EOS, FLT_MIN)) + cooling->dlogT_EOS;

  /* Get the particle's temperature */
  const float T = cooling_get_temperature(phys_const, hydro_props, us, cosmo,
                                          cooling, p, xp);
  const float log10_T = log10f(T);

806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
  /* Physical density of this particle */
  const float rho_phys = hydro_get_physical_density(p, cosmo);

  /* Get the total metallicity in units of solar */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* Get the Hydrogen abundance */
  const float *const metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Get the particle pressure */
  const float P_phys = hydro_get_physical_pressure(p, cosmo);

  return compute_subgrid_H2_fraction(cooling, phys_const, floor_props, cosmo,
                                     rho_phys, logZZsol, XH, P_phys, log10_T,
                                     log10_T_EOS_max);
Matthieu Schaller's avatar
Matthieu Schaller committed
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
}

/**
 * @brief Compute the temperature of the gas.
 *
 * For particles on the entropy floor, we use pressure equilibrium to
 * infer the properties of the particle.
 *
 * @param us The internal system of units.
 * @param phys_const The physical constants.
 * @param hydro_props The properties of the hydro scheme.
 * @param cosmo The cosmological model.
 * @param floor_props The properties of the entropy floor.
 * @param cooling The properties of the cooling scheme.
 * @param p The #part.
 * @param xp The #xpart.
 */
float cooling_get_subgrid_temperature(
    const struct unit_system *us, const struct phys_const *phys_const,
    const struct cosmology *cosmo, const struct hydro_props *hydro_props,
    const struct entropy_floor_properties *floor_props,
    const struct cooling_function_data *cooling, const struct part *p,
    const struct xpart *xp) {

  /* Get the EOS temperature from the entropy floor */
  const float T_EOS = entropy_floor_temperature(p, cosmo, floor_props);
  const float log10_T_EOS_max =
      log10f(max(T_EOS, FLT_MIN)) + cooling->dlogT_EOS;

  /* Get the particle's temperature */
  const float T = cooling_get_temperature(phys_const, hydro_props, us, cosmo,
                                          cooling, p, xp);
  const float log10_T = log10f(T);

858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
  /* Physical density of this particle */
  const float rho_phys = hydro_get_physical_density(p, cosmo);

  /* Get the total metallicity in units of solar */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* Get the Hydrogen abundance */
  const float *const metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Get the particle pressure */
  const float P_phys = hydro_get_physical_pressure(p, cosmo);

  return compute_subgrid_temperature(cooling, phys_const, floor_props, cosmo,
                                     rho_phys, logZZsol, XH, P_phys, log10_T,
                                     log10_T_EOS_max);
Matthieu Schaller's avatar
Matthieu Schaller committed
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
}

/**
 * @brief Compute the physical density of the gas.
 *
 * For particles on the entropy floor, we use pressure equilibrium to
 * infer the properties of the particle.
 *
 * Note that we return the density in physical coordinates.
 *
 * @param us The internal system of units.
 * @param phys_const The physical constants.
 * @param hydro_props The properties of the hydro scheme.
 * @param cosmo The cosmological model.
 * @param floor_props The properties of the entropy floor.
 * @param cooling The properties of the cooling scheme.
 * @param p The #part.
 * @param xp The #xpart.
 */
float cooling_get_subgrid_density(
    const struct unit_system *us, const struct phys_const *phys_const,
    const struct cosmology *cosmo, const struct hydro_props *hydro_props,
    const struct entropy_floor_properties *floor_props,
    const struct cooling_function_data *cooling, const struct part *p,
    const struct xpart *xp) {

  /* Get the EOS temperature from the entropy floor */
  const float T_EOS = entropy_floor_temperature(p, cosmo, floor_props);
  const float log10_T_EOS_max =
      log10f(max(T_EOS, FLT_MIN)) + cooling->dlogT_EOS;

  /* Get the particle's temperature */
  const float T = cooling_get_temperature(phys_const, hydro_props, us, cosmo,
                                          cooling, p, xp);
  const float log10_T = log10f(T);

912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
  /* Physical density of this particle */
  const float rho_phys = hydro_get_physical_density(p, cosmo);

  /* Get the total metallicity in units of solar */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* Get the Hydrogen abundance */
  const float *const metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Get the particle pressure */
  const float P_phys = hydro_get_physical_pressure(p, cosmo);

  return compute_subgrid_density(cooling, phys_const, floor_props, cosmo,
                                 rho_phys, logZZsol, XH, P_phys, log10_T,
                                 log10_T_EOS_max);
Matthieu Schaller's avatar
Matthieu Schaller committed
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
}

/**
 * @brief Set the subgrid properties (rho, T) of the gas particle
 *
 * @param phys_const The physical constants in internal units.
 * @param us The internal system of units.
 * @param cosmo The current cosmological model.
 * @param hydro_props the hydro_props struct
 * @param floor_props Properties of the entropy floor.
 * @param cooling The #cooling_function_data used in the run.
 * @param p Pointer to the particle data.
 * @param xp Pointer to the extended particle data.
 */
void cooling_set_subgrid_properties(
    const struct phys_const *phys_const, const struct unit_system *us,
    const struct cosmology *cosmo, const struct hydro_props *hydro_props,
    const struct entropy_floor_properties *floor_props,
    const struct cooling_function_data *cooling, struct part *p,
    struct xpart *xp) {

  /* Get the EOS temperature from the entropy floor */
  const float T_EOS = entropy_floor_temperature(p, cosmo, floor_props);
  const float log10_T_EOS_max =
      log10f(max(T_EOS, FLT_MIN)) + cooling->dlogT_EOS;

  /* Get the particle's temperature */
  const float T = cooling_get_temperature(phys_const, hydro_props, us, cosmo,
                                          cooling, p, xp);
  const float log10_T = log10f(T);

961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
  /* Physical density of this particle */
  const float rho_phys = hydro_get_physical_density(p, cosmo);

  /* Get the total metallicity in units of solar */
  float dummy[colibre_cooling_N_elementtypes];
  const float logZZsol = abundance_ratio_to_solar(p, cooling, dummy);

  /* Get the Hydrogen abundance */
  const float *const metal_fraction =
      chemistry_get_metal_mass_fraction_for_cooling(p);
  const float XH = metal_fraction[chemistry_element_H];

  /* Get the particle pressure */
  const float P_phys = hydro_get_physical_pressure(p, cosmo);

Matthieu Schaller's avatar
Matthieu Schaller committed
976
  p->cooling_data.subgrid_temp = compute_subgrid_temperature(
977
978
979
980
981
      cooling, phys_const, floor_props, cosmo, rho_phys, logZZsol, XH, P_phys,
      log10_T, log10_T_EOS_max);
  p->cooling_data.subgrid_dens =
      compute_subgrid_density(cooling, phys_const, floor_props, cosmo, rho_phys,
                              logZZsol, XH, P_phys, log10_T, log10_T_EOS_max);
Matthieu Schaller's avatar
Matthieu Schaller committed
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
}

/**
 * @brief Returns the total radiated energy by this particle.
 *
 * @param xp #xpart data struct
 */
__attribute__((always_inline)) INLINE float cooling_get_radiated_energy(
    const struct xpart *xp) {

  return xp->cooling_data.radiated_energy;
}

/**
 * @brief Split the coolong content of a particle into n pieces
 *
 * @param p The #part.
 * @param xp The #xpart.
 * @param n The number of pieces to split into.
 */
void cooling_split_part(struct part *p, struct xpart *xp, double n) {

  xp->cooling_data.radiated_energy /= n;
}

/**
 * @brief Inject a fixed amount of energy to each particle in the simulation
 * to mimic Hydrogen reionization.
 *
 * @param cooling The properties of the cooling model.
 * @param cosmo The cosmological model.
 * @param s The #space containing the particles.
 */
void cooling_Hydrogen_reionization(const struct cooling_function_data *cooling,
                                   const struct cosmology *cosmo,
                                   struct space *s) {

  struct part *parts = s->parts;
  struct xpart *xparts = s->xparts;

  /* Energy to inject in internal units */
  const float extra_heat =
      cooling->H_reion_heat_cgs * cooling->internal_energy_from_cgs;

  message("Applying extra energy for H reionization to non-star-forming gas!");

  /* Loop through particles and set new heat */
  for (size_t i = 0; i < s->nr_parts; i++) {

    struct part *p = &parts[i];
    struct xpart *xp = &xparts[i];

    if (xp->sf_data.SFR <= 0.) {
      const float old_u = hydro_get_physical_internal_energy(p, xp, cosmo);
      const float new_u = old_u + extra_heat;

      hydro_set_physical_internal_energy(p, xp, cosmo, new_u);
      hydro_set_drifted_physical_internal_energy(p, cosmo, new_u);
    }
  }
}

/**
 * @brief Initialises properties stored in the cooling_function_data struct
 *
1047
1048
1049
1050
1051
 * @param parameter_file The parsed parameter file.
 * @param us Internal system of units data structure.
 * @param hydro_props the properties of the hydro scheme.
 * @param phys_const #phys_const data structure.
 * @param cooling #cooling_function_data struct to initialize.
Matthieu Schaller's avatar
Matthieu Schaller committed
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
 */
void cooling_init_backend(struct swift_params *parameter_file,
                          const struct unit_system *us,
                          const struct phys_const *phys_const,
                          const struct hydro_props *hydro_props,
                          struct cooling_function_data *cooling) {

  /* read some parameters */

  parser_get_param_string(parameter_file, "COLIBRECooling:dir_name",
                          cooling->cooling_table_path);

  /* Despite the names, the values of H_reion_heat_cgs and He_reion_heat_cgs
   * that are read in are actually in units of electron volts per proton mass.
   * We later convert to units just below */

  cooling->H_reion_done = 0;
  cooling->H_reion_z =
      parser_get_param_float(parameter_file, "COLIBRECooling:H_reion_z");
  cooling->H_reion_heat_cgs =
      parser_get_param_float(parameter_file, "COLIBRECooling:H_reion_eV_p_H");
  cooling->He_reion_z_centre = parser_get_param_float(
      parameter_file, "COLIBRECooling:He_reion_z_centre");
  cooling->He_reion_z_sigma =
      parser_get_param_float(parameter_file, "COLIBRECooling:He_reion_z_sigma");
  cooling->He_reion_heat_cgs =
      parser_get_param_float(parameter_file, "COLIBRECooling:He_reion_eV_p_H");

  /* Properties for the subgrid properties model ---------------------------- */
  cooling->dlogT_EOS = parser_get_param_float(
      parameter_file, "COLIBRECooling:delta_logTEOS_subgrid_properties");

  /* Optional parameters to correct the abundances */
  cooling->Ca_over_Si_ratio_in_solar = parser_get_opt_param_float(
      parameter_file, "COLIBRECooling:Ca_over_Si_in_solar", 1.f);
  cooling->S_over_Si_ratio_in_solar = parser_get_opt_param_float(
      parameter_file, "COLIBRECooling:S_over_Si_in_solar", 1.f);

  /* Convert H_reion_heat_cgs and He_reion_heat_cgs to cgs
   * (units used internally by the cooling routines). This is done by
   * multiplying by 'eV/m_H' in internal units, then converting to cgs units.
   * Note that the dimensions of these quantities are energy/mass = velocity^2
   */

  cooling->H_reion_heat_cgs *=
      phys_const->const_electron_volt / phys_const->const_proton_mass *
      units_cgs_conversion_factor(us, UNIT_CONV_ENERGY_PER_UNIT_MASS);

  cooling->He_reion_heat_cgs *=
      phys_const->const_electron_volt / phys_const->const_proton_mass *
      units_cgs_conversion_factor(us, UNIT_CONV_ENERGY_PER_UNIT_MASS);

  /* Compute conversion factors */
  cooling->pressure_to_cgs =
      units_cgs_conversion_factor(us, UNIT_CONV_PRESSURE);
  cooling->internal_energy_to_cgs =
      units_cgs_conversion_factor(us, UNIT_CONV_ENERGY_PER_UNIT_MASS);
  cooling->internal_energy_from_cgs = 1. / cooling->internal_energy_to_cgs;
  cooling->number_density_to_cgs =
      units_cgs_conversion_factor(us, UNIT_CONV_NUMBER_DENSITY);
  cooling->number_density_from_cgs = 1. / cooling->number_density_to_cgs;

  /* Store some constants in CGS units */
  const float units_kB[5] = {1, 2, -2, 0, -1};
  const double kB_cgs = phys_const->const_boltzmann_k *
                        units_general_cgs_conversion_factor(us, units_kB);
  const double proton_mass_cgs =
      phys_const->const_proton_mass *
      units_cgs_conversion_factor(us, UNIT_CONV_MASS);

  cooling->log10_kB_cgs = log10(kB_cgs);
  cooling->inv_proton_mass_cgs = 1. / proton_mass_cgs;
  cooling->T_CMB_0 = phys_const->const_T_CMB_0 *
                     units_cgs_conversion_factor(us, UNIT_CONV_TEMPERATURE);

  /* Get the minimal temperature allowed */
  cooling->Tmin = hydro_props->minimal_temperature;
  if (cooling->Tmin < 10.)
    error("COLIBRE cooling cannot handle a minimal temperature below 10 K");

  /* Recover the minimal energy allowed (in internal units) */
  const double u_min = hydro_props->minimal_internal_energy;

  /* Convert to CGS units */
  cooling->umin_cgs = u_min * cooling->internal_energy_to_cgs;

#ifdef SWIFT_DEBUG_CHECKS
  /* Basic cross-check... */
  if (kB_cgs > 1.381e-16 || kB_cgs < 1.380e-16)
    error("Boltzmann's constant not initialised properly!");
#endif

  /* Compute the coefficient at the front of the Compton cooling expression */
  const double radiation_constant =
      4. * phys_const->const_stefan_boltzmann / phys_const->const_speed_light_c;
  const double compton_coefficient =
      4. * radiation_constant * phys_const->const_thomson_cross_section *
      phys_const->const_boltzmann_k /
      (phys_const->const_electron_mass * phys_const->const_speed_light_c);
  const float dimension_coefficient[5] = {1, 2, -3, 0, -5};

  /* This should be ~1.0178085e-37 g cm^2 s^-3 K^-5 */
  const double compton_coefficient_cgs =
      compton_coefficient *
      units_general_cgs_conversion_factor(us, dimension_coefficient);

#ifdef SWIFT_DEBUG_CHECKS
  const double expected_compton_coefficient_cgs = 1.0178085e-37;
  if (fabs(compton_coefficient_cgs - expected_compton_coefficient_cgs) /
          expected_compton_coefficient_cgs >
      0.01)
    error("compton coefficient incorrect.");
#endif

  /* And now the Compton rate */
  cooling->compton_rate_cgs = compton_coefficient_cgs * cooling->T_CMB_0 *
                              cooling->T_CMB_0 * cooling->T_CMB_0 *
                              cooling->T_CMB_0;

  /* Threshold in dt / t_cool above which we
   * are in the rapid cooling regime. If negative,
   * we never use this scheme (i.e. always drift
   * the internal energies). */
  cooling->rapid_cooling_threshold = parser_get_param_double(
      parameter_file, "COLIBRECooling:rapid_cooling_threshold");

  /* Finally, read the tables */
  read_cooling_header(cooling);
  read_cooling_tables(cooling);
}

/**
 * @brief Restore cooling tables (if applicable) after
 * restart
 *
 * @param cooling the #cooling_function_data structure
 * @param cosmo #cosmology structure
 */
void cooling_restore_tables(struct cooling_function_data *cooling,
                            const struct cosmology *cosmo) {

  read_cooling_header(cooling);
  read_cooling_tables(cooling);

  cooling_update(cosmo, cooling, /*space=*/NULL);
}

/**
 * @brief Prints the properties of the cooling model to stdout.
 *
 * @param cooling #cooling_function_data struct.
 */
void cooling_print_backend(const struct cooling_function_data *cooling) {

  message("Cooling function is 'COLIBRE'.");
}

/**
 * @brief Clean-up the memory allocated for the cooling routines
 *
 * We simply free all the arrays.
 *
 * @param cooling the cooling data structure.
 */
void cooling_clean(struct cooling_function_data *cooling) {

  /* Free the side arrays */
  free(cooling->Redshifts);
  free(cooling->nH);
  free(cooling->Temp);
  free(cooling->Metallicity);
  free(cooling->Therm);
  free(cooling->LogAbundances);
  free(cooling->Abundances);
  free(cooling->Abundances_inv);
  free(cooling->atomicmass);
  free(cooling->atomicmass_inv);
  free(cooling->Zsol);
  free(cooling->Zsol_inv);
  free(cooling->LogMassFractions);
  free(cooling->MassFractions);

  /* Free the tables */
  free(cooling->table.Tcooling);
  free(cooling->table.Ucooling);
  free(cooling->table.Theating);
  free(cooling->table.Uheating);
  free(cooling->table.Telectron_fraction);
  free(cooling->table.Uelectron_fraction);
  free(cooling->table.T_from_U);
  free(cooling->table.U_from_T);
  free(cooling->table.Umu);
  free(cooling->table.Tmu);
  free(cooling->table.meanpartmass_Teq);
  free(cooling->table.logHfracs_Teq);
  free(cooling->table.logHfracs_all);
  free(cooling->table.logTeq);
  free(cooling->table.logPeq);
}

/**
 * @brief Write a cooling struct to the given FILE as a stream of bytes.
 *
 * @param cooling the struct
 * @param stream the file stream
 */
void cooling_struct_dump(const struct cooling_function_data *cooling,
                         FILE *stream) {

  /* To make sure everything is restored correctly, we zero all the pointers to
     tables. If they are not restored correctly, we would crash after restart on
     the first call to the cooling routines. Helps debugging. */
  struct cooling_function_data cooling_copy = *cooling;
  cooling_copy.Redshifts = NULL;
  cooling_copy.nH = NULL;
  cooling_copy.Temp = NULL;
  cooling_copy.Metallicity = NULL;
  cooling_copy.Therm = NULL;
  cooling_copy.LogAbundances = NULL;
  cooling_copy.Abundances = NULL;
  cooling_copy.Abundances_inv = NULL;
  cooling_copy.atomicmass = NULL;
  cooling_copy.LogMassFractions = NULL;
  cooling_copy.MassFractions = NULL;

  cooling_copy.table.Tcooling = NULL;
  cooling_copy.table.Theating = NULL;
  cooling_copy.table.Telectron_fraction = NULL;
  cooling_copy.table.Ucooling = NULL;
  cooling_copy.table.Uheating = NULL;
  cooling_copy.table.Uelectron_fraction = NULL;
  cooling_copy.table.T_from_U = NULL;
  cooling_copy.table.U_from_T = NULL;

  restart_write_blocks((void *)&cooling_copy,
                       sizeof(struct cooling_function_data), 1, stream,
                       "cooling", "cooling function");
}

/**
 * @brief Restore a hydro_props struct from the given FILE as a stream of
 * bytes.
 *
 * Read the structure from the stream and restore the cooling tables by
 * re-reading them.
 *
 * @param cooling the struct
 * @param stream the file stream
 * @param cosmo #cosmology structure
 */
void cooling_struct_restore(struct cooling_function_data *cooling, FILE *stream,
                            const struct cosmology *cosmo) {
  restart_read_blocks((void *)cooling, sizeof(struct cooling_function_data), 1,
                      stream, NULL, "cooling function");

  cooling_restore_tables(cooling, cosmo);
}