Gradients¶
With PyTorch installed (pip install pyRADDOSE-3D[torch]), the dose
calculation is differentiable: hand solve a tensor for a setting and
every number it returns carries a gradient with respect to it. That turns
"which strategy is best?" from a parameter scan into an optimisation.
Without a tensor, nothing changes -- the calculation stays on NumPy, which is what the conformance tests against RADDOSE-3D check.
import matplotlib.pyplot as plt
import torch
from pyraddose_3d.models.experiment import Experiment
from pyraddose_3d.solve import FIXED, TUNABLE, solve
experiment = Experiment.model_validate(
{
"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}],
}
)
A first gradient¶
Settings are named by their path in the configuration. How does the maximum dose respond to widening the beam?
fwhm = torch.tensor([15.0, 15.0], dtype=torch.float64, requires_grad=True)
max_dose = solve(experiment, {"beam.fwhm": fwhm})[0].max_dose
max_dose.backward()
print(f"max dose {max_dose.item():.2f} MGy")
print(f"d(max dose)/d(fwhm) = {fwhm.grad.tolist()} MGy per um")
max dose 127.29 MGy d(max dose)/d(fwhm) = [-8.486331279720451, -8.277183667281841] MGy per um
Checked against a central finite difference, widening both axes together:
step = 1e-3
up = solve(experiment, {"beam.fwhm": (15.0 + step, 15.0 + step)})[0].max_dose
down = solve(experiment, {"beam.fwhm": (15.0 - step, 15.0 - step)})[0].max_dose
print(f"finite difference {(float(up) - float(down)) / (2 * step):.6f}")
print(f"autograd {fwhm.grad.sum().item():.6f}")
finite difference -16.763515 autograd -16.763515
What can be tuned¶
The beam and the wedges can. The crystal's geometry and anything that sets a number of images cannot: those are integer counts -- which voxels are inside the crystal, how many images there are -- so the dose is a step function of them, and a gradient would be confidently wrong. Asking for one is refused with the reason.
print("tunable:")
for path in sorted(TUNABLE):
print(" ", path)
print("refused:")
for path in FIXED:
print(" ", path)
tunable: beam.collimation.x beam.collimation.y beam.energy beam.flux beam.fwhm wedges.*.exposure_time wedges.*.rot_axis_beam_offset wedges.*.start wedges.*.start_offset wedges.*.translate_per_degree refused: crystal.dimensions crystal.diameter crystal.height crystal.angle_p crystal.angle_l crystal.pixels_per_micron wedges.*.end wedges.*.angular_resolution
try:
solve(experiment, {"crystal.dimensions": torch.tensor([40.0, 30.0, 20.0])})
except KeyError as error:
print(error.args[0])
'crystal.dimensions' cannot be optimised: crystal geometry decides which voxels are inside the crystal, and that test is a boolean parity count. Autograd sees only the attenuation path through the mesh and is blind to voxels entering or leaving as the crystal changes size, so it returns a confident number that is missing a term -- measured 20% wrong against a finite difference for a cuboid's thickness. Optimise the beam and the wedge instead; the crystal is whatever came out of the drop
A small optimisation¶
The diffraction efficiency -- elastically scattered photons per MGy of diffraction-weighted dose -- rewards spreading the dose evenly. For this crystal it rises steeply with beam width and then levels off. Gradient ascent on the width, starting from a narrow beam, should climb onto that plateau. Optimising the logarithm of the width keeps it positive.
log_width = torch.tensor(10.0, dtype=torch.float64).log().requires_grad_()
optimiser = torch.optim.Adam([log_width], lr=0.15)
path = []
for _ in range(25):
width = log_width.exp()
efficiency = solve(experiment, {"beam.fwhm": torch.stack([width, width])})[0]
efficiency = efficiency.diffraction_efficiency
path.append((width.item(), efficiency.item()))
optimiser.zero_grad()
(-efficiency / 1e9).backward()
optimiser.step()
print(f"start {path[0][0]:5.1f} um: {path[0][1]:.3g} photons/MGy")
print(f"end {path[-1][0]:5.1f} um: {path[-1][1]:.3g} photons/MGy")
start 10.0 um: 6.94e+08 photons/MGy end 91.3 um: 1.84e+09 photons/MGy
Against a scan of the same objective:
widths = [5, 10, 15, 20, 30, 40, 50, 60, 80, 100]
scan = [
float(solve(experiment, {"beam.fwhm": (w, w)})[0].diffraction_efficiency)
for w in widths
]
fig, ax = plt.subplots(figsize=(6, 3.8), constrained_layout=True)
ax.plot(widths, scan, "o-", color="grey", label="scan")
ax.plot(*zip(*path, strict=True), ".-", color="C1", label="gradient ascent")
ax.set_xlabel("beam FWHM (um)")
ax.set_ylabel("diffraction efficiency (photons/MGy)")
ax.legend()
plt.show()
The ascent climbs the steep part quickly and reaches the plateau. There Adam's momentum carries it past the best width, near 60 um, but it ends within 0.3% of the best efficiency the scan found.
With one setting, the scan is the cheaper way: ten runs against twenty-five steps. The gradient pays off as settings multiply. Scanning n settings at ten values each costs 10^n runs; a gradient step costs a forward and a backward pass however many settings there are.
One caution. The image count and the voxel occupancy are steps, so a setting that changes them -- a wedge start moved far enough to add an image, say -- makes the objective jump, and the gradient cannot see the jump coming. Keep steps small compared with what changes those counts.