-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulation_kernel.py
More file actions
1174 lines (853 loc) · 35.6 KB
/
Copy pathsimulation_kernel.py
File metadata and controls
1174 lines (853 loc) · 35.6 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
"""
The simulation kernel.
Owns the clock, the expansion history, the galaxy catalogue, the
stellar population of whichever galaxy the observer is in, and the
observer themselves.
Two design choices are worth stating up front.
The state of the universe is a *function of cosmic time*, not an
accumulation of steps. Nothing integrates, so jumping a billion years
forward costs the same as advancing a single frame, running the clock
backwards to the Big Bang is exact, and there is no drift to correct.
The observer's position is stored relative to the galaxy they are
currently in, in parsecs, and rebased when they arrive somewhere new.
Absolute coordinates spanning the observable universe would need far
more precision than a float can offer; galaxy-relative coordinates
need almost none.
"""
import threading
import time as wallclock
from dataclasses import dataclass, field
import numpy as np
from simulation_constants import (
C,
YEAR,
MYR,
GYR,
PARSEC,
KPC,
MPC,
AU,
RANDOM_SEED,
GALAXY_COUNT,
STAR_COUNT,
UNIVERSE_RADIUS_MPC,
MAX_FUTURE_TIME,
DEFAULT_TIME_RATE,
MAX_TIME_RATE,
)
from cosmology.cosmictime.time import CosmicTime, format_cosmic_time
from cosmology.expansion.scale_factor import ExpansionModel, PRESENT_AGE, describe_epoch
from cosmology.hubbleflow import HubbleFlow
from galaxy_pop.galaxy_formation import (
generate_catalogue,
MORPH_NAMES,
MORPH_SPIRAL,
)
from galaxy_pop.mergers import resolve_mergers
from stellar_pop.stellar_evolution.population import (
StellarPopulation,
PHASE_REMNANT,
)
from stellar_pop.stellar_evolution.relations import (
FATE_BLACK_HOLE,
FATE_DIRECT_COLLAPSE,
)
from stellar_pop.supernovae import SN_TYPE_NAMES
from compact_objects.black_holes import eddington_luminosity_watts, shadow_radius
from compact_objects.quasars import (
duty_cycle,
bolometric_luminosity,
eddington_ratio_distribution,
)
from planetary_systems.formation import generate_system
PARSEC_PER_MPC = 1.0e6
_NOTHING = np.empty(0, dtype=np.intp)
# Rebuilding the young stellar population re-sorts the whole event
# schedule, so it is rate limited in real time however fast the
# simulated clock is running.
RESEED_MIN_REAL_SECONDS = 2.0
# How much of the expected rebuild time to aim ahead by. Below one, so
# the clock lands just past the planned epoch rather than short of it.
RESEED_LEAD_FRACTION = 0.85
# Likewise for recomputing which black holes are currently quasars,
# and for resolving galaxy mergers.
QUASAR_MIN_REAL_SECONDS = 0.5
MERGER_MIN_REAL_SECONDS = 0.25
# Adopting a new host galaxy means building its whole stellar
# population, so it is rate limited however fast the observer is
# moving. Without this, crossing intergalactic space at speed queues
# a rebuild every frame.
REBASE_MIN_REAL_SECONDS = 2.0
# Travel speed is set by the distance to the nearest object, so that
# the same control works beside a planet and between galaxies. Both
# ends of that range have to be bounded: without an upper bound the
# observer accelerates away from everything for ever, since the
# further out they get the further away the nearest object is.
MIN_TRAVEL_REFERENCE_M = 1.0e9
MAX_TRAVEL_REFERENCE_M = 3.0e24
# Seconds to cross the reference distance at speed_setting 1.
TRAVEL_CROSSING_SECONDS = 4.0
# No single frame may move the observer more than this fraction of the
# reference distance. A long frame would otherwise fling them much
# further than a short one, putting them somewhere emptier and faster,
# which makes the next frame longer still.
MAX_STEP_FRACTION = 0.35
class BackgroundBuild:
"""
One piece of heavy NumPy work, run off the main thread.
Building a galaxy's stars takes half a second. Doing that inside a
frame drops the frame rate to two for as long as it takes, which is
exactly the sort of stall the user notices when flying between
galaxies. NumPy releases the interpreter lock for the array
operations that dominate here, so a plain thread genuinely overlaps
with rendering.
The work must only *read* simulation state. Installing the result
is the caller's job, on the main thread.
"""
def __init__(self, name, function, *args, **kwargs):
self.name = name
self.result = None
self.error = None
self.started = wallclock.perf_counter()
self._thread = threading.Thread(
target=self._run, args=(function, args, kwargs), daemon=True
)
self._thread.start()
def _run(self, function, args, kwargs):
try:
self.result = function(*args, **kwargs)
except BaseException as error: # surfaced on the main thread
self.error = error
@property
def done(self):
return not self._thread.is_alive()
@property
def elapsed(self):
return wallclock.perf_counter() - self.started
@dataclass(slots=True)
class SimulationEvent:
event_type: str
object_id: int
cosmic_time: float
data: dict = field(default_factory=dict)
def __str__(self) -> str:
return f"[{format_cosmic_time(self.cosmic_time)}] {self.event_type}"
@dataclass(slots=True)
class Observer:
"""
Where the user is, and how fast they are going.
Position is in parsecs relative to the centre of `galaxy_index`.
"""
galaxy_index: int = 0
position_pc: np.ndarray = field(default_factory=lambda: np.zeros(3))
velocity_c: float = 0.0
speed_setting: float = 1.0
def position_mpc(self, catalogue):
centre = catalogue["position_mpc"][self.galaxy_index].astype(np.float64)
return centre + self.position_pc / PARSEC_PER_MPC
def distance_from_galaxy_centre_m(self):
return float(np.linalg.norm(self.position_pc)) * PARSEC
class SimulationKernel:
def __init__(self, seed=RANDOM_SEED, galaxy_count=GALAXY_COUNT, star_count=STAR_COUNT):
self.rng = np.random.default_rng(seed)
self.seed = seed
self.expansion = ExpansionModel()
self.hubble = HubbleFlow(self.expansion)
self.time = CosmicTime(PRESENT_AGE)
self.galaxy_count = int(galaxy_count)
self.star_count = int(star_count)
self.time_rate = DEFAULT_TIME_RATE
self.paused = False
self.events = []
self.event_log = []
self.catalogue = None
self.population = None
self.observer = Observer()
self._system_cache = {}
self._quasar_luminosity = None
self._real_time_marks = {}
self._pending_galaxy = None
self._pending_reseed = None
# Seeded with a plausible first guess; measured thereafter.
self._last_reseed_seconds = 0.2
# Set for one frame whenever the star population object is
# swapped out, so the renderer knows to rebuild its buffers.
self.population_replaced = False
self.initialized = False
# --------------------------------------------------------
# Setup
# --------------------------------------------------------
def initialize(self, progress=None):
if self.initialized:
return
def report(message):
if progress is not None:
progress(message)
report("Solving the expansion history...")
report(f"Generating {self.galaxy_count:,} galaxies...")
self.catalogue = generate_catalogue(
self.galaxy_count, self.rng, self.expansion, UNIVERSE_RADIUS_MPC
)
# Put the observer in a large spiral near the centre of the
# volume, which is the analogue of standing in the Milky Way.
self.observer.galaxy_index = self._pick_home_galaxy()
report(f"Populating the home galaxy with {self.star_count:,} stars...")
self.population = self._build_population(self.observer.galaxy_index)
report("Lighting the quasars...")
self._update_quasars()
self.observer.position_pc = np.array([0.0, 0.0, -8_000.0])
self.initialized = True
report("Ready.")
def _pick_home_galaxy(self):
catalogue = self.catalogue
spiral = catalogue["morphology"] == MORPH_SPIRAL
distance = np.linalg.norm(catalogue["position_mpc"], axis=1)
# A big spiral, close to the middle of the simulated volume.
score = np.where(spiral, catalogue["stellar_mass"], 0.0) / (1.0 + distance)
return int(np.argmax(score))
def _build_population(self, galaxy_index):
catalogue = self.catalogue
morphology = int(catalogue["morphology"][galaxy_index])
radius = float(catalogue["radius"][galaxy_index])
# A deterministic per-galaxy stream, so the same galaxy always
# has the same stars however many times you leave and return.
rng = np.random.default_rng((self.seed * 1_000_003 + galaxy_index) % (2**63))
return StellarPopulation(
self.star_count,
rng,
self.expansion,
radius,
morphology,
)
def _build_population_at(self, galaxy_index, cosmic_time):
"""
Build a galaxy's stars and bring them to a given epoch.
Both halves run on the worker thread, so installing the result
on the main thread is only a reference swap.
"""
population = self._build_population(galaxy_index)
population.evaluate_all(cosmic_time)
return population
# --------------------------------------------------------
# The clock
# --------------------------------------------------------
@property
def cosmic_time(self):
return self.time.seconds
def universe_age_gyr(self):
return self.time.seconds / GYR
def step(self, real_dt):
"""
Advance one frame. Returns the indices of the stars whose
appearance changed, ready to be handed to the renderer.
"""
self.events.clear()
# A paused universe is unchanging, so there is nothing to
# recompute and nothing to re-upload.
if self.paused or real_dt <= 0.0:
return _NOTHING
simulated_dt = real_dt * self.time_rate * YEAR
target = min(self.time.seconds + simulated_dt, MAX_FUTURE_TIME)
if target <= self.time.seconds:
return _NOTHING
self.time.jump_to(target)
changed = self.population.advance_to(target)
self._collect_supernovae(target)
# The young stellar population turns over as the galaxy keeps
# forming stars, so it is redrawn when the epoch has moved far
# enough for the old draw to be meaningless.
#
# The test has to be against the wall clock as well as against
# simulated time. At a trillion years per second three hundred
# million years elapse in a third of a millisecond, and
# redrawing the population every frame would cost more than
# everything else in the simulator put together.
if self.population.young_population_is_stale(
target, 300.0 * MYR
) and self._real_seconds_since("reseed", RESEED_MIN_REAL_SECONDS):
self._start_reseed(target)
self._maybe_update_slow_systems(simulated_dt)
finished = self.poll_background()
return finished if finished is not None else changed
def jump_to(self, cosmic_time):
"""
Move the clock anywhere, including backwards.
This is the one place a stall is acceptable: it is a deliberate
action with a visible result, so it is done synchronously and
the user sees the new epoch on the very next frame.
"""
self.events.clear()
target = float(np.clip(cosmic_time, 0.0, MAX_FUTURE_TIME))
self.time.jump_to(target)
changed = self.population.reseed_young_population(target)
self._update_quasars()
self._system_cache.clear()
self._log(
SimulationEvent(
"time jump",
-1,
target,
{"epoch": describe_epoch(target)},
)
)
return changed
def jump_by(self, seconds):
return self.jump_to(self.time.seconds + seconds)
def go_to_big_bang(self):
return self.jump_to(0.0)
def go_to_present(self):
return self.jump_to(PRESENT_AGE)
def cycle_time_rate(self, factor=10.0):
self.time_rate *= factor
if self.time_rate > MAX_TIME_RATE:
self.time_rate = 1.0
elif self.time_rate < 1.0:
self.time_rate = MAX_TIME_RATE
return self.time_rate
# --------------------------------------------------------
# Background work
# --------------------------------------------------------
def _start_reseed(self, cosmic_time):
"""
Redraw the short-lived stellar population on a worker thread.
The plan is built for where the clock is *expected to be* when
the worker finishes, not for where it is now. At a billion
years a second, the two hundred milliseconds a rebuild takes
covers two hundred million years of stellar evolution, and
catching up that much history in the frame the plan lands on
costs more than the rebuild saved.
The estimate is deliberately short, so the clock has usually
just passed the planned epoch rather than not yet reached it:
catching up a little is cheap, whereas a plan from the future
would have to be thrown away.
"""
if self._pending_reseed is not None or self._pending_galaxy is not None:
return
lead = 0.0
if not self.paused:
lead = (
RESEED_LEAD_FRACTION
* self._last_reseed_seconds
* self.time_rate
* YEAR
)
target = min(cosmic_time + lead, MAX_FUTURE_TIME)
rng = np.random.default_rng(self.rng.integers(0, 2**62))
self._pending_reseed = BackgroundBuild(
"reseed", self.population.plan_young_reseed, target, rng
)
def _start_galaxy_build(self, galaxy_index):
if self._pending_galaxy is not None:
return
self._pending_galaxy = BackgroundBuild(
"galaxy", self._build_population_at, int(galaxy_index), self.time.seconds
)
self._pending_galaxy.galaxy_index = int(galaxy_index)
def poll_background(self):
"""
Install any finished background work. Returns the indices that
need re-uploading, or None if nothing completed.
"""
self.population_replaced = False
pending = self._pending_galaxy
if pending is not None and pending.done:
self._pending_galaxy = None
if pending.error is not None:
self._log(
SimulationEvent(
"galaxy build failed",
pending.galaxy_index,
self.time.seconds,
{"error": type(pending.error).__name__},
)
)
else:
self.population = pending.result
# The clock kept running while the build was going, so
# walk the new population forward over the events it
# missed. That is the incremental path, not a full
# re-evaluation, so it costs a fraction of a
# millisecond rather than tens of them.
if self.population.cosmic_time != self.time.seconds:
self.population.advance_to(self.time.seconds)
self.population_replaced = True
self._system_cache.clear()
catalogue = self.catalogue
index = pending.galaxy_index
self._log(
SimulationEvent(
"arrived at galaxy",
index,
self.time.seconds,
{
"morphology": MORPH_NAMES[
int(catalogue["morphology"][index])
],
"stellar_mass": float(catalogue["stellar_mass"][index]),
},
)
)
return np.arange(self.population.count)
pending = self._pending_reseed
if pending is not None and pending.done:
self._pending_reseed = None
self._last_reseed_seconds = pending.elapsed
if pending.error is not None:
return None
# The estimate overshot and the plan is for an epoch that
# has not arrived. Installing it would mean evaluating the
# whole population backwards, which is exactly the stall
# this machinery exists to avoid, so drop it and let the
# next attempt aim better.
if self.time.seconds < pending.result["reference_time"]:
self._real_time_marks.pop("reseed", None)
return None
return self.population.apply_young_reseed(
pending.result, self.time.seconds
)
return None
@property
def is_loading(self):
return self._pending_galaxy is not None
# --------------------------------------------------------
# Slow subsystems
# --------------------------------------------------------
def _real_seconds_since(self, name, minimum):
"""
True at most once per `minimum` seconds of wall clock.
Several subsystems are naturally paced by simulated time, but
simulated time can run twenty orders of magnitude faster than
real time. Anything expensive needs both limits.
"""
now = wallclock.perf_counter()
last = self._real_time_marks.get(name)
if last is not None and now - last < minimum:
return False
self._real_time_marks[name] = now
return True
def _maybe_update_slow_systems(self, simulated_dt):
"""
Mergers and quasar activity change over hundreds of millions of
years. Recomputing them every frame would be wasted work, so
they are driven by accumulated simulated time instead.
"""
self._merger_accumulator = getattr(self, "_merger_accumulator", 0.0) + simulated_dt
if self._merger_accumulator < 20.0 * MYR:
return
if not self._real_seconds_since("mergers", MERGER_MIN_REAL_SECONDS):
return
dt = self._merger_accumulator
self._merger_accumulator = 0.0
merged = resolve_mergers(
self.catalogue, dt, self.time.seconds, self.expansion, self.rng
)
for event in merged:
self._log(
SimulationEvent(
"galaxy merger" if event.is_major else "minor merger",
event.primary_index,
event.cosmic_time,
{"mass_ratio": round(event.mass_ratio, 3)},
)
)
if self._real_seconds_since("quasars", QUASAR_MIN_REAL_SECONDS):
self._update_quasars()
def _update_quasars(self):
"""
Decide which supermassive black holes are shining right now.
"""
catalogue = self.catalogue
z = float(self.expansion.redshift(self.time.seconds))
masses = catalogue["smbh_mass"]
active = self.rng.random(masses.shape) < duty_cycle(z)
ratios = eddington_ratio_distribution(self.rng, masses.shape[0], z)
self._quasar_luminosity = np.where(
active & (catalogue["formation_time"] <= self.time.seconds),
bolometric_luminosity(masses, ratios),
0.0,
)
self.quasar_count = int((self._quasar_luminosity > 1.0e38).sum())
@property
def quasar_luminosity(self):
return self._quasar_luminosity
def _collect_supernovae(self, cosmic_time):
"""
Turn newly exploded stars into events the UI can announce.
"""
population = self.population
exploding = population.active_supernovae(cosmic_time)
if exploding.size == 0:
self.supernova_indices = exploding
return
self.supernova_indices = exploding
previous = getattr(self, "_announced_supernovae", set())
fresh = [int(i) for i in exploding if int(i) not in previous]
for index in fresh[:8]:
self._log(
SimulationEvent(
"supernova",
index,
cosmic_time,
{
"type": SN_TYPE_NAMES[int(population.sn_type[index])],
"mass_solar": float(population.mass[index]),
},
)
)
self._announced_supernovae = set(int(i) for i in exploding)
def _log(self, event):
self.events.append(event)
self.event_log.append(event)
if len(self.event_log) > 256:
del self.event_log[:128]
# --------------------------------------------------------
# Interaction
# --------------------------------------------------------
def force_supernova(self, star_index=None):
"""
Detonate a star. With no argument, the nearest massive star
that is still burning.
"""
population = self.population
if star_index is None:
star_index = self.nearest_massive_star()
if star_index is None:
return None
result = population.force_supernova(int(star_index), self.time.seconds)
if result is None:
return None
self._log(
SimulationEvent(
"induced supernova",
int(star_index),
self.time.seconds,
{
"type": result,
"mass_solar": float(population.mass[int(star_index)]),
},
)
)
return result
def nearest_star(self):
return self.population.nearest(self.observer.position_pc)
def nearest_massive_star(self, minimum_mass=8.0):
"""
The closest star that could actually undergo core collapse.
"""
population = self.population
candidates = population.massive_living_stars(minimum_mass)
if candidates.size == 0:
return None
delta = population.position_pc[candidates] - self.observer.position_pc.astype(
np.float32
)
return int(candidates[np.argmin(np.einsum("ij,ij->i", delta, delta))])
def planetary_system(self, star_index):
"""
The planets of one star, generated on demand and cached.
"""
star_index = int(star_index)
cached = self._system_cache.get(star_index)
if cached is not None:
return cached
population = self.population
system = generate_system(
star_index,
float(population.mass[star_index]),
float(max(population.luminosity[star_index], 1.0e-6)),
float(population.metallicity[star_index]),
seed=self.seed,
)
if len(self._system_cache) > 64:
self._system_cache.clear()
self._system_cache[star_index] = system
return system
# --------------------------------------------------------
# Black holes
# --------------------------------------------------------
@staticmethod
def _deterministic(seed_value, count=3):
"""
A stable handful of uniform deviates for one object, so its
spin and orientation never change between visits.
"""
rng = np.random.default_rng(int(seed_value) & 0x7FFFFFFF)
return rng.random(count)
def black_hole_spin_and_axis(self, identifier):
"""
Spin magnitude and orientation for one hole.
Accretion spins a black hole up towards the Thorne limit of
a = 0.998, so an actively feeding hole is a fast rotator; the
axis is fixed once and for all by the angular momentum of
what formed it.
"""
u = self._deterministic(identifier, 4)
spin = 0.35 + 0.6 * u[0]
theta = np.arccos(2.0 * u[1] - 1.0)
phi = 2.0 * np.pi * u[2]
axis = np.array(
[
np.sin(theta) * np.cos(phi),
np.cos(theta),
np.sin(theta) * np.sin(phi),
]
)
return float(spin), axis
def stellar_black_hole_accretion(self, star_index):
"""
Eddington ratio of a stellar-mass black hole.
Most are isolated and utterly dark. A few per cent have a
companion close enough to spill gas over its Roche lobe, and
those are the X-ray binaries: bright, jetted microquasars.
"""
u = self._deterministic(int(star_index) * 7919 + 13, 2)
if u[0] > 0.06:
return 0.0
return float(10.0 ** (-2.2 + 2.2 * u[1]))
def nearby_black_holes(self, limit=2, max_distance_m=2.0e17):
"""
Stellar-mass black holes close enough to resolve.
"""
population = self.population
candidates = np.flatnonzero(
(population.phase == PHASE_REMNANT)
& (population.fate >= FATE_BLACK_HOLE)
& (population.fate <= FATE_DIRECT_COLLAPSE)
)
if candidates.size == 0:
return []
# In float64. Positions are stored as float32, which is
# plenty for placing a star inside a galaxy but quantises to
# a couple of hundred AU - useless once the observer is a few
# thousand kilometres from a black hole.
delta = population.position_pc[candidates].astype(np.float64) - (
self.observer.position_pc
)
distance_pc = np.sqrt(np.einsum("ij,ij->i", delta, delta))
order = np.argsort(distance_pc)[:limit]
found = []
for slot in order:
if distance_pc[slot] * PARSEC > max_distance_m:
break
index = int(candidates[slot])
spin, axis = self.black_hole_spin_and_axis(index)
found.append(
{
"index": index,
"offset_m": delta[slot] * PARSEC,
"mass_solar": float(population.remnant_mass[index]),
"spin": spin,
"axis": axis,
"eddington_ratio": self.stellar_black_hole_accretion(index),
}
)
return found
def nearest_feeding_black_hole(self):
"""
The closest stellar-mass black hole that is actually
accreting, and so has a disc and jets to look at.
"""
population = self.population
candidates = np.flatnonzero(
(population.phase == PHASE_REMNANT)
& (population.fate >= FATE_BLACK_HOLE)
& (population.fate <= FATE_DIRECT_COLLAPSE)
)
if candidates.size == 0:
return None
feeding = [
int(index)
for index in candidates
if self.stellar_black_hole_accretion(int(index)) > 0.0
]
if not feeding:
return None
delta = population.position_pc[feeding] - self.observer.position_pc.astype(
np.float32
)
return feeding[int(np.argmin(np.einsum("ij,ij->i", delta, delta)))]
def brightest_active_nucleus(self):
"""
The galaxy whose central black hole is currently shining
hardest. Returns None when nothing is active, which is the
usual state of affairs in the local universe.
"""
if self._quasar_luminosity is None:
return None
index = int(np.argmax(self._quasar_luminosity))
if self._quasar_luminosity[index] <= 0.0:
return None
return index
def central_black_hole(self):
"""
The supermassive black hole at the centre of the host galaxy.
Its Eddington ratio comes from the quasar model, so it lights
up during the epochs when quasars were common and sits dark
today.
"""
index = self.observer.galaxy_index
mass = float(self.catalogue["smbh_mass"][index])
spin, axis = self.black_hole_spin_and_axis(index + 1_000_003)
luminosity = 0.0
if self._quasar_luminosity is not None:
luminosity = float(self._quasar_luminosity[index])
eddington = 0.0
if luminosity > 0.0:
eddington = luminosity / float(eddington_luminosity_watts(mass))
return {
"offset_m": -self.observer.position_pc * PARSEC,
"mass_solar": mass,
"spin": spin,
"axis": axis,
"eddington_ratio": float(np.clip(eddington, 0.0, 2.0)),
}
# --------------------------------------------------------
# Travel
# --------------------------------------------------------
def move_observer(self, direction, real_dt, boost=1.0):
"""
Fly. `direction` is a unit vector in the observer's frame.
Travel speed scales with how far away the nearest thing is, so
the same control both crosses a hundred million light years and
creeps up on a planet. The speed is reported honestly as a
multiple of c: this is a map, not a spacecraft.
"""
if real_dt <= 0.0:
return
reference = self.travel_reference_distance_m()
speed_m_s = (
reference
/ TRAVEL_CROSSING_SECONDS
* self.observer.speed_setting
* boost
)
step_m = speed_m_s * real_dt
# Never cross more than a fraction of the reference distance in
# one frame, whatever the frame took.
step_m = min(step_m, MAX_STEP_FRACTION * reference)