Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Part 2: Inferential Thinking

The Statistical Universe | Module 5 | COMP 521

Learning Outcomes

By the end of Part 2, you will be able to:


Part 2: From Beliefs to Mathematics

How do we transform vague beliefs into rigorous inference?

Core Question: How do we transform statements like “this star probably has little dust” into a mathematical framework that can connect observations to physical parameters under uncertainty?

Observable →\to Model →\to Inference roadmap

This section develops the mathematical language that makes that pipeline possible.


2.1 Probability as Extended Logic

Priority - 🔴 Essential:

What Are We Actually Doing? Epistemology

At its core, this section is about epistemology — the study of how we know things — because astronomy almost never gives us the physical quantities we care about directly.

We do not directly observe stellar mass, distance, age, or composition. We do observe light curves, spectra, colors, images, and apparent brightness.

That means astronomy always begins with an observable, then requires a model connecting those observables to physical reality, and finally demands inference to determine which physical explanations are most plausible.

Every scientific conclusion we make is therefore an inference: a statement about reality built from incomplete and uncertain information. The real question is: How should a rational scientist update knowledge in the presence of uncertainty? Classical logic cannot answer that question. Logic tells us what is certainly true. Science operates in a regime where almost nothing is certain. We need a framework that extends logic to handle degrees of belief without becoming inconsistent. That is the problem Cox set out to solve.

The Limits of True and False

Classical logic, the foundation of mathematics since Aristotle, deals in absolutes. A statement is either true or false. A star either has dust extinction or it doesn’t. But astronomy rarely gives us that kind of certainty. When we observe a reddened star, we cannot conclude with certainty that the star lies behind dust. The reddening could be intrinsic because the star is cool, it could be due to dust, it could reflect measurement error, or it could be some combination.

Consider the logical chain an astronomer faces:

Classical logic fails here because it has no language for graded support. It can represent certainty, but not the intermediate state that dominates science: evidence that supports a claim without proving it. The star might be behind dust, but it might also be intrinsically red. A scientist needs to say something like: “the reddening increases the plausibility that the star is behind dust, but it does not prove it.” That is exactly the gap between deductive logic and scientific inference. Probability enters here not as a convenient tool, but as a necessity.

Probability: The Language of Plausible Reasoning

In the 1940s, physicist Richard Cox asked a more demanding question than “How should we use probability?” He asked: What rules must any rational system of belief obey if it is going to reason consistently under uncertainty? Under Cox’s assumptions about rational consistency, the rules of plausible reasoning are isomorphic to probability theory. In that sense, probability is not just a convenient tool. It is the unique consistent extension of Boolean logic to uncertain reasoning.

Cox started with desiderata (requirements) that any system of plausible reasoning should satisfy:

  1. Degrees of Plausibility: Propositions have degrees of plausibility, represented by real numbers

  2. Consistency: If a conclusion can be reached in multiple ways, all ways must give the same answer

  3. Correspondence: In the limit of certainty, plausible reasoning must reduce to deductive logic

  4. Universality: The system should handle any proposition we can state

From just these requirements — which seem almost too basic to be powerful — Cox proved that plausible reasoning MUST follow the rules of probability theory. Not “should” or “could” — MUST.

From Astronomical Intuition to Mathematical Probability

Astronomers have always thought probabilistically, even before formalizing it. When Henrietta Leavitt said “these stars are probably at the same distance,” she was expressing a degree of belief. When modern astronomers say “this galaxy probably contains dark matter,” they’re doing plausible reasoning. Probability theory just makes this reasoning mathematically rigorous.

Let’s see how astronomical statements become probabilities:

Qualitative Statement →\to Probability Statement

Each transformation takes vague intuition and makes it precise. The numbers aren’t arbitrary — they encode our accumulated knowledge from centuries of observations.

The Cepheid Example: From Logic to Probability

Before writing probabilities, we should state the inferential problem clearly:

Classical logic cannot solve this because the data do not determine a unique conclusion. Probability gives us a way to represent and update degrees of support across many possible physical explanations.

