Choosing the energy¶
The diffraction efficiency is the number of photons a crystal scatters elastically -- the diffraction -- per MGy of diffraction-weighted dose: how much data each unit of damage buys. Nearly everything in it depends on the beam energy: how strongly the crystal absorbs, how strongly it scatters, how far the beam gets into it. So which energy is best?
This notebook answers that for a crystal and a detector, first by
scanning and then by gradient, and shows the one place a gradient needs
help: absorption edges. programs/optimise packages the search as a run
script.
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
from pyraddose_3d.backend.detector import sensor_absorption
from pyraddose_3d.models.experiment import Experiment
from pyraddose_3d.optimise import absorption_edges, maximise_energy
from pyraddose_3d.solve import apply_overrides, solve
experiment = Experiment.from_file(
"../../programs/optimise/optimise_energy_example_config.yaml"
)
def efficiency(experiment, energy):
"""Diffraction efficiency at an energy, in photons per MGy."""
summary = solve(experiment, {"beam.energy": energy})[0]
return float(summary.diffraction_efficiency)
An insulin crystal, 40 x 30 x 20 um, in a 15 um Gaussian beam. Neither the flux nor the exposure time matters to the answer: with no decay model, both scale the diffraction and the dose together.
for flux, seconds in ((2e12, 30.0), (5e11, 7.0)):
summary = solve(experiment, {"beam.flux": flux, "wedges.0.exposure_time": seconds})[
0
]
print(
f"{flux:.0e} photons/s for {seconds:4.0f} s: "
f"{float(summary.diffraction_efficiency):.6g} photons/MGy"
)
2e+12 photons/s for 30 s: 1.19433e+09 photons/MGy 5e+11 photons/s for 7 s: 1.19433e+09 photons/MGy
A scan¶
Seventy-one runs, every half keV from 5 to 40:
started = time.perf_counter()
energies = np.arange(5.0, 40.01, 0.5)
scanned = np.array([efficiency(experiment, e) for e in energies])
scan_seconds = time.perf_counter() - started
print(f"{len(energies)} runs, {scan_seconds:.1f} s")
edges = absorption_edges(experiment, 5.0, 40.0)
print("absorption edges in range:", edges, "keV")
fig, ax = plt.subplots(figsize=(6.5, 3.8), constrained_layout=True)
ax.plot(energies, scanned, ".-")
for edge in edges:
ax.axvline(edge, color="grey", ls=":", lw=1)
ax.set_xlabel("beam energy (keV)")
ax.set_ylabel("diffraction efficiency (photons/MGy)")
plt.show()
71 runs, 10.2 s absorption edges in range: [9.659] keV
Efficiency rises with energy: elastic scattering falls off more slowly than photoabsorption, so each MGy buys more diffraction. It dips at the zinc K edge, where zinc starts absorbing more. Near 36 keV it levels off and turns down, as Compton scattering -- which deposits dose too -- takes over from photoabsorption.
Taken at face value, that says use the highest energy available. But the efficiency counts photons the crystal scatters, not photons a detector records.
The detector¶
A detector records a photon only if its sensor absorbs it, and a thin
silicon sensor lets most hard X-rays straight through.
sensor_absorption gives the fraction absorbed, from the same cross-
sections the crystal uses:
sensors = {
"silicon, 450 um": ("Si", 450.0),
"silicon, 1000 um": ("Si", 1000.0),
"CdTe, 750 um": ("CdTe", 750.0),
}
absorbed = {name: sensor_absorption(energies, *s) for name, s in sensors.items()}
fig, (left, right) = plt.subplots(1, 2, figsize=(11, 3.8), constrained_layout=True)
for name in sensors:
left.plot(energies, absorbed[name], label=name)
right.plot(energies, scanned * absorbed[name], label=name)
right.plot(energies, scanned, color="grey", ls="--", label="all scattered")
left.set_xlabel("beam energy (keV)")
left.set_ylabel("fraction absorbed by the sensor")
right.set_xlabel("beam energy (keV)")
right.set_ylabel("detected photons per MGy")
right.legend(fontsize=8)
plt.show()
for name in sensors:
detected = scanned * absorbed[name]
print(f"{name:18s} best in the scan: {energies[np.argmax(detected)]:4.1f} keV")
silicon, 450 um best in the scan: 11.5 keV silicon, 1000 um best in the scan: 14.5 keV CdTe, 750 um best in the scan: 36.5 keV
Now there is a real optimum, and it depends on the detector: around 10-12 keV for a 450 um silicon sensor, higher for a thicker one, and the crystal's own optimum for CdTe, which absorbs nearly everything.
By gradient¶
The scan took seventy-one runs to locate the best energy to a quarter of
a keV. A gradient does better, because it says which way to go: within
a stretch of energies with no edge in it, the sign of the slope says
which side of a point the maximum lies, so each run halves the stretch.
maximise_energy splits the range at the absorption edges and does that
in each piece, keeping 50 eV clear of each edge -- real edges have fine
structure the model's sharp steps do not.
def detected_efficiency(summaries, energy):
"""What a 450 um silicon sensor records, per MGy."""
return summaries[0].diffraction_efficiency * sensor_absorption(energy, "Si", 450.0)
started = time.perf_counter()
searches = maximise_energy(experiment, detected_efficiency, 5.0, 25.0, clearance=0.05)
search_seconds = time.perf_counter() - started
runs = sum(search.evaluations for search in searches)
print(f"{runs} runs with gradients, {search_seconds:.1f} s")
for search in searches:
energy, value = search.best
print(
f"{search.low:6.3f}-{search.high:6.3f} keV: best {energy:6.3f} keV, "
f"{value:.4g} photons/MGy, {search.evaluations} runs"
)
15 runs with gradients, 1.8 s 5.000- 9.609 keV: best 9.609 keV, 1.041e+09 photons/MGy, 2 runs 9.709-25.000 keV: best 11.531 keV, 1.034e+09 photons/MGy, 13 runs
silicon = scanned * absorbed["silicon, 450 um"]
fig, ax = plt.subplots(figsize=(6.5, 3.8), constrained_layout=True)
ax.plot(energies, silicon, color="grey", label=f"scan, {len(energies)} runs")
for number, search in enumerate(searches):
x, y, _ = zip(*search.points, strict=True)
label = f"search, {runs} runs" if number == 0 else None
ax.plot(x, y, "o", color="C1", label=label)
ax.axvline(edges[0], color="grey", ls=":", lw=1)
ax.set_xlim(5, 25)
ax.set_xlabel("beam energy (keV)")
ax.set_ylabel("detected photons per MGy")
ax.legend()
plt.show()
The search spent two runs on the piece below the zinc edge -- the slope at its top end still pointed up, so its maximum is the top end -- and thirteen on the piece above, locating that maximum to 0.01 keV. Fifteen runs against the scan's seventy-one, and fifty times the precision.
Each of those runs also computed a gradient. That is cheap: the timings above put the whole search at a fraction of the scan, because a torch run with its gradient costs about what a plain NumPy run does.
The two pieces' best energies are within 1% of each other, and from 10.5 to 12.5 keV the detected efficiency stays within 2.5% of the best. Precision says where the top is; it does not say the top matters -- anywhere in that window does about as well.
Absorption edges¶
Selenomethionine puts selenium in the crystal, and selenium's K edge at 12.658 keV is a much bigger step than zinc's:
semet = Experiment.model_validate(
{
**experiment.model_dump(),
"crystal": {
**experiment.crystal.model_dump(),
"composition": {
**experiment.crystal.composition.model_dump(),
"protein_heavy_atoms": {"Zn": 0.333, "S": 6, "Se": 2},
},
},
}
)
coarse = np.arange(5.0, 40.01, 1.0)
semet_scan = np.array([efficiency(semet, e) for e in coarse])
below, above = 12.658 - 0.005, 12.658 + 0.005
for energy in (below, above):
point = torch.tensor(energy, dtype=torch.float64, requires_grad=True)
value = solve(semet, {"beam.energy": point})[0].diffraction_efficiency
value.backward()
print(
f"{energy:.3f} keV: {value.item():.4g} photons/MGy, "
f"slope {point.grad.item():+.3g} per keV"
)
12.653 keV: 1.236e+09 photons/MGy, slope +7.38e+07 per keV 12.663 keV: 7.971e+08 photons/MGy, slope +2.87e+07 per keV
Efficiency falls by a third across the edge, and the slope points up on both sides of it. A gradient describes only where it stands, so an optimiser climbing towards the edge from below has every reason to step over it -- and once over, it keeps climbing, to an energy worse than the one it left. Above the edge, efficiency never gets back to its value below it: it peaks near 39.5 keV, about 8% short.
Splitting at the edges avoids that, because each piece is smooth:
semet_searches = maximise_energy(
semet,
lambda summaries, _: summaries[0].diffraction_efficiency,
5.0,
40.0,
clearance=0.05,
)
for search in semet_searches:
energy, value = search.best
print(
f"{search.low:6.3f}-{search.high:6.3f} keV: best {energy:6.3f} keV, "
f"{value:.4g} photons/MGy, {search.evaluations} runs"
)
best = max(semet_searches, key=lambda search: search.best[1])
semet_runs = sum(search.evaluations for search in semet_searches)
print(
f"search: {best.best[0]:.3f} keV, {best.best[1]:.4g} photons/MGy, {semet_runs} runs"
)
print(
f"scan: {coarse[np.argmax(semet_scan)]:.3f} keV, {semet_scan.max():.4g} "
f"photons/MGy, {len(coarse)} runs"
)
fig, ax = plt.subplots(figsize=(6.5, 3.8), constrained_layout=True)
ax.plot(coarse, semet_scan, ".-", color="grey", label="scan")
for number, search in enumerate(semet_searches):
x, y, _ = zip(*search.points, strict=True)
ax.plot(x, y, "o", color="C1", label="search" if number == 0 else None)
for edge in absorption_edges(semet, 5.0, 40.0):
ax.axvline(edge, color="grey", ls=":", lw=1)
ax.set_xlabel("beam energy (keV)")
ax.set_ylabel("diffraction efficiency (photons/MGy)")
ax.legend()
plt.show()
5.000- 9.609 keV: best 9.609 keV, 1.056e+09 photons/MGy, 2 runs 9.709-12.608 keV: best 12.608 keV, 1.233e+09 photons/MGy, 2 runs 12.708-40.000 keV: best 39.520 keV, 1.13e+09 photons/MGy, 14 runs search: 12.608 keV, 1.233e+09 photons/MGy, 18 runs scan: 12.000 keV, 1.187e+09 photons/MGy, 36 runs
The coarse scan never samples the stretch just below the edge, so it misses the best energy, by about 4% in efficiency, despite twice the runs. A finer scan would find it; the search found it without being told where to look, because it knew where the edges were.
For diffraction efficiency, stay just below the selenium edge. That is the opposite of what a SAD experiment wants, which needs the anomalous signal at the edge -- efficiency does not count anomalous differences, so it cannot weigh that trade. It is the right question for native data from a selenomethionine crystal.
Keeping the answer¶
apply_overrides writes the energy into the configuration, so the
strategy can be saved as YAML and run like any other. Re-running it
without gradients, on NumPy -- the backend whose agreement with
RADDOSE-3D the conformance tests establish -- gives the same efficiency
to well under a tenth of a percent:
energy, found = max((search.best for search in searches), key=lambda b: b[1])
optimised = apply_overrides(experiment, {"beam.energy": energy})
summary = solve(optimised)[0]
rerun = float(summary.diffraction_efficiency * sensor_absorption(energy))
print(f"energy {optimised.beam.energy:.3f} keV")
print(f"detected {rerun:.4g} photons/MGy, {abs(rerun / found - 1):.1e} from the search")
energy 9.609 keV detected 1.041e+09 photons/MGy, 1.0e-05 from the search
What this leaves out¶
- Photoelectron escape. From a crystal a few micrometres across,
photoelectrons carry energy out before depositing it, more so at higher
energies, so the answer here understates what high energies offer small
crystals. The port models escape as RADDOSE-3D does, but by Monte Carlo,
which has no gradient, so the search cannot include it; rerun the chosen
energy with
escape: {photoelectron: true}to see how much it changes. - The detector's real efficiency. The sensor model is the fraction absorbed, an upper bound that ignores charge sharing, fluorescence escape, counting thresholds and dead area.
- Anomalous signal, as above.