Setting up a model on a Voronoi grid#
A Voronoi grid is defined by a set of points, which we call sites: each site defines one cell, which contains all the positions that are closer to that site than to any other site (see Voronoi grids for more details). Voronoi grids are a natural choice if your density comes from a simulation that uses particles (for example smoothed particle hydrodynamics) or a moving mesh, since you can use the particle positions directly as the sites, and they are also a convenient way to set up a model with high resolution only where it is needed.
In this tutorial, we set up a clumpy spherical cloud on a Voronoi grid, lit by three stars, and compute scattered light images at three wavelengths. We also compare two ways of bounding the grid: a rectangular domain only, and a rectangular domain combined with a spherical wall.
Note
This example uses the kmh94_3.1_hg dust model provided by the
hyperion-dust
package, which can be installed with pip install hyperion-dust.
Setting up the model#
The full script is available here,
and we go through it step by step below.
Density#
We first define the density of the cloud: a sphere with a radius of 10,000 au containing a smooth background, with a density decreasing outwards, and 45 Gaussian clumps with random positions, sizes, and peak densities:
import numpy as np
from hyperion.model import Model
from hyperion.util.constants import au, lsun
from hyperion_dust import get_dust
# Use the KMH94 dust model with Henyey-Greenstein scattering
dust = get_dust('kmh94_3.1_hg')
# Use a fixed random seed so that the cloud is the same every time
rng = np.random.default_rng(2026)
# Radius of the spherical cloud
R = 1.e4 * au
# Background density (in g/cm^3), giving an optical depth of order unity from
# the center to the edge of the cloud at optical wavelengths, not counting the
# clumps
RHO_0 = 3.e-20
# The cloud contains a number of Gaussian clumps, with random positions
# inside the sphere, and a range of sizes and peak densities
n_clumps = 45
directions = rng.normal(size=(n_clumps, 3))
directions /= np.linalg.norm(directions, axis=1)[:, np.newaxis]
radii = 0.85 * R * rng.uniform(0., 1., n_clumps) ** (1. / 3.)
clump_centers = directions * radii[:, np.newaxis]
clump_sizes = R * 10 ** rng.uniform(-1.6, -0.9, n_clumps)
clump_amplitudes = 10 ** rng.uniform(1., 2., n_clumps)
def density(x, y, z):
"""
Return the density at positions x, y, z (in cm).
"""
r = np.sqrt(x ** 2 + y ** 2 + z ** 2)
# Background density, decreasing from the center to the edge
rho = RHO_0 * (1. - 0.7 * r / R)
# Add the clumps
for center, size, amplitude in zip(clump_centers, clump_sizes, clump_amplitudes):
d2 = (x - center[0]) ** 2 + (y - center[1]) ** 2 + (z - center[2]) ** 2
rho = rho + RHO_0 * amplitude * np.exp(-0.5 * d2 / size ** 2)
return rho
Choosing the sites#
Next, we choose the positions of the sites. If you have particles from a simulation, you can simply use the particle positions here. In this example, we instead place the sites so that they follow the density: 3,000 sites distributed uniformly across the cloud, and many more inside the clumps, so that the cells are smallest where the density is highest:
def random_points_in_sphere(n, radius):
"""
Return n random positions distributed uniformly inside a sphere.
"""
directions = rng.normal(size=(n, 3))
directions /= np.linalg.norm(directions, axis=1)[:, np.newaxis]
radii = radius * rng.uniform(0., 1., n) ** (1. / 3.)
return directions * radii[:, np.newaxis]
# Choose the positions of the Voronoi sites. If you have particles from a
# simulation (e.g. SPH), you can simply use the particle positions. Here we
# place the sites so that they follow the density: a uniform population of
# sites across the whole cloud, plus many more sites inside the clumps, so
# that the cells are smallest where the density is highest.
sites = [random_points_in_sphere(3000, R)]
for center, size, amplitude in zip(clump_centers, clump_sizes, clump_amplitudes):
n = int(40 * np.sqrt(amplitude))
sites.append(center + 1.5 * size * rng.normal(size=(n, 3)))
sites = np.vstack(sites)
# All sites must be inside the sphere when using a spherical wall, so we
# drop the few clump sites that fall outside
sites = sites[np.linalg.norm(sites, axis=1) < 0.995 * R]
x, y, z = sites[:, 0], sites[:, 1], sites[:, 2]
print(f"Using {len(x)} Voronoi sites")
This gives 13,905 sites. Since we will bound the grid with a sphere of radius
R below, we make sure that all the sites are inside that sphere.
Density in each cell#
Hyperion needs one density value per cell, in the same order as the sites. Here we simply use the value of the density at the position of each site:
# The density in each cell is taken to be the density at the position of its
# site
rho = density(x, y, z)
This is a good approximation only if the cells are small compared to the scale over which the density changes, which is why we placed more sites in the clumps. If your sites come from a simulation, you will typically use the density of each particle instead.
Setting up the grid#
We then define a function that sets up the model, since we will create the
same model twice: once without and once with a spherical wall. The grid is
set with set_voronoi_grid(), which takes the
positions of the sites and the limits of the rectangular domain (in cm),
within which the cells are computed:
def setup_model(wall):
"""
Set up the model, with or without a spherical wall around the cloud.
"""
m = Model()
# Set up the Voronoi grid. The cells fill the rectangular domain given by
# the limits (in cm). If a spherical wall is used, the cells are in
# addition cut by a sphere, given by its center and radius.
if wall:
m.set_voronoi_grid(x, y, z,
xmin=-1.6 * R, xmax=1.6 * R,
ymin=-1.6 * R, ymax=1.6 * R,
zmin=-1.6 * R, zmax=1.6 * R,
wall='sphere', wall_args=(0., 0., 0., R))
else:
m.set_voronoi_grid(x, y, z,
xmin=-1.6 * R, xmax=1.6 * R,
ymin=-1.6 * R, ymax=1.6 * R,
zmin=-1.6 * R, zmax=1.6 * R)
If you do not give the limits of the domain, the domain is the box enclosing all the sites, with a border of 1 percent on each side. In both cases, the cells of the outermost sites extend all the way to the edge of the rectangular domain. Since our sites fill a sphere, the outermost cells then extend into the corners of the domain, beyond the edge of the cloud, and the density we assign to these cells fills a much larger volume than intended.
To avoid this, we can pass wall='sphere' and
wall_args=(x0, y0, z0, r), where (x0, y0, z0) is the center of the
sphere and r is its radius (in cm). The cells are then also cut by the
sphere, and photons leave the grid when they cross it. All the sites must be
strictly inside the sphere. Note that each outer cell is cut by the plane
tangent to the sphere at the point closest to its site, so the boundary of
the grid is a polyhedral approximation of the sphere, which becomes better as
the number of cells near the boundary increases.
Dust, sources, and images#
The rest of the setup is the same as for any other kind of grid. The density is given as a 1-d array with one value per site, and we add three point sources, as well as images at three wavelengths covering the whole domain:
# Add the density, with one value per site, in the same order as the sites
m.add_density_grid(rho, dust)
# Add a hot star at the center and two cooler stars
for position, luminosity, temperature in [((0., 0., 0.), 3.e4, 20000.),
((0.45 * R, -0.25 * R, 0.1 * R), 2.e3, 6000.),
((-0.35 * R, 0.4 * R, -0.2 * R), 1.e3, 4000.)]:
source = m.add_point_source()
source.position = position
source.luminosity = luminosity * lsun
source.temperature = temperature
# Compute an image covering the whole domain, viewed down the z axis
image = m.add_peeled_images(sed=False, image=True)
image.set_viewing_angles([0.], [0.])
image.set_image_size(150, 150)
image.set_image_limits(-1.6 * R, 1.6 * R, -1.6 * R, 1.6 * R)
Since we are only interested in scattered light at optical wavelengths, we do not compute the temperature of the dust, and we use Monochromatic radiative transfer to compute images only at the three wavelengths we need (see also How to efficiently compute pure scattering models):
# We only compute scattered light images at three wavelengths, so we use
# monochromatic radiative transfer and do not compute temperatures. In
# monochromatic mode, photons lose energy each time they scatter, and
# we stop following them once their energy has decreased by a factor
# of 10^4.
m.set_monochromatic(True, wavelengths=[0.45, 0.55, 0.8], energy_threshold=1.e-4)
m.set_n_initial_iterations(0)
m.set_n_photons(imaging_sources=500000, imaging_dust=0)
return m
Running the models#
Finally, we write out and run the model without and with the spherical wall:
for name, wall in [('voronoi_cloud_nowall', False),
('voronoi_cloud_wall', True)]:
m = setup_model(wall)
m.write(name + '.rtin')
m.run(name + '.rtout', overwrite=True)
The two models take about a minute and a half each to run on a single core (under three minutes in total for the whole script). To run them in parallel with MPI instead, you can use for example:
m.run(name + '.rtout', overwrite=True, mpi=True, n_processes=4)
Note that the random numbers then differ, so the noise in the images will not be exactly the same as in the figure below.
Warning
In this example we only compute scattered light, but if you compute dust temperatures, then as for any other grid the cells need to be small enough to resolve the temperature gradients. The temperature varies most rapidly close to the sources and across optically thick boundaries (for example at the surface of a dense clump or disk), and these are not necessarily the places where the density is highest. A Voronoi grid taken directly from the particles of a simulation, or with sites placed according to the density as in this example, may therefore not have enough resolution there, for example in low-density regions around sources. In such cases, you may need to add sites in those regions (and assign a density to the new cells) to get accurate temperatures. As always, you can check whether the resolution is sufficient by increasing it and making sure that the results do not change.
Plotting the results#
To show the effect of the spherical wall, we make a figure with a slice
through the grid at z=0 for each model, and the corresponding images. We
read the sites and the density in each cell back from the output files with
get_quantities(), and find which cell each
pixel of the slice belongs to by finding the closest site. For the model with
the wall, we also blank out the pixels that are cut off by the wall:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib.patches import Circle
from scipy.spatial import cKDTree
from hyperion.model import ModelOutput
from hyperion.util.constants import au, pc
# Radius of the cloud and half-width of the domain, as in the setup script
R = 1.e4 * au
L = 1.6 * R
# Pixel positions for a slice through the grid at z=0 (in cm)
n_pix = 350
xs = np.linspace(-L, L, n_pix)
X, Y = np.meshgrid(xs, xs)
pixels = np.column_stack([X.ravel(), Y.ravel(), np.zeros(X.size)])
fig, axes = plt.subplots(2, 2, figsize=(9, 9.5))
for column, (name, title) in enumerate([('voronoi_cloud_nowall', 'No wall'),
('voronoi_cloud_wall', 'Spherical wall')]):
mo = ModelOutput(name + '.rtout')
# Read back the Voronoi sites and the density in each cell
grid = mo.get_quantities()
sites = np.column_stack([grid.x, grid.y, grid.z])
rho = grid['density'][0].array
# Each pixel belongs to the cell of the closest site
_, cell = cKDTree(sites).query(pixels)
cell = cell.reshape(X.shape)
rho_slice = rho[cell]
if title == 'Spherical wall':
# With the spherical wall, each cell is cut by the plane tangent to
# the sphere at the point closest to its site, so we blank out the
# pixels that lie beyond that plane
s = sites[cell]
s_unit = s / np.linalg.norm(s, axis=-1)[:, :, np.newaxis]
outside = X * s_unit[:, :, 0] + Y * s_unit[:, :, 1] > R
rho_slice[outside] = np.nan
cell[outside] = -1
# Find the boundaries between cells, to overlay them on the density
edges = np.zeros(X.shape, dtype=bool)
edges[1:, :] |= cell[1:, :] != cell[:-1, :]
edges[:, 1:] |= cell[:, 1:] != cell[:, :-1]
edges_rgba = np.zeros(X.shape + (4,))
edges_rgba[edges] = (1., 1., 1., 0.4)
extent = [-L / au / 1000, L / au / 1000, -L / au / 1000, L / au / 1000]
# Top row: slice through the cells, colored by density
ax = axes[0, column]
ax.set_facecolor('black')
ax.imshow(rho_slice, origin='lower', extent=extent, cmap='magma',
norm=LogNorm(vmin=5e-21, vmax=3e-18), interpolation='nearest')
ax.imshow(edges_rgba, origin='lower', extent=extent, interpolation='antialiased')
ax.add_patch(Circle((0, 0), R / au / 1000, fill=False, color='#7fd3ff',
lw=1, ls='--'))
ax.set_title(title + ': cells at z=0')
# Bottom row: three-color scattered light image (red=0.8, green=0.55,
# blue=0.45 microns), with the same arcsinh stretch for both models
image = mo.get_image(units='MJy/sr', distance=300 * pc)
rgb = image.val[0][:, :, ::-1]
rgb = np.clip(np.arcsinh(rgb / 100.) / np.arcsinh(5000. / 100.), 0., 1.)
ax = axes[1, column]
ax.imshow(rgb, origin='lower', extent=extent, interpolation='nearest')
ax.add_patch(Circle((0, 0), R / au / 1000, fill=False, color='#7fd3ff',
lw=1, ls='--'))
ax.set_title(title + ': image at 0.45/0.55/0.8 $\\mu$m')
for ax in axes.ravel():
ax.set_xlabel('x (1000 au)')
ax.set_ylabel('y (1000 au)')
fig.tight_layout()
fig.savefig('voronoi_cloud.png', dpi=80)
which gives:
The dashed circle shows the edge of the cloud. Without a wall (left), the outer cells extend far beyond the cloud, to the edges of the domain, so the model actually contains a large volume of material outside the sphere. This material shows up as diffuse scattered light filling the whole image, with straight-edged structures following the shapes of the large outer cells, and the extra dust in front of the cloud reduces the contrast of the clumps. With the spherical wall (right), the cells stop at the sphere, and the image shows the cloud as intended.