Skip to content

Hybrid Imaging of a Black Hole

In this tutorial, we will use hybrid imaging to analyze the 2017 EHT data. By hybrid imaging, we mean decomposing the model into simple geometric models, e.g., rings and such, plus a rasterized image model to soak up the additional structure. This approach was first developed in BB20 and applied to EHT 2017 data. We will use a similar model in this tutorial.

Introduction to Hybrid modeling and imaging

The benefit of using a hybrid-based modeling approach is the effective compression of information/parameters when fitting the data. Hybrid modeling requires the user to incorporate specific knowledge of how you expect the source to look like. For instance for M87, we expect the image to be dominated by a ring-like structure. Therefore, instead of using a high-dimensional raster to recover the ring, we can use a ring model plus a raster to soak up the additional degrees of freedom. This is the approach we will take in this tutorial to analyze the April 6 2017 EHT data of M87.

"nul"

Loading the Data

To get started we will load Comrade

julia
using Comrade

Load the Data

julia
using Pyehtim

For reproducibility we use a stable random number genreator

julia
using StableRNGs
rng = StableRNG(42)
StableRNGs.LehmerRNG(state=0x00000000000000000000000000000055)

To download the data visit https://doi.org/10.25739/g85n-f134 To load the eht-imaging obsdata object we do:

julia
obs = ehtim.obsdata.load_uvfits(joinpath(__DIR, "..", "..", "Data", "SR1_M87_2017_096_lo_hops_netcal_StokesI.uvfits"))
Python: <ehtim.obsdata.Obsdata object at 0x7faf98fce020>

Now we do some minor preprocessing:

  • Scan average the data since the data have been preprocessed so that the gain phases coherent.
julia
obs = scan_average(obs).add_fractional_noise(0.02)
Python: <ehtim.obsdata.Obsdata object at 0x7faf3ae855a0>

For this tutorial we will once again fit complex visibilities since they provide the most information once the telescope/instrument model are taken into account.

julia
dvis  = extract_table(obs, Visibilities())
EHTObservationTable{Comrade.EHTVisibilityDatum{:I}}
  source:      M87
  mjd:         57849
  bandwidth:   1.856e9
  sites:       [:AA, :AP, :AZ, :JC, :LM, :PV, :SM]
  nsamples:    274

Building the Model/Posterior

Now we build our intensity/visibility model. That is, the model that takes in a named tuple of parameters and perhaps some metadata required to construct the model. For our model, we will use a raster or ContinuousImage model, an m-ring model, and a large asymmetric Gaussian component to model the unresolved short-baseline flux.

julia
function sky(θ, metadata)
    (;c, σimg, f, r, σ, τ, ξτ, ma, mp, fg) = θ
    (;ftot, grid) = metadata
    # Form the image model
    # First transform to simplex space first applying the non-centered transform
    rast = (ftot*f*(1-fg)).*to_simplex(CenteredLR(), σimg.*c)
    mimg = ContinuousImage(rast, grid, BSplinePulse{3}())
    # Form the ring model
    α = ma.*cos.(mp .- ξτ)
    β = ma.*sin.(mp .- ξτ)
    ring = smoothed(modify(MRing(α, β), Stretch(r, r*(1+τ)), Rotate(ξτ), Renormalize((ftot*(1-f)*(1-fg)))), σ)
    gauss = modify(Gaussian(), Stretch(μas2rad(250.0)), Renormalize(ftot*f*fg))
    # We group the geometric models together for improved efficiency. This will be
    # automated in future versions.
    return mimg + (ring + gauss)
end
sky (generic function with 1 method)

Unlike other imaging examples (e.g., Imaging a Black Hole using only Closure Quantities) we also need to include a model for the instrument, i.e., gains as well. The gains will be broken into two components

  • Gain amplitudes which are typically known to 10-20%, except for LMT, which has amplitudes closer to 50-100%.

  • Gain phases which are more difficult to constrain and can shift rapidly.

julia
using VLBIImagePriors
using Distributions, DistributionsAD
G = SingleStokesGain() do x
    lg = x.lg
    gp = x.gp
    return exp(lg + 1im*gp)
end

intpr = (
    lg= ArrayPrior(IIDSitePrior(ScanSeg(), Normal(0.0, 0.2)); LM = IIDSitePrior(ScanSeg(), Normal(0.0, 1.0))),
    gp= ArrayPrior(IIDSitePrior(ScanSeg(), DiagonalVonMises(0.0, inv(π^2))); refant=SEFDReference(0.0))
        )
intmodel = InstrumentModel(G, intpr)
InstrumentModel
  with Jones:  SingleStokesGain
  with reference basis: CirBasis()

