Crystals and beams¶
How the shape of the crystal and the profile of the beam decide where the dose goes. Each run here changes one thing from a common starting point and draws the dose through the middle of the crystal.
The beam travels along +z and the crystal rotates about y. A slice across the beam (an x-y plane) therefore shows the beam's profile, and a slice along it (an x-z plane) shows what rotation does.
import copy
import matplotlib.pyplot as plt
import numpy as np
from pyraddose_3d.models.experiment import Experiment
from pyraddose_3d.outputs import final_dose_state
from pyraddose_3d.solve import simulate
BASE = {
"crystal": {
"type": "cuboid",
"dimensions": [40.0, 30.0, 20.0],
"pixels_per_micron": 0.5,
"composition": {
"method": "unit_cell",
"unit_cell": [78.02, 78.02, 78.02],
"num_monomers": 24,
"num_residues": 51,
"protein_heavy_atoms": {"Zn": 0.333, "S": 6},
"solvent_heavy_conc": {"P": 425},
},
},
"beam": {"type": "gaussian", "flux": 2e12, "energy": 12.1, "fwhm": [15.0, 15.0]},
"wedges": [{"start": 0.0, "end": 90.0, "exposure_time": 30.0}],
}
def run(**changes):
"""Simulate the starting experiment with some settings changed.
Settings given as None are removed, so the default applies.
"""
config = copy.deepcopy(BASE)
for block, settings in changes.items():
merged = {**config[block], **settings}
config[block] = {k: v for k, v in merged.items() if v is not None}
return simulate(Experiment.model_validate(config))
def dose_slice(ax, simulation, plane="xy", vmax=None):
"""Draw the final dose in the voxel plane nearest the crystal's centre."""
state = final_dose_state(simulation)
xyz, dose = state["coordinates"], state["dose"]
across = {"xy": 2, "xz": 1}[plane]
shown = [axis for axis in range(3) if axis != across]
middle = xyz[:, across].mean()
nearest = np.abs(xyz[:, across] - middle).min()
keep = np.isclose(np.abs(xyz[:, across] - middle), nearest)
image = ax.scatter(
xyz[keep, shown[0]], xyz[keep, shown[1]], c=dose[keep],
marker="s", s=40, vmin=0, vmax=vmax, cmap="inferno",
) # fmt: skip
ax.set_aspect("equal")
ax.set_xlabel(f"{'xyz'[shown[0]]} (um)")
ax.set_ylabel(f"{'xyz'[shown[1]]} (um)")
return image
Crystal shapes¶
The same beam on a cuboid, a sphere and a cylinder of similar size. The sphere and the cylinder are polyhedra, as in RADDOSE-3D.
shapes = {
"cuboid": run(),
"sphere": run(crystal={"type": "spherical", "dimensions": None, "diameter": 30.0}),
"cylinder": run(
crystal={
"type": "cylinder",
"dimensions": None,
"diameter": 30.0,
"height": 30.0,
}
),
}
for name, simulation in shapes.items():
print(f"{name:9s} max dose {float(simulation.summaries[0].max_dose):5.2f} MGy")
cuboid max dose 127.29 MGy sphere max dose 126.73 MGy cylinder max dose 126.78 MGy
top = max(float(simulation.summaries[0].max_dose) for simulation in shapes.values())
fig, axes = plt.subplots(1, 3, figsize=(12, 3.8), constrained_layout=True)
for ax, (name, simulation) in zip(axes, shapes.items(), strict=True):
image = dose_slice(ax, simulation, "xz", vmax=top)
ax.set_title(name)
fig.colorbar(image, ax=axes, label="dose (MGy)")
plt.show()
A shape keyword the crystal does not use is an error, not silently ignored -- here a sphere given a cuboid's dimensions:
from pydantic import ValidationError
try:
run(crystal={"type": "spherical", "diameter": 30.0, "dimensions": [1, 2, 3]})
except ValidationError as error:
print(error.errors()[0]["msg"])
Extra inputs are not permitted
Beam profiles¶
A Gaussian beam, the same Gaussian behind a circular aperture, and a top hat filling a rectangular one. Seen across the beam, the dose follows the profile in y -- the rotation axis -- and is smeared out in x by rotation.
beams = {
"Gaussian": run(),
"Gaussian, 15 um circular aperture": run(
beam={"collimation": {"shape": "circular", "x": 15.0, "y": 15.0}}
),
"top hat, 15 um square": run(
beam={"type": "tophat", "fwhm": None,
"collimation": {"shape": "rectangular", "x": 15.0, "y": 15.0}}
),
} # fmt: skip
top = max(float(simulation.summaries[0].max_dose) for simulation in beams.values())
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6), constrained_layout=True)
for ax, (name, simulation) in zip(axes, beams.items(), strict=True):
image = dose_slice(ax, simulation, "xy", vmax=top)
summary = simulation.summaries[0]
ax.set_title(f"{name}\nmax {float(summary.max_dose):.1f} MGy")
fig.colorbar(image, ax=axes, label="dose (MGy)")
plt.show()
Closing the aperture raised the dose. In RADDOSE-3D the flux is the flux through the aperture -- the Gaussian is normalised over the open area -- so a smaller aperture puts the same photons into less crystal, rather than throwing some away.
Which beam is better depends on what is being traded. The diffraction efficiency -- elastically scattered photons per MGy of diffraction-weighted dose -- is one way to compare them:
for name, simulation in beams.items():
summary = simulation.summaries[0]
print(
f"{name:36s} average DWD {float(summary.average_dwd):5.2f} MGy "
f"efficiency {float(summary.diffraction_efficiency):.3g} photons/MGy"
)
Gaussian average DWD 27.95 MGy efficiency 1.19e+09 photons/MGy Gaussian, 15 um circular aperture average DWD 63.74 MGy efficiency 5.93e+08 photons/MGy top hat, 15 um square average DWD 50.54 MGy efficiency 7.7e+08 photons/MGy
A measured beam¶
The profile can also come from an image of the beam: a plain PGM file of relative intensities, and the size of its pixels. The flux sets the total, and the intensity between pixel centres is interpolated bilinearly. This image is made up, an off-centre peak on a ramp with a dead corner.
RADDOSE-3D lays the image's horizontal axis along the rotation axis, y, running the other way, and its vertical axis along x, also reversed: the peak right of centre in the image falls at negative y.
from pyraddose_3d.backend.beam import read_pgm
PGM = "../../tests/data/beam_profile.pgm"
measured = run(
beam={"type": "experimental", "fwhm": None, "file": PGM, "pixel_size": [1.5, 1.4]}
)
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 3.8), constrained_layout=True)
# read_pgm returns the beam's frame; undo it to draw the file as written.
left.imshow(read_pgm(PGM).T[::-1, ::-1], cmap="gray")
left.set_title("the image, as drawn")
left.set_axis_off()
image = dose_slice(right, measured, "xy")
right.set_title(
f"dose across the beam, max {float(measured.summaries[0].max_dose):.1f} MGy"
)
fig.colorbar(image, ax=right, label="dose (MGy)")
plt.show()