Exercises
- Recover the ellipse and hyperbola from their time equations. Change the eccentricity while keeping one observed time fixed.
- Double the number of integration steps in a circular orbit. Compare the final position error and angular momentum conservation.
- Recover inserted star counts from simulated bias, dark, and flat effects. Change the assumed sky by ten electrons per pixel, then predict the signal change.
- Calculate the distance to redshift one using two midpoint grids. Compare numerical refinement with the effect of changing the matter density.
Run the code
Copy the following into a file named astrophysics-lab.py. Run python astrophysics-lab.py from that folder.
"""Four reproducible astrophysics exercises using only Python's standard library.
All detector counts and model parameters are instructional inputs.
"""
from math import asinh, cos, cosh, isclose, pi, sin, sinh, sqrt
def bisect(residual, lo, hi, tolerance=1e-12):
"""Solve a monotonically increasing residual with a known bracket."""
if not residual(lo) <= 0 <= residual(hi):
raise ValueError("The interval does not bracket a root")
while hi - lo > tolerance:
midpoint = (lo + hi) / 2
if residual(midpoint) < 0:
lo = midpoint
else:
hi = midpoint
return (lo + hi) / 2
def ellipse(mean_anomaly, eccentricity, semimajor_axis):
anomaly = bisect(
lambda angle: angle - eccentricity * sin(angle) - mean_anomaly,
mean_anomaly - 1,
mean_anomaly + 1,
)
return anomaly, semimajor_axis * (1 - eccentricity * cos(anomaly))
def hyperbola(mean_anomaly, eccentricity, positive_axis_scale):
sign = -1 if mean_anomaly < 0 else 1
magnitude = abs(mean_anomaly)
bound = asinh(magnitude / eccentricity) + 1
while eccentricity * sinh(bound) - bound < magnitude:
bound *= 2
anomaly = sign * bisect(
lambda angle: eccentricity * sinh(angle) - angle - magnitude, 0, bound
)
return anomaly, positive_axis_scale * (eccentricity * cosh(anomaly) - 1)
def acceleration(x, y):
radius_cubed = (x * x + y * y) ** 1.5
return -x / radius_cubed, -y / radius_cubed
def circular_verlet(steps):
"""Integrate one circular period in units with mu, initial r and speed all 1."""
dt = 2 * pi / steps
x, y, vx, vy = 1.0, 0.0, 0.0, 1.0
ax, ay = acceleration(x, y)
max_energy_drift = 0.0
for _ in range(steps):
x += vx * dt + 0.5 * ax * dt * dt
y += vy * dt + 0.5 * ay * dt * dt
next_ax, next_ay = acceleration(x, y)
vx += 0.5 * (ax + next_ax) * dt
vy += 0.5 * (ay + next_ay) * dt
ax, ay = next_ax, next_ay
energy = 0.5 * (vx * vx + vy * vy) - 1 / sqrt(x * x + y * y)
max_energy_drift = max(max_energy_drift, abs(energy + 0.5))
return sqrt((x - 1) ** 2 + y * y), max_energy_drift, abs(x * vy - y * vx - 1)
def aperture_signal(raw_counts, sky_per_pixel, bias, matched_dark, flats):
if len(raw_counts) != len(flats) or not all(flat > 0 for flat in flats):
raise ValueError("Every pixel needs a valid flat")
calibrated = [
(pixel - bias - matched_dark) / flat for pixel, flat in zip(raw_counts, flats)
]
return sum(value - sky_per_pixel for value in calibrated)
def weighted_level(observations, common_error):
weight_sum = sum(1 / sigma**2 for _, sigma in observations)
weighted = sum(value / sigma**2 for value, sigma in observations) / weight_sum
return weighted, sqrt(1 / weight_sum), sqrt(1 / weight_sum + common_error**2)
def flat_distance(z, intervals, h0=70.0, matter=0.3):
"""Return comoving and luminosity distances in Mpc, ignoring radiation."""
dz = z / intervals
total = sum(
1 / sqrt(matter * (1 + (i + 0.5) * dz) ** 3 + (1 - matter))
for i in range(intervals)
)
comoving = (299792.458 / h0) * dz * total
return comoving, (1 + z) * comoving
def main():
anomaly, radius = ellipse(pi / 2 - 0.5, 0.5, 1)
assert isclose(anomaly, pi / 2, abs_tol=1e-10)
assert isclose(radius, 1, abs_tol=1e-10)
unbound, unbound_radius = hyperbola(1.5 * sinh(1) - 1, 1.5, 2)
assert isclose(unbound, 1, abs_tol=1e-10)
assert isclose(unbound_radius, 2.62924, abs_tol=1e-5)
coarse_orbit, fine_orbit = circular_verlet(64), circular_verlet(128)
assert fine_orbit[0] < coarse_orbit[0] / 3
assert fine_orbit[1] < coarse_orbit[1]
assert max(fine_orbit[2], coarse_orbit[2]) < 1e-10
flat = [0.98, 1.02, 1.00, 0.99, 1.01]
injected = [100, 250, 800, 250, 100]
raw = [120 + factor * (100 + signal) for factor, signal in zip(flat, injected)]
recovered = aperture_signal(raw, 100, 100, 20, flat)
estimate, random_error, total_error = weighted_level([(10, 1), (14, 2), (8, 2)], 0.5)
assert isclose(recovered, 1500)
assert isclose(estimate, 31 / 3)
coarse_distance, fine_distance = flat_distance(1, 16), flat_distance(1, 1024)
assert abs(coarse_distance[0] - fine_distance[0]) < 1
assert isclose(fine_distance[0], 3303.829, abs_tol=0.01)
assert flat_distance(0, 64) == (0, 0)
print(f"Ellipse: E={anomaly:.6f}, r={radius:.6f}")
print(f"Hyperbola: H={unbound:.6f}, r={unbound_radius:.6f}")
print(f"Verlet end-position error: {coarse_orbit[0]:.6f} -> {fine_orbit[0]:.6f}")
print(f"Matched aperture count: {recovered:.0f} electrons")
print(f"Weighted level: {estimate:.3f} +/- {random_error:.3f} (random), {total_error:.3f} (total)")
print(f"z=1: {fine_distance[0]:.3f} Mpc comoving, {fine_distance[1]:.3f} Mpc luminosity")
print(f"Distance refinement delta: {abs(coarse_distance[0] - fine_distance[0]):.6f} Mpc")
if __name__ == "__main__":
main()
Expected output
Ellipse: E=1.570796, r=1.000000 Hyperbola: H=1.000000, r=2.629242 Verlet end-position error: 0.020113 -> 0.005042 Matched aperture count: 1500 electrons Weighted level: 10.333 +/- 0.816 (random), 0.957 (total) z=1: 3303.829 Mpc comoving, 6607.658 Mpc luminosity Distance refinement delta: 0.083896 Mpc
Interpreting the checks
Agreement with the known orbit or injected source tests the formulas and implementation. It does not establish observational accuracy. The distance grid check addresses integration sensitivity for the stated cosmology. It does not measure the true amount of matter.