Before we move on, let's go into the model function a bit. This function takes two arguments θ and metadata. The θ argument is a named tuple of parameters that are fit to the data. The metadata argument is all the ancillary information we need to construct the model. For our hybrid model, we will need two variables for the metadata, a grid that specifies the locations of the image pixels and a cache that defines the algorithm used to calculate the visibilities given the image model. This is required since ContinuousImage is most easily computed using number Fourier transforms like the NFFT or FFT. To combine the models, we use Comrade's overloaded + operators, which will combine the images such that their intensities and visibilities are added pointwise.

Now let's define our metadata. First we will define the cache for the image. This is required to compute the numerical Fourier transform.

julia
fovxy  = μas2rad(200.0)
npix   = 32
g      = imagepixels(fovxy, fovxy, npix, npix)
RectiGrid(
executor: Serial()
Dimensions: 
↓ X Sampled{Float64} LinRange{Float64}(-4.69663253574863e-10, 4.69663253574863e-10, 32) ForwardOrdered Regular Points,
→ Y Sampled{Float64} LinRange{Float64}(-4.69663253574863e-10, 4.69663253574863e-10, 32) ForwardOrdered Regular Points
)

Part of hybrid imaging is to force a scale separation between the different model components to make them identifiable. To enforce this we will set the length scale of the raster component equal to the beam size of the telescope in units of pixel length, which is given by

julia
beam = beamsize(dvis)
rat = (beam/(step(g.X)))
cprior = GaussMarkovRandomField(rat, size(g); order=2)
GaussMarkovRandomField(
Graph: MarkovRandomFieldGraph{2}(
dims: (32, 32)
)
Correlation Parameter: 3.9947524783031394
)

additionlly we will fix the standard deviation of the field to unity and instead use a pseudo non-centered parameterization for the field. GaussMarkovRandomField(meanpr, 0.1*rat, 1.0, crcache)

Finally we can put form the total model prior

julia
skyprior = (
          c  = cprior,
          σimg = truncated(Normal(0.0, 1.0); lower=0.01),
          f  = Uniform(0.0, 1.0),
          r  = Uniform(μas2rad(10.0), μas2rad(30.0)),
          σ  = Uniform(μas2rad(0.1), μas2rad(10.0)),
          τ  = truncated(Normal(0.0, 0.1); lower=0.0, upper=1.0),
          ξτ = Uniform(-π/2, π/2),
          ma = ntuple(_->Uniform(0.0, 0.5), 2),
          mp = ntuple(_->Uniform(0.0, ), 2),
          fg = Uniform(0.0, 1.0),
        )
(c = GaussMarkovRandomField(
Graph: MarkovRandomFieldGraph{2}(
dims: (32, 32)
)
Correlation Parameter: 3.9947524783031394
), σimg = Truncated(Distributions.Normal{Float64}(μ=0.0, σ=1.0); lower=0.01), f = Distributions.Uniform{Float64}(a=0.0, b=1.0), r = Distributions.Uniform{Float64}(a=4.84813681109536e-11, b=1.454441043328608e-10), σ = Distributions.Uniform{Float64}(a=4.848136811095359e-13, b=4.84813681109536e-11), τ = Truncated(Distributions.Normal{Float64}(μ=0.0, σ=0.1); lower=0.0, upper=1.0), ξτ = Distributions.Uniform{Float64}(a=-1.5707963267948966, b=1.5707963267948966), ma = (Distributions.Uniform{Float64}(a=0.0, b=0.5), Distributions.Uniform{Float64}(a=0.0, b=0.5)), mp = (Distributions.Uniform{Float64}(a=0.0, b=6.283185307179586), Distributions.Uniform{Float64}(a=0.0, b=6.283185307179586)), fg = Distributions.Uniform{Float64}(a=0.0, b=1.0))

Now we form the metadata

julia
skymetadata = (;ftot=1.1, grid = g)
skym = SkyModel(sky, skyprior, g; metadata=skymetadata)
 SkyModel
  with map: sky
   on grid: RectiGrid

This is everything we need to specify our posterior distribution, which our is the main object of interest in image reconstructions when using Bayesian inference.

julia
post = VLBIPosterior(skym, intmodel, dvis)
VLBIPosterior
ObservedSkyModel
  with map: sky
   on grid: FourierDualDomainObservedInstrumentModel
  with Jones:  SingleStokesGain
  with reference basis: CirBasis()Data Products: Comrade.EHTVisibilityDatum

To sample from our prior we can do

