forked from omega13a/stargen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenviro.cpp
More file actions
3762 lines (3441 loc) · 155 KB
/
Copy pathenviro.cpp
File metadata and controls
3762 lines (3441 loc) · 155 KB
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
#include "enviro.h"
#include <ctype.h> // for isdigit
#include <cmath> // for pow, NAN, sqrt, fabs, exp, log, floor
#include <cstdlib> // for exit, EXIT_FAILURE, atoi
#include <cstring> // for strstr, strcmp
#include <iostream> // for operator<<, basic_ostream, endl
#include <map> // for std::map, std::map<>::mapped_type
#include <string> // for std::string, operator<<, operator==
#include <vector> // for vector
#include <sstream> // for std::stringstream (not guaranteed via <iostream>)
#include <numbers> // for std::numbers::pi (portable replacement for M_PI)
#include <functional>
#include "const.h" // for SUN_MASS_IN_EARTH_MASSES, AVE, pow2
#include "units.hh" // au-backed exact length conversions (sgu::)
#include "elements.h" // for gases
#include "gas_radius_helpers.h" // for mini_neptune_radius, gas_dwarf_radius
#include "radius_tables.h" // for solid_rock, solid_half_rock_half_iron
#include "solid_radius_helpers.h" // for rock_radius, half_rock_half_iron_r...
#include "star_temps.h" // for tempA, tempB, tempE, tempF, tempG
#include "stargen.h" // for the_sun_clone, flag_verbose, assig...
#include "utils.h" // for toString, random_number, about
std::string breathability_phrase[4] = {"none", "breathable", "unbreathable",
"poisonous"};
thread_local std::map<std::map<long double, long double>, std::vector<long double> > polynomial_cache;
/*
* Main-sequence mass <-> luminosity.
*
* Eker et al. 2018, "Interrelated Main-Sequence Mass-Luminosity, Mass-Radius and
* Mass-Effective Temperature Relations" (MNRAS 479, 5491; arXiv:1807.02568): a
* six-piece classical relation log10(L/Lsun) = a*log10(M/Msun) + b, calibrated to
* 509 detached double-lined eclipsing-binary main-sequence stars over
* 0.179 <= M/Msun <= 31. Replaces the older uncalibrated Wikipedia power law.
*
* Below 0.179 Msun and above 31 Msun the nearest piece is extrapolated (the
* generator must still produce something for brown-dwarf and very-massive tails).
* See research/modern/07-stellar-relations-binaries.md.
*
* Eker's independent per-piece fits are not perfectly continuous at the regime
* boundaries; the small (<~20%) jumps there are inherent to the published
* relation and were present in the previous piecewise model too.
*/
namespace {
// {upper mass bound (Msun), slope a, intercept b}. The last piece's bound is the
// validity ceiling; masses above it reuse that piece.
struct EkerPiece { long double m_hi, a, b; };
constexpr EkerPiece kEkerML[] = {
{0.45L, 2.028L, -0.976L},
{0.72L, 4.572L, -0.102L},
{1.05L, 5.743L, -0.007L},
{2.40L, 4.329L, 0.010L},
{7.00L, 3.967L, 0.093L},
{31.0L, 2.865L, 1.105L},
};
} // namespace
/**
* @brief main-sequence mass -> luminosity (Eker et al. 2018)
* @param mass stellar mass in solar masses
* @return luminosity in solar luminosities
*/
long double mass_to_luminosity(long double mass) {
for (const auto& p : kEkerML) {
if (mass < p.m_hi) {
return std::pow(10.0L, p.a * std::log10(mass) + p.b);
}
}
const auto& top = kEkerML[(sizeof kEkerML / sizeof *kEkerML) - 1];
return std::pow(10.0L, top.a * std::log10(mass) + top.b);
}
/**
* @brief main-sequence luminosity -> mass (inverse of Eker et al. 2018)
*
* Thresholds are the luminosity at each piece's upper mass bound, so the inverse
* selects the same regime the forward relation would.
* @param luminosity luminosity in solar luminosities
* @return stellar mass in solar masses
*/
auto luminosity_to_mass(long double luminosity) -> long double {
const long double log_l = std::log10(luminosity);
for (const auto& p : kEkerML) {
const long double l_hi = std::pow(10.0L, p.a * std::log10(p.m_hi) + p.b);
if (luminosity < l_hi) {
return std::pow(10.0L, (log_l - p.b) / p.a);
}
}
const auto& top = kEkerML[(sizeof kEkerML / sizeof *kEkerML) - 1];
return std::pow(10.0L, (log_l - top.b) / top.a);
}
/**
* @brief Main-sequence effective temperature from stellar mass + luminosity.
*
* Used when a star is specified by mass (or luminosity) with no spectral type, so
* its effective temperature would otherwise default to a placeholder. Above 1.5
* Msun uses the Eker et al. 2018 mass-Teff relation
* (log Teff = -0.170 (log M)^2 + 0.888 log M + 3.671); at or below 1.5 Msun
* derives Teff from luminosity and the Eker mass-radius relation
* (R = 0.438 M^2 + 0.479 M + 0.075) via Stefan-Boltzmann, anchored so the Sun
* (1 Msun) -> ~5778 K. See research/modern/07-stellar-relations-binaries.md.
*
* @param mass stellar mass in solar masses
* @param luminosity luminosity in solar luminosities
* @return effective temperature in Kelvin
*/
auto mass_to_eff_temp(long double mass, long double luminosity) -> long double {
if (mass > 1.5L) {
const long double lm = std::log10(mass);
return std::pow(10.0L, -0.170L * lm * lm + 0.888L * lm + 3.671L);
}
long double radius = 0.438L * mass * mass + 0.479L * mass + 0.075L; // Rsun
if (radius <= 0.0L) {
radius = 1.0L;
}
return 5778.0L * std::pow(luminosity / (radius * radius), 0.25L);
}
/**
* @brief Get the Lum Index
*
* @param spec_type
* @return int
*/
int getLumIndex(const std::string& spec_type) {
if (spec_type.find("Ia0") != std::string::npos ||
spec_type.find("Ia") != std::string::npos ||
spec_type.find("Ib") != std::string::npos ||
spec_type.find("II") != std::string::npos) {
return 2;
}
if (spec_type.find("III") != std::string::npos ||
spec_type.find("IV") != std::string::npos) {
return 1;
}
return 0;
}
/**
* @brief Get the Star Type
*
* @param spec_type
* @return std::string
*/
std::string getStarType(std::string spec_type) {
spec_type = my_strtoupper(spec_type);
static const std::vector<std::pair<std::string, std::string>> starTypes = {
{"DA", "WD"}, {"DB", "WD"}, {"DC", "WD"}, {"DO", "WD"}, {"DQ", "WD"}, {"DZ", "WD"},
{"WN", "WN"}, {"WC", "WC"},
{"O", "O"}, {"B", "B"}, {"A", "A"}, {"F", "F"}, {"G", "G"}, {"K", "K"},
{"M", "M"}, {"L", "L"}, {"T", "T"}, {"Y", "Y"}, {"H", "H"}, {"E", "E"}, {"I", "I"},
{"R", "K"}, {"S", "M"}, {"N", "M"}, {"C", "M"}
};
for (const auto& [prefix, type] : starTypes) {
if (spec_type.find(prefix) != std::string::npos) {
return type;
}
}
std::cerr << "Unsupported star type: " << spec_type << std::endl;
exit(EXIT_FAILURE);
}
/**
* @brief Get the star Sub Type
*
* @param spec_type
* @return int
*/
auto getSubType(std::string spec_type) -> int {
int total_chars = 0;
// total_chars = spec_type.size();
std::string buffer;
for (std::string::iterator it = spec_type.begin(); it < spec_type.end(); it++) {
if (isdigit(static_cast<unsigned char>(*it)) || (*it == '.' && !buffer.empty())) {
buffer += *it;
} else if (!buffer.empty()) {
// Stop at the first non-numeric character after the numeric subtype began.
break;
}
}
if (buffer.empty()) {
return 0;
}
return static_cast<int>(strtod(buffer.c_str(), nullptr));
}
/**
* @brief spec type to eff temp
*
* @param spec_type
* @return long double
*/
long double spec_type_to_eff_temp(const std::string& spec_type) {
if (spec_type.empty()) {
return 0;
}
std::string star_type = getStarType(spec_type);
int sub_type = getSubType(spec_type);
int lumIndex = getLumIndex(spec_type);
switch (star_type[0]) {
case 'W':
if (star_type == "WD") return tempWD[sub_type];
if (star_type == "WN") return tempWN[sub_type];
if (star_type == "WC") return tempWC[sub_type];
break;
case 'O': return tempO[lumIndex][sub_type];
case 'B': return tempB[lumIndex][sub_type];
case 'A': return tempA[lumIndex][sub_type];
case 'F': return tempF[lumIndex][sub_type];
case 'G': return tempG[lumIndex][sub_type];
case 'K': return tempK[lumIndex][sub_type];
case 'M': return tempM[lumIndex][sub_type];
case 'L': return tempL[sub_type];
case 'T': return tempT[sub_type];
case 'Y': return tempY[sub_type];
case 'H': return tempH[sub_type];
case 'I': return tempI[sub_type];
case 'E': return tempE[sub_type];
}
std::cerr << "Unsupported star type: " << star_type << std::endl;
exit(EXIT_FAILURE);
}
/**
* @brief eff temp to spec type
*
* @param eff_temp
* @param luminosity
* @return std::string
*/
std::string eff_temp_to_spec_type(long double eff_temp, long double luminosity) {
// Lower temperature bound of each spectral class, on the standard
// Morgan-Keenan / Pecaut & Mamajek (2013) scale. The previous boundaries
// were miscalibrated (e.g. G set at 6000 K, so a 5778 K Sun fell into K, and
// O was never reachable), which produced wrong spectral types for stars whose
// type is derived from effective temperature.
static const std::vector<std::pair<long double, std::string>> temp_classes = {
{30000, "O"}, {10000, "B"}, {7300, "A"}, {6000, "F"},
{5300, "G"}, {3900, "K"}, {2300, "M"}, {1300, "L"},
{600, "T"}, {0, "Y"}
};
auto get_spec_class = [&]() {
for (size_t i = 0; i < temp_classes.size(); ++i) {
const auto& [temp, class_name] = temp_classes[i];
if (eff_temp > temp) {
long double prev_temp = (i > 0) ? temp_classes[i-1].first : 200000; // Assuming 200000 as max temp
int subclass = floor(10.0 - 10.0 * (eff_temp - temp) / (prev_temp - temp));
return class_name + std::to_string(std::max(0, std::min(9, subclass)));
}
}
return std::string("Y9");
};
std::string spec_class = eff_temp > 52000 ? "WN" + std::to_string(std::min(9, std::max(0, int(10 - 10 * (eff_temp - 52000) / 148000))))
: get_spec_class();
// Stars on the mass/luminosity-derived path are main-sequence (mass->L is the
// main-sequence relation; age is capped at the MS lifetime; post-MS evolution
// is not modelled), so the luminosity class is V. The previous absolute-
// magnitude heuristic mislabelled intrinsically-bright MS stars as IV/III
// (e.g. an 8 Msun B-dwarf as a giant). Catalog stars set their spectral type
// directly (setSpecType) and keep any given giant/subgiant class.
(void)luminosity;
return spec_class + "V";
}
/**
* @brief This function, given the orbital radius of a planet in AU, returns
* the orbital 'zone' of the particle.
*
* @param ecosphere_radius
* @param orb_radius
* @return int
*/
auto orbital_zone(long double ecosphere_radius, long double orb_radius) -> int {
if (orb_radius < (4.0 * ecosphere_radius)) {
return 1;
} else if (orb_radius < (15.0 * ecosphere_radius)) {
return 2;
} else {
return 3;
}
}
/**
* @brief The mass is in units of solar masses, and the density is in units
* of grams/cc. The radius returned is in units of km.
*
* @param mass
* @param density
* @return long double
*/
auto volume_radius(long double mass, long double density) -> long double {
long double volume = NAN;
mass = mass * SOLAR_MASS_IN_GRAMS;
volume = mass / density;
return sgu::cm_to_km(std::pow((3.0 * volume) / (4.0 * PI), (1.0 / 3.0)));
}
/**
* @brief The mass passed in is in units of solar masses, and the orbital radius
* is in units of AU. The density is returned in units of grams/cc.
*
* @param mass
* @param orb_radius
* @param r_ecosphere
* @param gas_giant
* @return long double
*/
auto empirical_density(long double mass, long double orb_radius,
long double r_ecosphere, bool gas_giant) -> long double {
long double temp = NAN;
temp = std::pow(mass * SUN_MASS_IN_EARTH_MASSES, 1.0 / 8.0);
temp = temp * pow1_4(r_ecosphere / orb_radius);
if (gas_giant) {
return temp * 1.2;
} else {
return temp * 5.5;
}
}
/**
* @brief The mass passed in is in units of solar masses, and the equatorial
* radius is in km. The density is returned in units of grams/cc.
*
* @param mass
* @param equat_radius
* @return long double
*/
auto volume_density(long double mass, long double equat_radius) -> long double {
long double volume = NAN;
mass = mass * SOLAR_MASS_IN_GRAMS;
equat_radius = sgu::km_to_cm(equat_radius);
volume = (4.0 * PI * pow3(equat_radius)) / 3.0;
return mass / volume;
}
/**
* @brief The separation is in units of AU, and both masses are in units of solar
* masses. The period returned is in terms of Earth days.
*
* @param separation
* @param small_mass
* @param large_mass
* @return long double
*/
auto period(long double separation, long double small_mass,
long double large_mass) -> long double {
long double period_in_years = NAN;
period_in_years = sqrt(pow3(separation) / (small_mass + large_mass));
return period_in_years * DAYS_IN_A_YEAR;
}
/**
* @brief Fogg's information for this routine came from Dole "Habitable Planets
* for Man", Blaisdell Publishing Company, NY, 1964. From this, he came
* up with his eq.12, which is the equation for the 'base_angular_velocity'
* below. He then used an equation for the change in angular velocity per
* time (dw/dt) from P. Goldreich and S. Soter's paper "Q in the Solar
* System" in Icarus, vol 5, pp.375-389 (1966). Using as a comparison the
* change in angular velocity for the Earth, Fogg has come up with an
* approximation for our new planet (his eq.13) and take that into account
* This is used to find 'change_in_angular_velocity' below.
* Input parameters are mass (in solar masses), radius (in Km), orbital
* period (in days), orbital radius (in AU), density (in g/cc),
* eccentricity, and whether it is a gas giant or not.
* The length of the day is returned in units of hours.
*
* @param the_planet
* @param parent_mass
* @param is_moon
* @return long double
*/
/*--------------------------------------------------------------------------*/
/* Tidal synchronization ("despinning") timescale, Gladman et al. 1996 */
/* (Icarus 122, 166, eq. 1) / Peale 1977 / Murray & Dermott 1999. Pure */
/* numeric core in CGS, returned in YEARS so it can be compared directly with */
/* the system age. The moment of inertia is written explicitly, */
/* C = moi_factor * M_p * R_p^2, so the net radius dependence is R_p^-3: */
/* t_sync = (4/9)(Q/k2) * a^6 * w * C / (G * M_star^2 * R_p^5) [seconds] */
/* (The 4/9 prefactor is order-unity and convention-dependent; the lock */
/* decision spans many orders of magnitude in t_sync so it is insensitive to */
/* it. Sanity: Earth/Sun ~13 Gyr -> unlocked; 1 M_earth at 0.1 AU around a */
/* 0.3 Msun M dwarf ~1.5e5 yr -> locked.) */
/*--------------------------------------------------------------------------*/
auto tidal_sync_time_years(long double a_au, long double m_star_solar, long double r_p_km,
long double m_p_solar, long double spin_rad_s, long double moi_factor,
long double q, long double k2) -> long double {
long double a_cm = sgu::au_to_cm(a_au);
long double m_star_g = m_star_solar * SOLAR_MASS_IN_GRAMS;
long double r_p_cm = sgu::km_to_cm(r_p_km);
long double m_p_g = m_p_solar * SOLAR_MASS_IN_GRAMS;
if (a_cm <= 0.0 || m_star_g <= 0.0 || r_p_cm <= 0.0 || m_p_g <= 0.0 || spin_rad_s <= 0.0 ||
k2 <= 0.0) {
return INCREDIBLY_LARGE_NUMBER; // degenerate inputs cannot lock
}
long double moment_of_inertia = moi_factor * m_p_g * (r_p_cm * r_p_cm);
long double a6 = std::pow(a_cm, 6.0L);
long double r5 = std::pow(r_p_cm, 5.0L);
long double t_sync_sec = (4.0L / 9.0L) * (q / k2) *
(a6 * spin_rad_s * moment_of_inertia) /
(GRAV_CONSTANT * (m_star_g * m_star_g) * r5);
return t_sync_sec / SECONDS_PER_YEAR;
}
/**
* @brief Tidal-lock timescale (years) for a planet/moon, selecting Q/k2 by type.
* Wrapper over tidal_sync_time_years; pure, no globals/RNG -> determinism-safe.
* parent_mass is in SOLAR masses (the star for planets, the planet for moons),
* matching day_length's convention.
*/
auto tidal_lock_timescale_years(planet *the_planet, long double parent_mass, bool is_moon,
long double spin_rad_s, long double moi_factor) -> long double {
long double a_au = is_moon ? the_planet->getMoonA() : the_planet->getA();
long double q = is_gas_planet(the_planet) ? TIDAL_Q_GAS : TIDAL_Q_ROCKY;
long double k2 = is_gas_planet(the_planet) ? TIDAL_LOVE_K2_GAS : TIDAL_LOVE_K2_ROCKY;
return tidal_sync_time_years(a_au, parent_mass, the_planet->getRadius(), the_planet->getMass(),
spin_rad_s, moi_factor, q, k2);
}
/*--------------------------------------------------------------------------*/
/* Post-accretion gas-disk eccentricity damping (Cresswell & Nelson 2008, */
/* A&A 482, 677; parameterizing Tanaka & Ward 2004). All in solar/AU/year */
/* units, so Omega_K and the disk lifetime are dimensionless-consistent and */
/* no new unit constants are needed. Returns the damped eccentricity. Pure */
/* (no RNG, no globals) -> determinism-safe. Inclination is intentionally NOT */
/* damped here: it is assigned later in generate_planet, so it is zero at this */
/* stage (the iota terms vanish). */
/*--------------------------------------------------------------------------*/
auto gas_disk_damped_eccentricity(long double e, long double a_au, long double m_p_solar,
long double m_star_solar) -> long double {
if (e <= 0.0 || a_au <= 0.0 || m_p_solar <= 0.0 || m_star_solar <= 0.0) {
return e;
}
long double h = DISK_ASPECT_RATIO;
long double sigma = DISK_SIGMA0_SOLAR_PER_AU2 * std::pow(a_au, -1.5L); // solar / AU^2
long double p_yr = std::sqrt((a_au * a_au * a_au) / (m_star_solar + m_p_solar)); // Kepler III
long double omega_k = (2.0L * PI) / p_yr; // rad/yr
long double t_wave =
(m_star_solar / m_p_solar) * (m_star_solar / (sigma * a_au * a_au)) *
(h * h * h * h) / omega_k; // Tanaka & Ward wave time, years
long double eps = e / h;
long double bracket = 1.0L - 0.14L * (eps * eps) + 0.06L * (eps * eps * eps);
if (bracket < DISK_DAMP_BRACKET_FLOOR) {
bracket = DISK_DAMP_BRACKET_FLOOR; // never anti-damp at e >> h
}
long double t_e = (t_wave / 0.780L) * bracket;
if (t_e <= 0.0) {
return e;
}
return e * std::exp(-DISK_LIFETIME_YEARS / t_e);
}
/**
* @brief Apply one post-accretion gas-disk eccentricity-damping pass over the
* whole planet list (Cresswell & Nelson 2008). Called once after accretion,
* before per-planet environment generation. Pure arithmetic, adds no RNG draws,
* so it leaves the rest of the population (masses, distances, compositions)
* byte-identical and preserves parallel/serial determinism.
*/
void apply_gas_disk_damping(sun &the_sun, planet *innermost) {
long double m_star = the_sun.getIsCircumbinary() ? the_sun.getCombinedMass() : the_sun.getMass();
for (planet *p = innermost; p != nullptr; p = p->next_planet) {
p->setE(gas_disk_damped_eccentricity(p->getE(), p->getA(), p->getMass(), m_star));
}
}
auto day_length(planet *the_planet, long double parent_mass,
bool is_moon) -> long double {
long double planetary_mass_in_grams =
the_planet->getMass() * SOLAR_MASS_IN_GRAMS;
long double equatorial_radius_in_cm = sgu::km_to_cm(the_planet->getRadius());
long double year_in_hours = the_planet->getOrbPeriod() * 24.0;
// bool giant; maybe this used to be used
//bool giant = the_planet->getType() == tGasGiant || the_planet->getType() == tBrownDwarf || the_planet->getType() == tSubGasGiant || the_planet->getType() == tSubSubGasGiant;
long double k2 = NAN;
long double base_angular_velocity = NAN;
long double change_in_angular_velocity = NAN;
long double ang_velocity = NAN;
long double spin_resonance_factor = NAN;
long double day_in_hours = NAN;
bool stopped = false;
the_planet->setResonantPeriod(false);
/*if (giant)
{
k2 = 0.24;
}
else
{
k2 = 0.33;
}*/
k2 = calculate_moment_of_inertia_coeffient(the_planet);
// Calculate the base angular velocity
base_angular_velocity = sqrt(2.0 * J * (planetary_mass_in_grams) /
(k2 * pow2(equatorial_radius_in_cm)));
// This next calculation determines how much the planet's rotation is
// slowed by the presence of the parent body.
if (!is_moon) {
change_in_angular_velocity =
CHANGE_IN_EARTH_ANG_VEL * (the_planet->getDensity() / EARTH_DENSITY) *
(equatorial_radius_in_cm / EARTH_RADIUS) *
(EARTH_MASS_IN_GRAMS / planetary_mass_in_grams) *
std::pow(parent_mass, 2.0) * (1.0 / std::pow(the_planet->getA(), 6.0));
} else {
change_in_angular_velocity =
CHANGE_IN_EARTH_ANG_VEL * (the_planet->getDensity() / EARTH_DENSITY) *
(equatorial_radius_in_cm / EARTH_RADIUS) *
(EARTH_MASS_IN_GRAMS / planetary_mass_in_grams) *
std::pow(parent_mass, 2.0) * (1.0 / std::pow(the_planet->getMoonA(), 6.0));
}
ang_velocity = base_angular_velocity + (change_in_angular_velocity *
the_planet->getTheSun().getAge());
if (ang_velocity <= 0.0) {
stopped = true;
day_in_hours = INCREDIBLY_LARGE_NUMBER;
} else {
day_in_hours = RADIANS_PER_ROTATION / (SECONDS_PER_HOUR * ang_velocity);
}
// Physically-derived tidal lock: synchronized when the Gladman et al. 1996
// despinning timescale is short compared with the host system age (replaces the
// old kinematic day>=year test). NB k2 here is the moment-of-inertia factor
// computed at line ~467, NOT a tidal Love number.
long double t_sync_years =
tidal_lock_timescale_years(the_planet, parent_mass, is_moon, base_angular_velocity, k2);
if (stopped || (t_sync_years <= the_planet->getTheSun().getAge())) {
if ((the_planet->getE() > 0.1 && !is_moon) ||
(the_planet->getMoonE() > 0.1 && is_moon)) {
if (!is_moon) {
spin_resonance_factor = getSpinResonanceFactor(the_planet->getE());
} else {
spin_resonance_factor = getSpinResonanceFactor(the_planet->getMoonE());
}
the_planet->setResonantPeriod(true);
return spin_resonance_factor * year_in_hours;
} else {
the_planet->setAxialTilt(0);
return year_in_hours;
}
}
return day_in_hours;
}
/**
* @brief The orbital radius is expected in units of Astronomical Units (AU).
* Inclination is returned in units of degrees. (seb: real)
*
* @param orb_radius
* @param parent_mass
* @return long double
*/
auto inclination(long double orb_radius, long double parent_mass) -> long double {
// Primordial obliquity is set by the last few stochastic giant impacts, which
// arrive from random directions in a geometrically thick embryo swarm. The
// result is an *isotropic* obliquity: cos(eps) is uniform on [-1, 1], i.e.
// p(eps) = 0.5*sin(eps) on [0, 180] degrees. This admits retrograde spins
// (cf. Venus ~177 deg, Uranus ~98 deg), unlike a folded Gaussian peaked at 0.
// Kokubo & Ida 2007, ApJ 671, 2082; Kokubo & Genda 2010, ApJ 714, L21.
// See research/modern/08-spin-obliquity-validation.md.
long double cos_obliquity = 1.0L - 2.0L * random_number(0.0L, 1.0L);
long double obliquity = std::acos(cos_obliquity) * 180.0L / PI; // degrees, [0,180]
// Tides erode obliquity for planets close to the star (Heller et al. 2011,
// arXiv:1101.2156); damp linearly toward zero inside the tidal-influence
// distance. That distance scales with stellar mass as M^(1/3) -- the same
// dependence as the tidal-locking critical radius -- rather than the old
// dimensionally-inconsistent comparison of an AU distance against a solar mass.
// OBLIQUITY_TIDAL_REACH_AU = 1.0 makes this identical to the prior behavior at
// one solar mass.
long double tidal_reach = OBLIQUITY_TIDAL_REACH_AU * std::cbrt(parent_mass);
if (tidal_reach > 0.0 && orb_radius < tidal_reach) {
obliquity *= (orb_radius / tidal_reach);
}
return obliquity;
}
/**
* @brief This function implements the escape velocity calculation. Note that
* it appears that Fogg's eq.15 is incorrect.
* The mass is in units of solar mass, the radius in kilometers, and the
* velocity returned is in cm/sec.
*
* @param mass
* @param radius
* @return long double
*/
auto escape_vel(long double mass, long double radius) -> long double {
long double mass_in_grams = NAN, radius_in_cm = NAN;
mass_in_grams = mass * SOLAR_MASS_IN_GRAMS;
radius_in_cm = sgu::km_to_cm(radius);
return sqrt(2.0 * GRAV_CONSTANT * mass_in_grams / radius_in_cm);
}
/*------------------------------------------------------------------------*/
/* This is Fogg's eq.16. The molecular weight (usually assumed to be N2) */
/* is used as the basis of the Root Mean Square (RMS) velocity of the */
/* molecule or atom. The velocity returned is in cm/sec. */
/* Orbital radius is in A.U.(ie: in units of the earth's orbital radius). */
/*------------------------------------------------------------------------*/
auto rms_vel(long double molecular_weight, long double exospheric_temp) -> long double {
return sgu::m_to_cm(
sqrt((3.0 * MOLAR_GAS_CONST * exospheric_temp) / molecular_weight));
}
auto min_molec_weight(planet *the_planet) -> long double {
long double mass = the_planet->getMass();
long double radius = the_planet->getRadius();
long double temp = the_planet->getExosphericTemp();
long double target = 5.0E9;
long double guess_1 = molecule_limit(mass, radius, temp);
long double guess_2 = guess_1;
long double life = gas_life(guess_1, the_planet);
int loops = 0;
target = the_planet->getTheSun().getAge();
if (life > target) {
while (life > target && loops++ < 25) {
guess_1 = guess_1 / 2.0;
life = gas_life(guess_1, the_planet);
}
} else {
while (life < target && loops++ < 25) {
guess_2 = guess_2 * 2.0;
life = gas_life(guess_2, the_planet);
}
}
loops = 0;
while ((guess_2 - guess_1) > 0.1 && loops++ < 25) {
long double guess_3 = (guess_1 + guess_2) / 2.0;
life = gas_life(guess_3, the_planet);
if (life < target) {
guess_1 = guess_3;
} else {
guess_2 = guess_3;
}
}
// life = gas_life(guess_2, the_planet);
return guess_2;
}
/*------------------------------------------------------------------------*/
/* This function returns the smallest molecular weight retained by the */
/* body, which is useful for determining the atmosphere composition. */
/* Mass is in units of solar masses, and equatorial radius is in units of */
/* kilometers. */
/*------------------------------------------------------------------------*/
auto molecule_limit(long double mass, long double equat_radius,
long double exospheric_temp) -> long double {
long double esc_velocity = escape_vel(mass, equat_radius);
return (3.0 * MOLAR_GAS_CONST * exospheric_temp) /
(pow2(sgu::cm_to_m(esc_velocity / GAS_RETENTION_THRESHOLD)));
}
/*----------------------------------------------------------------------*/
/* This function calculates the surface acceleration of a planet. The */
/* mass is in units of solar masses, the radius in terms of km, and the */
/* acceleration is returned in units of cm/sec2. */
/*----------------------------------------------------------------------*/
auto acceleration(long double mass, long double radius) -> long double {
return GRAV_CONSTANT * (mass * SOLAR_MASS_IN_GRAMS) /
pow2(sgu::km_to_cm(radius));
}
auto acceleration(planet *the_planet) -> long double {
const long double SOLAR_MASS_KG = SOLAR_MASS_IN_KG_APPROX; // kg
const long double EARTH_MASS_KG = EARTH_MASS_IN_KG_APPROX; // kg
const long double EARTH_RADIUS_KM = MEAN_EARTH_RADIUS_KM; // km
const long double EARTH_GRAVITY_CM_S2 = EARTH_ACCELERATION; // cm/s^2 (980.665)
// Convert planet mass to Earth masses
long double mass_earth_masses = the_planet->getMass() * (SOLAR_MASS_KG / EARTH_MASS_KG);
// Get planet radius in Earth radii
long double radius_earth_radii = the_planet->getRadius() / EARTH_RADIUS_KM;
// Get composition fractions
long double ice_fraction = the_planet->getImf();
long double rock_fraction = the_planet->getRmf();
long double carbon_fraction = rock_fraction * the_planet->getCmf();
long double silicate_fraction = rock_fraction * (1.0 - the_planet->getCmf());
long double iron_fraction = 1.0 - ice_fraction - rock_fraction;
// Density factors (relative to Earth's average density)
const long double ICE_DENSITY_FACTOR = 0.26;
const long double SILICATE_DENSITY_FACTOR = 0.94;
const long double CARBON_DENSITY_FACTOR = 1.0;
const long double IRON_DENSITY_FACTOR = 2.25;
// Calculate average density factor
long double avg_density_factor = (ice_fraction * ICE_DENSITY_FACTOR +
silicate_fraction * SILICATE_DENSITY_FACTOR +
carbon_fraction * CARBON_DENSITY_FACTOR +
iron_fraction * IRON_DENSITY_FACTOR);
// Calculate surface gravity relative to Earth
long double fudge_factor = .6; // densities are too high, probably not considering enough elements
long double relative_gravity = (mass_earth_masses / std::pow(radius_earth_radii, 2)) * avg_density_factor * fudge_factor;
// Convert to cm/s^2
long double calculated_gravity_cm_s2 = relative_gravity * EARTH_GRAVITY_CM_S2;
// Log the results
// std::cout << "Planet mass (Earth masses): " << mass_earth_masses << "\n";
// std::cout << "Planet radius (Earth radii): " << radius_earth_radii << "\n";
// std::cout << "Calculated gravity (Earth g): " << relative_gravity << "\n";
// std::cout << "Calculated gravity (cm/s^2): " << calculated_gravity_cm_s2 << "\n";
// std::cout << "Ice fraction: " << ice_fraction << "\n";
// std::cout << "Rock fraction: " << rock_fraction << "\n";
// std::cout << "Carbon fraction: " << carbon_fraction << "\n";
// std::cout << "Silicate fraction: " << silicate_fraction << "\n";
// std::cout << "Iron fraction: " << iron_fraction << "\n";
// std::cout << "Average density factor: " << avg_density_factor << "\n";
return calculated_gravity_cm_s2;
}
auto acceleration_oblateness_refinement(planet *the_planet) -> long double {
const long double G = GRAV_CONSTANT_SI; // m^3 kg^-1 s^-2
const long double EARTH_MASS = EARTH_MASS_IN_KG_APPROX; // kg
const long double EARTH_RADIUS_M = MEAN_EARTH_RADIUS_M; // meters (mean)
const long double EARTH_GRAVITY = EARTH_GRAVITY_M_S2; // m/s^2
// Constants for transition masses
const long double ROCKY_TRANSITION_MASS_KG = 10.0 * EARTH_MASS; // 10 Earth masses
const long double GAS_GIANT_TRANSITION_MASS_KG = 100.0 * EARTH_MASS; // 100 Earth masses
// Convert planet mass to kilograms
long double mass_kg = (the_planet->getDustMass() + the_planet->getGasMass()) *
SOLAR_MASS_IN_KG_APPROX; // Convert solar masses to kg
long double radius_km = the_planet->getRadius(); // Equatorial radius in km
// Check if radius and mass are valid
if (radius_km == 0 || mass_kg == 0) {
return 0.0; // Avoid divide by zero
}
// Calculate the radius based on mass regimes
long double radius_m;
if (mass_kg < ROCKY_TRANSITION_MASS_KG) {
// Rocky planets (mass < 10 Earth masses), R ∝ M^0.25
radius_m = EARTH_RADIUS_M * std::pow(mass_kg / EARTH_MASS, 0.25);
} else if (mass_kg < GAS_GIANT_TRANSITION_MASS_KG) {
// Transition zone (10 to 100 Earth masses), R ∝ M^0.5
radius_m = EARTH_RADIUS_M * std::pow(mass_kg / EARTH_MASS, 0.5);
} else {
// Gas giants (mass ≥ 100 Earth masses), radius approximately constant (around Jupiter's radius)
radius_m = 71.5e6; // Set to approximately Jupiter's radius (71,500 km)
}
// Adjust for oblateness (if oblateness > 0)
long double oblateness_factor = the_planet->getOblateness();
long double polar_radius_m =
radius_m * (1.0 - oblateness_factor); // Polar radius is reduced by oblateness
// Angular velocity (omega) based on day length (convert hours to seconds)
long double day_seconds = the_planet->getDay() * 3600;
long double angular_velocity = (day_seconds > 0) ? (2 * std::numbers::pi / day_seconds) : 0.0;
// Adjust gravity for centrifugal force at the equator
long double centrifugal_force =
angular_velocity * angular_velocity * radius_m; // Centrifugal force at equator
long double gravity_equator = G * mass_kg / std::pow(radius_m, 2) - centrifugal_force;
// Gravity at the poles (no centrifugal force)
long double gravity_pole = G * mass_kg / std::pow(polar_radius_m, 2);
// Average gravity (you could use a weighted average if necessary)
long double average_gravity = (gravity_equator + gravity_pole) / 2.0;
// Handle different mass regimes for the final gravity calculation
long double mass_earth_masses = mass_kg / EARTH_MASS;
if (mass_earth_masses < 1.0) {
// Rocky bodies below Earth mass: gs ~ M^(1/2)
average_gravity = EARTH_GRAVITY * std::pow(mass_earth_masses, 0.5);
} else if (mass_earth_masses < 100.0) {
// Transition zone: gravity remains roughly constant
average_gravity = std::max(0.8 * EARTH_GRAVITY, std::min(average_gravity, 1.2 * EARTH_GRAVITY));
}
// For gas giants (mass > 100 Earth masses), we'll use the calculated gravity directly
return average_gravity;
}
/*---------------------------------------------------------------------*/
/* This function calculates the surface gravity of a planet. The */
/* acceleration is in units of cm/sec2, and the gravity is returned in */
/* units of Earth gravities. */
/*---------------------------------------------------------------------*/
auto gravity(long double acceleration) -> long double {
return (acceleration / EARTH_ACCELERATION);
}
/*---------------------------------------------------------------------------*/
/* This implements Fogg's eq.17. The 'inventory' returned is unitless. */
/*---------------------------------------------------------------------------*/
auto vol_inventory(long double mass, long double escape_vel,
long double rms_vel, long double stellar_mass,
int zone, bool greenhouse_effect, bool accreted_gas) -> long double {
long double velocity_ratio = NAN, proportion_const = NAN, temp1 = NAN, temp2 = NAN, earth_units = NAN;
velocity_ratio = escape_vel / rms_vel;
if (velocity_ratio >= GAS_RETENTION_THRESHOLD || accreted_gas) {
switch (zone) {
case 1:
proportion_const = 140000.0; /* 100 -> 140 JLB */
break;
case 2:
proportion_const = 75000.0;
break;
case 3:
proportion_const = 250.0;
break;
default:
std::cout << "Error: orbital zone not initialized correctly!\n";
exit(EXIT_FAILURE);
return EXIT_FAILURE;
break;
}
earth_units = mass * SUN_MASS_IN_EARTH_MASSES;
temp1 = (proportion_const * earth_units) / stellar_mass;
temp2 = temp1;
if (greenhouse_effect || accreted_gas) {
return temp2;
} else {
return temp2 / 140.0;
}
} else {
return 0.0;
}
}
/*------------------------------------------------------------------------------*/
/* This implements Fogg's eq.18. The pressure returned is in units of */
/* millibars (mb). The gravity is in units of Earth gravities, the radius
*/
/* in units of kilometers. */
/* */
/* JLB: Aparently this assumed that earth pressure = 1000mb. I've added a
*/
/* fudge factor (EARTH_SURF_PRES_IN_MILLIBARS / 1000.) to correct for that
*/
/*------------------------------------------------------------------------------*/
auto pressure(long double volatile_gas_inventory,
long double equat_radius, long double gravity) -> long double {
equat_radius = KM_EARTH_RADIUS / equat_radius;
return volatile_gas_inventory * gravity *
(EARTH_SURF_PRES_IN_MILLIBARS / 1000.0) / pow2(equat_radius);
}
/*---------------------------------------------------------------------------*/
/* This function returns the boiling point of water in an atmosphere of */
/* pressure 'surf_pressure', given in millibars. The boiling point is */
/* returned in units of Kelvin. This is Fogg's eq.21. */
/*---------------------------------------------------------------------------*/
auto boiling_point(long double surf_pressure) -> long double {
long double surface_pressure_in_bars = NAN;
surface_pressure_in_bars = surf_pressure / MILLIBARS_PER_BAR;
return 1.0 / ((log(surface_pressure_in_bars) / -5050.5) + (1.0 / 373.0));
}
/*----------------------------------------------------------------------------*/
/* This function is Fogg's eq.22. Given the volatile gas inventory and */
/* planetary radius of a planet (in Km), this function returns the */
/* fraction of the planet covered with water. */
/* I have changed the function very slightly: the fraction of Earth's */
/* surface covered by water is 71%, not 75% as Fogg used. */
/*----------------------------------------------------------------------------*/
auto hydro_fraction(long double volatile_gas_inventory,
long double planet_radius) -> long double {
long double temp = NAN;
temp = (0.71 * volatile_gas_inventory / 1000.0) *
pow2(KM_EARTH_RADIUS / planet_radius);
if (temp >= 1.0) {
return 1.0;
} else {
return temp;
}
}
/*-----------------------------------------------------------------------*/
/* Given the surface temperature of a planet (in Kelvin), this function */
/* returns the fraction of cloud cover available. This is Fogg's eq.23. */
/* See Hart in "Icarus" (vol 33, pp23 - 39, 1978) for an explanation. */
/* This equation is Hart's eq.3. */
/* I have modified it slightly using constants and relationships from */
/* Glass's book "Introduction to Planetary Geology", p.46. */
/* The 'CLOUD_COVERAGE_FACTOR' is the amount of surface area on Earth */
/* covered by one Kg. of cloud. */
/*-----------------------------------------------------------------------*/
auto cloud_fraction(long double surf_temp,
long double smallest_MW_retained,
long double equat_radius,
long double hydro_fraction) -> long double {
long double water_vapor_in_kg = NAN, fraction = NAN, surf_area = NAN, hydro_mass = NAN;
if (smallest_MW_retained > WATER_VAPOR) {
return 0.0;
} else {
surf_area = 4.0 * PI * pow2(equat_radius);
hydro_mass = hydro_fraction * surf_area * EARTH_WATER_MASS_PER_AREA;
water_vapor_in_kg = (0.00000001 * hydro_mass) *
exp(Q2_36 * (surf_temp - EARTH_AVERAGE_KELVIN));
fraction = CLOUD_COVERAGE_FACTOR * water_vapor_in_kg / surf_area;
if (fraction >= 1.0) {
return 1.0;
} else {
return fraction;
}
}
}
/*------------------------------------------------------------------------------*/
/* Given the surface temperature of a planet (in Kelvin), this function */
/* returns the fraction of the planet's surface covered by ice. This is */
/* Fogg's eq.24. See Hart[24] in Icarus vol.33, p.28 for an explanation.
*/
/* I have changed a constant from 70 to 90 in order to bring it more in */
/* line with the fraction of the Earth's surface covered with ice, which */
/* is approximatly .016 (=1.6%). */
/*------------------------------------------------------------------------------*/
auto ice_fraction(long double hydro_fraction, long double surf_temp) -> long double {
long double temp = NAN;
if (surf_temp > 328.0) {
surf_temp = 328.0;
}
temp = std::pow(((328.0 - surf_temp) / 90.0), 5.0);
if (temp > (1.5 * hydro_fraction)) {
temp = 1.5 * hydro_fraction;
}
if (temp >= 1.0) {
return 1.0;
} else {
return temp;
}
}
/*--------------------------------------------------------------------------*/
/* This is Fogg's eq.19. The ecosphere radius is given in AU, the orbital */
/* radius in AU, and the temperature returned is in Kelvin. */
/*--------------------------------------------------------------------------*/
auto eff_temp(long double ecosphere_radius, long double orb_radius,
long double albedo) -> long double {
return sqrt(ecosphere_radius / orb_radius) *
pow1_4((1.0 - albedo) / (1.0 - EARTH_ALBEDO)) * EARTH_EFFECTIVE_TEMP;
}