Let’s apply this to our running Cepheid example. Using classical logic:

What we know for certain:

What we can’t deduce with certainty:

Enter probability:

Probability extends our logical reasoning to handle these uncertainties systematically.

Why Not Other Systems?

You might wonder: Why probability? Couldn’t we use fuzzy logic, possibility theory, or some other framework? Cox’s theorems say no — if we want consistency, we’re forced to use probability.

Here’s what happens with alternatives:

Fuzzy Logic: Handles vagueness (“very hot star”) but not uncertainty about facts Interval Arithmetic: Gives ranges but loses information about likelihood within the range Possibility Theory: Lacks the mathematical structure needed for updating with evidence

Only probability theory provides:

This uniqueness is profound. It means that aliens doing astronomy would use the same probability theory we do — not because they learned it from us, but because mathematics forces it on any consistent reasoner.


2.2 Likelihood: Encoding Physics as Probability

Priority: 🔴 Essential

The Direction That Physics Gives Us

In the Observable →\to Model →\to Inference framework, the likelihood is the step where the model turns physical parameters into predicted observables with an explicit uncertainty model.

Physics naturally runs forward — from causes to effects, from parameters to observations. If we know a star’s temperature, we can predict its spectrum. If we know a Cepheid’s period and intrinsic brightness, we can predict its apparent magnitude at any distance. This forward direction is what physics provides, and it’s encoded in the likelihood function.

But here’s the critical insight that confuses many: The likelihood is NOT the probability of the parameters. It’s the probability of the data given the parameters. This distinction is subtle but fundamental.

Consider measuring a Cepheid’s brightness:

The likelihood lives in the forward-model direction:

So the likelihood asks:

If the distance were 2.5 Mpc, how probable is it that we would observe m=21.5m = 21.5?

That is fundamentally different from the inferential question:

Given that we observed m=21.5m = 21.5, how plausible is 2.5 Mpc?

The first is likelihood. The second requires Bayes’ theorem.

Building a Likelihood from Physics

Let’s construct a real likelihood function for our Cepheid. We start with the physics — the Period-Luminosity relation discovered by Leavitt:

The Physics Model:

MV=−2.43(log⁡10P−1)−4.05M_V = -2.43(\log_{10} P - 1) - 4.05

where M_V is absolute V-band magnitude and P is period in days.

Adding Distance: The distance modulus relation connects intrinsic and apparent brightness:

m−M=5log⁡10(d)−5m - M = 5\log_{10}(d) - 5

where d is distance in parsecs.

Combining the Physics:

mpredicted=MV+5log⁡10(d)−5m_{predicted} = M_V + 5\log_{10}(d) - 5

mpredicted=−2.43(log⁡10P−1)−4.05+5log⁡10(d)−5m_{predicted} = -2.43(\log_{10} P - 1) - 4.05 + 5\log_{10}(d) - 5

This is our deterministic model — given P and d, we predict m. But observations aren’t perfect...

From Deterministic Model to Probabilistic Likelihood

Real measurements have uncertainties. Our CCD has read noise, the atmosphere scintillates, and Cepheids have intrinsic scatter in their P-L relation. We need to transform our deterministic model into a probability distribution.

Step 1: Identify the uncertainties

Step 2: Choose a noise model From the Statistical Thinking module, we learned about the Central Limit Theorem — many small random effects sum to a Gaussian distribution. Both measurement errors and intrinsic scatter arise from many small effects, so we use a Gaussian noise model.

Step 3: Write the likelihood

L(d,AV∣mobs,P)=12πσ2exp⁡(−(mobs−mpredicted(d,AV,P))22σ2)\mathcal{L}(d, A_V | m_{obs}, P) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(m_{obs} - m_{predicted}(d, A_V, P))^2}{2\sigma^2}\right)

where we’ve added extinction A_V to our model (making it more realistic).

The Likelihood in Practice