julia
xrand = prior_sample(rng, post)
(sky = (c = [-2.1962796581148964 -1.1243036995667173 … 0.1809752675358745 0.5228771323078414; -0.3425595294889296 0.875841911517527 … -1.7473734958334282 -0.04613166448214303; … ; -1.0346864752090177 -0.3318267589886823 … 1.8169964745030398 0.9883988762644694; -0.17570171401278734 -1.1226297884080063 … 0.23776676295262178 -0.12297534720788651], σimg = 0.42179682054864803, f = 0.5609945096442908, r = 6.822575941314203e-11, σ = 1.3552947886307434e-11, τ = 0.06730160453188876, ξτ = -1.4000761734573677, ma = (0.34647334815942743, 0.2990582529227658), mp = (4.539841547826114, 0.12993729152293854), fg = 0.37817042117774347), instrument = (lg = [-0.05442203326486966, -0.06854489109756777, -0.03494199200648159, 0.01466628222962606, -0.5344934234689837, 0.06909851514694904, 0.16895161284675558, -0.35730974364294593, 2.2297802017289468, 0.14330481934854625  …  -0.2562770339996219, -0.13260692566162727, -0.3754572129527364, 0.13202624897901952, -0.22070992008362902, -0.14044807385292715, 0.08434814836495083, -0.16645257431733257, 0.07930960115946253, 0.09730314408987739], gp = [0.0, 0.801726817174358, 0.0, 0.5352791204380771, 1.2147806619090493, 1.8380953555627066, 0.0, -1.2091566463464445, 0.4316140924972767, 2.8356106901992013  …  0.6797921035265353, 1.5869294029613246, 1.9179548979911933, -0.7937725614627756, 0.0, -2.1551512461478652, -1.4071803931922073, -0.3657978469609746, -2.891016934890005, -1.059347481121196]))

and then plot the results

julia
import CairoMakie as CM
gpl = imagepixels(μas2rad(200.0), μas2rad(200.0), 128, 128)
fig = imageviz(intensitymap(skymodel(post, xrand), gpl));

Reconstructing the Image

To find the image we will demonstrate two methods:

  • Optimization to find the MAP (fast but often a poor estimator)

  • Sampling to find the posterior (slow but provides a substantially better estimator)

For optimization we will use the Optimization.jl package and the LBFGS optimizer. To use this we use the comrade_opt function

julia
using Optimization
using OptimizationOptimJL
using Zygote
xopt, sol = comrade_opt(post, LBFGS(), Optimization.AutoZygote(); initial_params=prior_sample(rng, post), maxiters=1000, g_tol=1e0)
((sky = (c = [-0.08179704004088623 -0.09320192050833864 … -0.18908375804662444 -0.07546798977235719; -0.07279212446158262 -0.07617833268700132 … -0.3141760658835688 -0.16584083409208916; … ; 0.12419977680384184 0.12655313131072948 … 0.07557542217357281 0.028780048103687412; 0.12549529387644714 0.11096599266827087 … 0.18299372001089262 0.08305353549197753], σimg = 2.666321487321501, f = 0.7046969673769103, r = 1.0135087601557804e-10, σ = 1.4925008531532094e-11, τ = 0.08367660382742312, ξτ = 0.05915421856318865, ma = (0.2532506452068686, 0.10034644552155955), mp = (2.563968231073573, 2.3222543764419714), fg = 0.10589756960701847), instrument = (lg = [0.004211009637388645, 0.004196129321322932, 0.028248185437352035, 0.04111907696995761, -0.2452015579156597, 0.09012314814626744, 0.017939373519678357, 0.04623099173528219, -0.011053733823311047, 0.07189198154873967  …  0.04854424448335403, 0.03035548133209934, -0.5075866186602055, 0.02861206589240569, 0.03217568514988794, 0.039925470459208294, 0.016098241527009265, 0.036744174915574995, -0.5678659896980882, 0.02650305583186808], gp = [0.0, 0.18438579208873804, 0.0, -2.1913039016238254, 1.4720567408923382, 0.0359410009841399, 0.0, -2.241190109205486, 1.5228170904265423, -0.15677836342374857  …  -1.6900909508915056, -0.040123523459699384, -2.901632825557557, 3.1211946970929145, 0.0, -1.8302436860155427, -1.7733847996415826, -0.06542180734465523, -3.0359721179204615, 3.0930264711381605])), retcode: Failure
u: [-0.08179704004088623, -0.07279212446158262, 0.07657003183123605, 0.24604653405440643, 0.23104013725253927, 0.033072004846269404, -0.15471955091914022, -0.17877485462996107, -0.11053019983090186, -0.009014671194851614  …  -0.9036450741549169, -0.23985440258796073, -0.918505738047752, -0.18866685874664316, -0.061470399489088196, 0.9382601752117046, -0.09920230667491006, -0.9357379329520733, 0.04564419916382246, -0.9390959845059217]
Final objective value:     -1526.092288817486
)

First we will evaluate our fit by plotting the residuals

julia
using Plots
fig = residual(post, xopt);