def cepheid_likelihood(params, observations):
    """
    Likelihood for Cepheid distance measurement.
    
    Physics model + measurement uncertainty = likelihood
    """
    distance, extinction = params  # What we want to infer
    period, apparent_mag, mag_error = observations  # What we measured
    
    # Physics: Period-Luminosity relation (Leavitt Law)
    absolute_mag = -2.43 * (np.log10(period) - 1) - 4.05
    
    # Physics: Distance modulus
    distance_modulus = 5 * np.log10(distance) - 5
    
    # Physics: Extinction dims the star
    predicted_mag = absolute_mag + distance_modulus + extinction
    
    # Statistics: Gaussian noise model
    intrinsic_scatter = 0.15  # Cepheids aren't perfect standard candles
    total_sigma = np.sqrt(mag_error**2 + intrinsic_scatter**2)
    
    # The likelihood: How probable is our observation given these parameters?
    residual = apparent_mag - predicted_mag
    log_likelihood = -0.5 * (residual/total_sigma)**2 - np.log(total_sigma * np.sqrt(2*np.pi))
    
    return np.exp(log_likelihood)

Likelihood function for Cepheid distance measurement. This figure shows how the likelihood P(\text{data}\mid d) quantifies the compatibility between our observations and different distance hypotheses. The normalized likelihood peaks at the maximum-likelihood estimate d \approx 5.00~\text{Mpc}, the distance most consistent with the observed apparent magnitude m = 25.3 \pm 0.05~\text{mag} and period P = 10~\text{days}. The shaded 68\% region spans approximately 4.89--4.99~\text{Mpc}. The narrow width shows that precise photometry and a calibrated period-luminosity relation strongly constrain distance. This is not the probability that the distance is correct; it is the probability of the observed data under each distance hypothesis.{width=“100%” #fig-likelihood-1d}

Common Likelihood Pitfalls

Pitfall 1: Forgetting intrinsic scatter If you only include measurement error, you’ll be overconfident. Real astronomical objects have intrinsic variation that must be included in the likelihood.

Pitfall 2: Assuming Gaussian errors From Statistical Thinking, we know the CLT gives us Gaussians for many small effects. But what about outliers? Cosmic rays? Variable stars misclassified as Cepheids? Real data often has heavy tails, requiring robust likelihoods (like Student-t distributions).

Pitfall 3: Ignoring correlations If you observe multiple Cepheids with the same telescope, their measurements share systematic errors. The likelihood needs the full covariance matrix, not just individual error bars.

Pitfall 4: Confusing likelihood with posterior Remember: likelihood is P(data∣parameters)P(\text{data} \mid \text{parameters}), not P(parameters∣data)P(\text{parameters} \mid \text{data}). Mixing these up leads to incorrect inferences.

Wrong reasoning sounds like this: “The likelihood peaks at 5 Mpc, so the star is probably at 5 Mpc.” That is not yet justified. A likelihood peak identifies which parameter values make the observed data most compatible with the forward model. It is not a posterior statement about what is most plausible after accounting for prior knowledge and normalization over parameter space.

How priors break parameter degeneracies in 2D likelihood spaces. The left panel shows a distance-extinction degeneracy ridge: many parameter combinations fit the data equally well. A star could be close and dusty, with d \approx 2.6~\text{Mpc} and A_V \approx 0.5~\text{mag}, or far and nearly clear, with d \approx 3.4~\text{Mpc} and A_V \approx 0.1~\text{mag}. The likelihood alone cannot distinguish these scenarios because dust extinction and distance both affect apparent brightness. The right panel adds physically motivated priors: a Gaussian prior on distance from previous measurements, 3.0 \pm 0.15~\text{Mpc}, and an exponential prior on extinction favoring low A_V. The posterior then concentrates near d \approx 3.0~\text{Mpc} and A_V \approx 0.2~\text{mag}. Priors are powerful here because they encode real astronomical knowledge that breaks degeneracies the data alone cannot resolve.{width=“100%” #fig-degeneracy-2d}

The Deep Connection to Information Theory

The likelihood encodes information about parameters contained in the data. In information theory terms, it quantifies how “surprised” we should be by the observations given different parameter values. High likelihood = unsurprising (expected given the parameters). Low likelihood = surprising (unexpected given the parameters).

The width of the likelihood function tells us about information content:

For our Cepheid, a precise brightness measurement gives a narrow likelihood in distance. A noisy measurement gives a broad likelihood. This width — the Fisher information — fundamentally limits how well we can measure distance regardless of our analysis method.

Connection to Statistical Thinking

Remember from the Statistical Thinking module that temperature is the width of the velocity distribution? The likelihood plays a similar role — it encodes the “width” of possible observations given parameters. Just as temperature describes the spread in molecular velocities, the likelihood describes the spread in possible observations.

The Central Limit Theorem from Statistical Thinking justifies our Gaussian likelihoods. When many small effects contribute to measurement error, their sum approaches a Gaussian. This is why Gaussian likelihoods are ubiquitous in astronomy — not by choice, but by mathematical necessity.



2.3 Priors: Quantifying What We Already Know

Priority: 🔴 Essential

In the Observable →\to Model →\to Inference framework, the prior represents what we already know about the unknown model parameters before confronting the current observations.

The Knowledge We Bring to Every Observation

No observation is interpreted in a vacuum. When Henrietta Leavitt observed Cepheids in the Small Magellanic Cloud, she brought the belief that these stars were roughly equidistant. When Edwin Hubble used Cepheids to measure the distance to Andromeda, he brought Leavitt’s P-L calibration. Every measurement builds on previous knowledge — this is what priors formalize.

Consider what you implicitly know before observing tonight’s Cepheid:

This isn’t subjective opinion — it’s accumulated astronomical knowledge from centuries of observations. Priors transform this knowledge into mathematical form.

Types of Priors in Astronomy

Physical Constraint Priors These encode fundamental physical limits:

def distance_prior(d):
    """Distance must be positive"""
    return 1.0 if d > 0 else 0.0

def extinction_prior(A_V):
    """Extinction can only redden light"""
    return 1.0 if A_V >= 0 else 0.0

def mass_prior(M):
    """Stars have limited mass range"""
    if 0.08 < M < 150:  # Solar masses
        return 1.0
    else:
        return 0.0

Population Priors These encode knowledge about astronomical populations:

The Initial Mass Function (IMF) tells us most stars are low-mass:

P(M)∝M−2.35(Salpeter IMF)P(M) \propto M^{-2.35} \quad \text{(Salpeter IMF)}

The galactic extinction distribution from dust maps:

P(AV∣l,b)=Value from Schlegel dust mapsP(A_V | l, b) = \text{Value from Schlegel dust maps}

The period distribution of Cepheids:

P(log⁡P)≈N(1.0,0.5)(days)P(\log P) \approx \mathcal{N}(1.0, 0.5) \quad \text{(days)}

Hierarchical Priors These capture how individual objects relate to populations:

# Individual Cepheid draws from population
population_mean_M = -2.43 * (log_P - 1) - 4.05
population_scatter = 0.15
individual_M ~ Normal(population_mean_M, population_scatter)

# Population parameters themselves have priors
population_scatter ~ HalfNormal(0.2)  # Must be positive, probably small

Four fundamental types of priors in Bayesian astronomy. This figure illustrates how different kinds of prior knowledge are encoded mathematically. A uniform prior treats all distances in a fixed interval as equally plausible. A Gaussian prior encodes previous measurements, such as a galaxy distance of 50 \pm 2~\text{kpc}. An exponential prior describes population structure, for example low-extinction sightlines being more common than high-extinction ones. A Jeffreys prior uses P(d) \propto 1/d to remain scale-invariant, so changing from 1 to 2~\text{kpc} is as significant as changing from 50 to 100~\text{kpc}. Each prior type serves a different inferential purpose and makes assumptions such as d > 0 explicit and testable.{width=“100%” #fig-prior-types}

The Prior Controversy: Subjectivity vs. Objectivity

Critics of Bayesian inference often focus on priors: “Aren’t they subjective? Different priors give different answers!” This criticism misunderstands what priors represent.

Priors are not arbitrary personal opinions. They are mathematical representations of information already available before analyzing the current dataset.

That information may come from:

Yes, different priors give different posteriors. But this is a feature, not a bug! If you have better prior information (say, from Gaia parallaxes), you SHOULD get better distance estimates than someone using vague priors.

Constructing Priors for Cepheid Distance

Let’s build realistic priors for our Cepheid problem:

import numpy as np
from scipy import stats

class CepheidPriors:
    """
    Prior knowledge for Cepheid distance measurement.
    Encodes centuries of astronomical knowledge.
    """
    
    def __init__(self, galaxy='LMC'):
        self.galaxy = galaxy
        
    def distance_prior(self, d):
        """
        Distance prior based on galaxy
        """
        if self.galaxy == 'LMC':
            # Previous measurements: 50 +/- 2 kpc
            # This is informative prior from decades of study
            mean_d = 50000  # parsecs
            sigma_d = 2000
            return stats.norm.pdf(d, mean_d, sigma_d)
            
        elif self.galaxy == 'M31':
            # Andromeda: 780 +/- 40 kpc
            mean_d = 780000
            sigma_d = 40000
            return stats.norm.pdf(d, mean_d, sigma_d)
            
        else:
            # Unknown galaxy: use volume prior
            # P(d) proportional to d**2 for uniform space distribution
            if 0 < d < 20e6:  # Within 20 Mpc
                return d**2
            else:
                return 0.0
    
    def extinction_prior(self, A_V, l, b):
        """
        Extinction prior from dust maps and galactic latitude
        """
        # Higher extinction toward galactic plane
        scale_height = 100  # parsecs
        
        if A_V < 0:
            return 0.0  # Extinction can't be negative
        
        # Exponential distribution with scale depending on latitude
        mean_extinction = 0.1 / np.abs(np.sin(b * np.pi/180))
        return stats.expon.pdf(A_V, scale=mean_extinction)
    
    def metallicity_prior(self, Z, galaxy_type='spiral'):
        """
        Metallicity affects P-L relation
        """
        if galaxy_type == 'spiral':
            # Solar neighborhood metallicity
            return stats.norm.pdf(Z, loc=0.0, scale=0.2)  # [Fe/H]
        elif galaxy_type == 'elliptical':
            # Metal-rich
            return stats.norm.pdf(Z, loc=0.3, scale=0.3)
        elif galaxy_type == 'dwarf':
            # Metal-poor
            return stats.norm.pdf(Z, loc=-0.7, scale=0.4)

When Priors Matter Most

Priors have different impacts depending on data quality:

Strong Data, Weak Prior: Data dominates

Weak Data, Strong Prior: Prior dominates

The Sweet Spot: Prior and data comparable

This is why priors matter so much in astronomy — we often have limited data and must leverage prior knowledge to make progress.

The balance between prior knowledge and new data determines posterior uncertainty. All panels start with the same informative Gaussian prior, centered at 50~\text{kpc} with \sigma_\text{prior} = 2.0~\text{kpc}, but differ in data quality. When the data are weak, with \sigma_\text{data} = 5.0~\text{kpc}, the posterior stays close to the prior and little new information is gained. When prior and data have comparable precision, with \sigma_\text{data} = 2.0~\text{kpc}, the posterior sits between them and becomes substantially narrower. When the data dominate, with \sigma_\text{data} = 0.5~\text{kpc}, the posterior closely tracks the likelihood. The uncertainty combination follows 1/\sigma_\text{post}^2 = 1/\sigma_\text{prior}^2 + 1/\sigma_\text{data}^2. This is why priors matter most when observations are weak or only moderately constraining — exactly the regime where much of astronomy operates.{width=“100%” #fig-prior-data-balance}

The Cosmic Distance Ladder as Hierarchical Priors

The entire cosmic distance ladder is a beautiful example of hierarchical Bayesian inference:

  1. Parallax (direct measurement)

    • Prior: Uniform in space

    • Data: Gaia measurements

    • Posterior: Distance to nearby stars

  2. Cluster Cepheids (first rung)

    • Prior: Cluster members share distance

    • Data: Periods and brightness

    • Posterior: P-L relation calibration

  3. LMC Cepheids (second rung)

    • Prior: P-L calibration from clusters

    • Data: LMC Cepheid observations

    • Posterior: Distance to LMC

  4. Distant Galaxies (third rung)

    • Prior: LMC distance and P-L relation

    • Data: Galaxy Cepheid observations

    • Posterior: Hubble constant

Each rung’s posterior becomes the next rung’s prior — a cascade of inference building from parallax to cosmology!

Connection to Statistical Thinking

From the Statistical Thinking module, we learned about marginalization — integrating over variables we don’t care about. Priors enable this:

P(d∣data)=∫P(d,AV∣data) dAVP(d | \text{data}) = \int P(d, A_V | \text{data}) \, dA_V

The prior on extinction AVA_V lets us marginalize it out if we only care about distance. Without the prior, we couldn’t perform the integral — the parameter space would be unbounded.

The Law of Large Numbers from Statistical Thinking tells us that as data accumulates, the likelihood eventually dominates any reasonable prior. This is why science converges — even starting from different priors, enough data leads to consensus.



2.4 Bayes’ Theorem: The Engine of Learning

Priority: 🔴 Essential

In the Observable →\to Model →\to Inference framework, Bayes’ theorem is the step that converts the forward model plus prior knowledge into an updated distribution over the unknown parameters after seeing the data.

The Counting Argument: Bayes from First Principles

Before writing equations, let’s derive Bayes’ theorem using simple counting — an argument so elementary it seems almost trivial, yet it gives us the most profound theorem in inference.

Imagine we have 1000 Cepheids in the Large Magellanic Cloud:

We observe one Cepheid with apparent magnitude m = 18.5. From experience:

Question: Given we observed m = 18.5, what’s the probability it’s in the LMC?

Counting solution:

Now let’s write this mathematically:

P(LMC∣m=18.5)=Number at LMC AND m=18.5Total number with m=18.5P(\text{LMC} | m=18.5) = \frac{\text{Number at LMC AND m=18.5}}{\text{Total number with m=18.5}}
=P(m=18.5∣LMC)×NLMCP(m=18.5∣LMC)×NLMC+P(m=18.5∣foreground)×Nforeground= \frac{P(m=18.5|\text{LMC}) \times N_{\text{LMC}}}{P(m=18.5|\text{LMC}) \times N_{\text{LMC}} + P(m=18.5|\text{foreground}) \times N_{\text{foreground}}}

Dividing by total number of Cepheids:

P(LMC∣m=18.5)=P(m=18.5∣LMC)×P(LMC)P(m=18.5)P(\text{LMC} | m=18.5) = \frac{P(m=18.5|\text{LMC}) \times P(\text{LMC})}{P(m=18.5)}

This is Bayes’ theorem! Not an axiom we assume, but a consequence of counting.

The General Form and Its Meaning

For continuous parameters (like distance), Bayes’ theorem becomes:

P(θ∣D)=P(D∣θ)×P(θ)P(D)\boxed{P(\theta | D) = \frac{P(D | \theta) \times P(\theta)}{P(D)}}

where:

Each piece has a role:

Why Multiplication? The Product Rule

Bayes’ theorem multiplies likelihood and prior because it follows directly from the product rule of probability. The joint probability P(θ,D)=P(D∣θ)P(θ)=P(θ∣D)P(D)P(\theta, D) = P(D|\theta)P(\theta) = P(\theta|D)P(D); solving for P(θ∣D)P(\theta|D) gives Bayes’ theorem. No independence assumption is needed — this is an identity.

The prior and likelihood represent different types of information:

For Gaussian prior and likelihood, the product gives a Gaussian posterior with smaller variance — the same principle behind combining independent measurements.

The Evidence Integral: Usually Ignored but Sometimes Crucial

The evidence (denominator) is:

P(D)=∫P(D∣θ)P(θ) dθP(D) = \int P(D|\theta) P(\theta) \, d\theta

This integral is often intractable, but we have options:

For Parameter Estimation: Ignore it!

For Model Comparison: Must compute it!

Applying Bayes to Cepheid Distance

Let’s work through the complete Bayesian inference for a Cepheid:

class CepheidBayesianInference:
    """
    Complete Bayesian inference for Cepheid distance.
    Combines prior knowledge with new observations.
    """
    
    def __init__(self, period=10.0, apparent_mag=18.5, mag_error=0.05, galaxy='LMC'):
        # Observation
        self.period = period  # days
        self.apparent_mag = apparent_mag
        self.mag_error = mag_error
        self.galaxy = galaxy
        
    def log_likelihood(self, distance, extinction):
        """
        P(data | parameters)
        From Section 2.2
        """
        # Period-Luminosity relation
        absolute_mag = -2.43 * (np.log10(self.period) - 1) - 4.05
        
        # Distance modulus + extinction
        predicted_mag = absolute_mag + 5*np.log10(distance) - 5 + extinction
        
        # Gaussian likelihood
        sigma_total = np.sqrt(self.mag_error**2 + 0.15**2)  # Include intrinsic scatter
        residual = self.apparent_mag - predicted_mag
        
        return -0.5 * (residual/sigma_total)**2 - np.log(sigma_total * np.sqrt(2*np.pi))
    
    def log_prior(self, distance, extinction):
        """
        P(parameters)
        From Section 2.3
        """
        # Distance prior: LMC at 50 +/- 2 kpc
        if distance <= 0:
            return -np.inf
        distance_prior = -0.5 * ((distance - 50000)/2000)**2
        
        # Extinction prior: Exponential with mean 0.2 mag
        if extinction < 0:
            return -np.inf
        extinction_prior = -extinction/0.2 - np.log(0.2)
        
        return distance_prior + extinction_prior
    
    def log_posterior(self, distance, extinction):
        """
        P(parameters | data) is proportional to P(data | parameters) * P(parameters)
        BAYES' THEOREM IN ACTION!
        """
        return self.log_likelihood(distance, extinction) + self.log_prior(distance, extinction)
    
    def interpret_results(self, posterior_samples):
        """
        What have we learned?
        """
        distance_mean = np.mean(posterior_samples[:, 0])
        distance_std = np.std(posterior_samples[:, 0])
        
        extinction_mean = np.mean(posterior_samples[:, 1])
        extinction_std = np.std(posterior_samples[:, 1])
        
        print(f"Distance: {distance_mean:.0f} +/- {distance_std:.0f} parsecs")
        print(f"Extinction: {extinction_mean:.2f} +/- {extinction_std:.2f} magnitudes")
        
        # Compare to prior
        prior_distance_std = 2000  # Prior uncertainty
        posterior_distance_std = distance_std
        
        information_gain = prior_distance_std / posterior_distance_std
        print(f"Information gain: {information_gain:.1f}x reduction in uncertainty")


# Example: LMC Cepheid at 50+/-2 kpc with P=10 days, m=18.5+/-0.05
inference = CepheidBayesianInference(
    period=10.0, apparent_mag=18.5, mag_error=0.05, galaxy='LMC'
)

# The posterior combines prior knowledge (LMC distance) with new data
# Result: Distance = 48.7 +/- 1.2 kpc, Extinction = 0.15 +/- 0.08 mag

Bayes' theorem as a step-by-step recipe for learning from data. The prior places the LMC Cepheid near 50 \pm 2~\text{kpc} based on previous work. A new observation of a P = 10~\text{day} Cepheid with apparent magnitude m = 18.5 produces a likelihood that peaks near 48~\text{kpc} with \sigma = 1.5~\text{kpc}. Multiplying prior and likelihood produces a narrower posterior centered near 48.7~\text{kpc} with \sigma_\text{post} \approx 1.2~\text{kpc}. The information gain is visible directly in the narrowing and quantitatively follows 1/\sigma_\text{post}^2 = 1/\sigma_\text{prior}^2 + 1/\sigma_\text{data}^2. This posterior then becomes the next prior as the distance ladder advances.{width=“100%” #fig-bayesian-updating}

The Flow of Information

Bayes’ theorem describes how information flows from data to knowledge:

  1. Start with prior: Centuries of astronomical knowledge

  2. Collect new data: Tonight’s observations

  3. Apply Bayes: Multiply likelihood by prior

  4. Get posterior: Updated knowledge

This isn’t a one-time process — it’s iterative:

Connection to Everything

Bayes’ theorem connects all our concepts:

From Statistical Thinking Module:

From This Module:

Looking Forward:

Joint posterior distribution with marginal distributions illustrating the power of marginalization. The central panel shows the joint posterior P(d, A_V \mid \text{data}) over distance and extinction. The elongated contours reveal a positive correlation: larger extinction implies smaller distance for the same observed brightness. The highest-probability region lies near d \approx 49~\text{kpc} and A_V \approx 0.2~\text{mag}. The top panel marginalizes over extinction to obtain P(d \mid \text{data}), while the right panel marginalizes over distance to obtain P(A_V \mid \text{data}). These marginals answer focused questions about one parameter while correctly accounting for uncertainty in the other. They are not the same as conditionals at a fixed parameter value.{width=“100%” #fig-2d-posterior-marginals}

The Unity of Science

Every scientific measurement uses Bayes’ theorem, whether explicitly or implicitly:

Even frequentist methods implicitly use Bayes with specific priors:


Part 2 Synthesis: The Mathematical Framework of Learning

The Path Forward

We now have the equations:

But can we solve them? For our Cepheid with distance and extinction, we need:

P(d,AV∣m,P)=P(m∣d,AV,P)×P(d)×P(AV)∫∫P(m∣d′,AV′,P)×P(d′)×P(AV′) dd′ dAV′P(d, A_V | m, P) = \frac{P(m | d, A_V, P) \times P(d) \times P(A_V)}{\int \int P(m | d', A_V', P) \times P(d') \times P(A_V') \, dd' \, dA_V'}

That integral in the denominator is already challenging for 2D. What about:

We quickly reach integrals in 10, 50, or 1000 dimensions. This is computationally impossible by direct integration.

Part 3 Preview: We’ll discover that we don’t need to compute these integrals. Instead, we can SAMPLE from the posterior distribution using MCMC. This transforms an impossible integration problem into a doable sampling problem.

Key Takeaways for Your Journey

  1. You’re already Bayesian: Every time you interpret an observation using prior knowledge, you’re doing Bayesian inference informally. This module makes it rigorous.

  2. Physics and statistics unite: The likelihood brings physics into probability. Your astrophysics knowledge directly enters the inference through P(D∣θ)P(D \mid \theta).

  3. Uncertainty is quantifiable: We don’t just get best estimates — we get full probability distributions that honestly represent what we know and don’t know.

  4. Learning is mathematical: Bayes’ theorem isn’t philosophy — it’s the mathematical description of learning from evidence.

  5. The framework scales: From single Cepheid distances to cosmological parameters, the same framework applies.

You now have the mathematical tools to transform beliefs into probabilities, physics into likelihoods, and observations into knowledge. Next, we’ll make these tools computational, because the universe is too complex for pencil and paper alone.



Remember: Every astronomical measurement is an act of inference. We’ve now formalized that act into mathematics. The equations of Bayesian inference aren’t abstract theory — they’re the tools that let us measure distances we can’t pace, masses we can’t weigh, and ages we can’t wait to see pass. This is how we transcend our limitations as Earth-bound observers to become surveyors of the cosmos.