These residuals suggest that we are substantially overfitting the data. This is a common side effect of MAP imaging. As a result if we plot the image we see that there is substantial high-frequency structure in the image that isn't supported by the data.

julia
imageviz(intensitymap(skymodel(post, xopt), gpl), figure=(;resolution=(500, 400),))

To improve our results we will now move to Posterior sampling. This is the main method we recommend for all inference problems in Comrade. While it is slower the results are often substantially better. To sample we will use the AdvancedHMC package.

julia
using AdvancedHMC
chain = sample(rng, post, NUTS(0.8), 700; n_adapts=500, progress=false, initial_params=xopt);
[ Info: Found initial step size 0.0015625

We then remove the adaptation/warmup phase from our chain

julia
chain = chain[501:end]
PosteriorSamples
  Samples size: (200,)
  sampler used: AHMC
Mean
┌───────────────────────────────────────────────────────────────────────────────
│ sky                                                                          ⋯
│ @NamedTuple{c::Matrix{Float64}, σimg::Float64, f::Float64, r::Float64, σ::Fl ⋯
├───────────────────────────────────────────────────────────────────────────────
│ (c = [-0.231924 -0.275893 … -0.473363 -0.279708; -0.213617 -0.373723 … -0.65 ⋯
└───────────────────────────────────────────────────────────────────────────────
                                                               2 columns omitted
Std. Dev.
┌───────────────────────────────────────────────────────────────────────────────
│ sky                                                                          ⋯
│ @NamedTuple{c::Matrix{Float64}, σimg::Float64, f::Float64, r::Float64, σ::Fl ⋯
├───────────────────────────────────────────────────────────────────────────────
│ (c = [0.667918 0.726858 … 0.678276 0.67625; 0.677899 0.812944 … 0.841485 0.7 ⋯
└───────────────────────────────────────────────────────────────────────────────
                                                               2 columns omitted

Warning

This should be run for 4-5x more steps to properly estimate expectations of the posterior

Now lets plot the mean image and standard deviation images. To do this we first clip the first 250 MCMC steps since that is during tuning and so the posterior is not sampling from the correct sitesary distribution.

julia
using StatsBase
msamples = skymodel.(Ref(post), chain[begin:2:end]);

The mean image is then given by

julia
imgs = intensitymap.(msamples, Ref(gpl))
fig = imageviz(mean(imgs), colormap=:afmhot, size=(400, 300));

julia
fig = imageviz(std(imgs), colormap=:batlow, size=(400, 300));

We can also split up the model into its components and analyze each separately

julia
comp = Comrade.components.(msamples)
ring_samples = getindex.(comp, 2)
rast_samples = first.(comp)
ring_imgs = intensitymap.(ring_samples, Ref(gpl));
rast_imgs = intensitymap.(rast_samples, Ref(gpl));

ring_mean, ring_std = mean_and_std(ring_imgs);
rast_mean, rast_std = mean_and_std(rast_imgs);

fig = CM.Figure(; resolution=(400, 400));
axes = [CM.Axis(fig[i, j], xreversed=true, aspect=CM.DataAspect()) for i in 1:2, j in 1:2]
CM.image!(axes[1,1], ring_mean, colormap=:afmhot); axes[1,1].title = "Ring Mean"
CM.image!(axes[1,2], ring_std, colormap=:afmhot); axes[1,2].title = "Ring Std. Dev."
CM.image!(axes[2,1], rast_mean, colormap=:afmhot); axes[2,1].title = "Rast Mean"
CM.image!(axes[2,2], rast_std./rast_mean, colormap=:afmhot); axes[2,2].title = "Rast std/mean"
CM.hidedecorations!.(axes)
fig |> DisplayAs.PNG |> DisplayAs.Text

Finally, let's take a look at some of the ring parameters

julia
figd = CM.Figure(;resolution=(650, 400));
p1 = CM.density(figd[1,1], rad2μas(chain.sky.r)*2, axis=(xlabel="Ring Diameter (μas)",))
p2 = CM.density(figd[1,2], rad2μas(chain.sky.σ)*2*sqrt(2*log(2)), axis=(xlabel="Ring FWHM (μas)",))
p3 = CM.density(figd[1,3], -rad2deg.(chain.sky.mp.:1) .+ 360.0, axis=(xlabel = "Ring PA (deg) E of N",))
p4 = CM.density(figd[2,1], 2*chain.sky.ma.:2, axis=(xlabel="Brightness asymmetry",))
p5 = CM.density(figd[2,2], 1 .- chain.sky.f, axis=(xlabel="Ring flux fraction",))

Now let's check the residuals using draws from the posterior

julia
p = Plots.plot();
for s in sample(chain, 10)
    residual!(p, post, s, legend=false)
end

And everything looks pretty good! Now comes the hard part: interpreting the results...


This page was generated using Literate.jl.