Skip to content

Running

solve

solve(
    experiment: Experiment,
    overrides: Mapping[str, Any] | None = None,
) -> list[WedgeSummary]

Run an experiment and return one summary per wedge.

Parameters:

  • experiment (Experiment) –

    The validated configuration.

  • overrides (Mapping[str, Any], default: None ) –

    Values to use in place of the configured ones, keyed by configuration path -- "beam.flux", "wedges.0.exposure_time". Only paths in :data:TUNABLE are accepted. Pass tensors here and the whole calculation runs in torch and the summaries come back as tensors, so a strategy can be optimised by gradient descent::

    fwhm = torch.tensor([20.0, 20.0], dtype=torch.float64, requires_grad=True)
    summary = solve(experiment, {"beam.fwhm": fwhm})[0]
    summary.max_dose.backward()
    

Returns:

  • list[WedgeSummary] –

    One entry per wedge, in order, each holding the sixteen reported numbers.

Raises:

  • KeyError –

    If an override names a path that is not tunable. Crystal geometry is rejected explicitly: autograd returns a number for it and the number is wrong, because the occupancy test is a boolean parity count.

  • NotImplementedError –

    If escape modelling is asked for with tensor overrides: it is Monte Carlo, and has no gradient.

Notes

With no overrides this is pure NumPy, which is what the conformance corpus runs and what a CCP4 install without torch gets. The crystal mesh and the voxel grid stay NumPy either way: they are fixed geometry whose occupancy is counted rather than measured, so there is no gradient there worth carrying. :func:~pyraddose_3d.backend._array.to_namespace reconciles the two at the boundary.

simulate

simulate(
    experiment: Experiment,
    overrides: Mapping[str, Any] | None = None,
    *,
    record_images: bool = False,
) -> Simulation

Run an experiment and keep everything it produced.

The same calculation as :func:solve, returning the per-voxel fields alongside the summaries.

Parameters:

  • experiment (Experiment) –

    The validated configuration.

  • overrides (Mapping[str, Any], default: None ) –

    As for :func:solve.

  • record_images (bool, default: False ) –

    Also keep every voxel's dose, fluence and decay after every image. Needed for per-image outputs; off by default because it costs a field per image.

Returns:

  • Simulation –

    The grid, the per-wedge exposures and the summaries.

Raises:

  • KeyError –

    If an override names a path that is not tunable.

  • ValueError –

    If the experiment runs RADDOSE-3D's MicroED engine, or its Monte Carlo or XFEL subprogram, which have entry points of their own.

  • NotImplementedError –

    If escape modelling is asked for with tensor overrides.

Simulation dataclass

Everything a run produced, not just the reported numbers.

:func:solve returns only the summaries, which is what an optimiser wants. The output files and the conformance checks need the fields the summaries were reduced from -- which voxels are inside the crystal, where they are, and what each received.

Attributes:

  • experiment (Experiment) –

    What was run: the configuration with any overrides written in, as :func:apply_overrides gives it.

  • mesh (Mesh) –

    The crystal, with its angles applied. Its bounding box is what RADDOSE-3D reports as the crystal's size.

  • coefficients (MaterialCoefficients) –

    Absorption, attenuation, elastic and inelastic coefficients at the beam energy, in inverse micrometres. For a pink beam, at the last energy sampled, as RADDOSE-3D reports them.

  • grid (VoxelGrid) –

    The voxel grid, in the lab frame before any rotation.

  • occupied (Array) –

    (N,) boolean, which voxels are inside the crystal.

  • density (Array) –

    Crystal density in g/cm^3.

  • angles (list[list[Any]]) –

    The rotation angles of each wedge, in radians.

  • exposures (list[ExposureResult]) –

    One per wedge. dose is cumulative over all wedges so far; fluence, elastic and absorbed_energy are that wedge's alone, as in RADDOSE-3D's per-wedge observer.

  • summaries (list[WedgeSummary]) –

    One per wedge -- what :func:solve returns.

  • seed (int | None) –

    The seed escape modelling drew its random numbers from: the experiment's, or one chosen at random if it gave none. None without escape.

TUNABLE module-attribute

TUNABLE: frozenset[str] = frozenset(
    {
        "beam.flux",
        "beam.energy",
        "beam.fwhm",
        "beam.collimation.x",
        "beam.collimation.y",
        "wedges.*.start",
        "wedges.*.exposure_time",
        "wedges.*.rot_axis_beam_offset",
        "wedges.*.start_offset",
        "wedges.*.translate_per_degree",
    }
)

FIXED module-attribute

FIXED: dict[str, str] = {
    "crystal.dimensions": _GEOMETRY_IS_COUNTED,
    "crystal.diameter": _GEOMETRY_IS_COUNTED,
    "crystal.height": _GEOMETRY_IS_COUNTED,
    "crystal.angle_p": _GEOMETRY_IS_COUNTED,
    "crystal.angle_l": _GEOMETRY_IS_COUNTED,
    "crystal.pixels_per_micron": "the voxel grid shape is an integer count, so this is a step function with a zero derivative everywhere it is defined",
    "wedges.*.end": "the end of a wedge sets how many images are taken and nothing else. exposure_angles returns begin + step * resolution, so the angles depend on the start and the step, never on the end; the end appears only inside an integer count. Ending at 88 or 89 degrees both give 45 images and identical doses, and 90 gives 46. The derivative is therefore zero wherever it exists. Optimise the exposure time, which is what actually trades dose against completeness at fixed rotation",
    "wedges.*.angular_resolution": "the angular step sets the number of images, an integer count, so this is a step function like wedges.*.end",
}

MicroED

A crystal with subprogram: microed and an electron beam runs RADDOSE-3D's MicroED engine instead, through its own entry point.

microed

microed(experiment: Experiment) -> MicroEDResult

Run RADDOSE-3D's MicroED engine: Subprogram EMED, or EMSP.

A deterministic calculation, ported from MicroED.CalculateEM: the dose to a thin crystal from its stopping power, slice by slice; how many electrons scatter elastically and inelastically; and a grid search for the voltage and thickness that would give the most diffraction information per unit dose. See :mod:pyraddose_3d.backend.microed.

The crystal's extent along each axis, after angle_p and angle_l, sets its size; z is along the beam, so it is the thickness. MicroED ignores the wedges, escape, the container and the decay model.

Parameters:

  • experiment (Experiment) –

    A configuration whose crystal has subprogram: microed and whose beam is an electron beam.

Returns:

Raises:

  • ValueError –

    If the experiment is not a MicroED one, or if its composition is the average one, which has no elements to scatter from.

MicroEDResult dataclass

What MicroED.CalculateEM reports.

Attributes:

  • energy (float) –

    Beam energy in keV.

  • dose (float) –

    Mean dose over the slices of the exposed volume, in MGy.

  • slice_doses (tuple[float, ...]) –

    Dose of each slice, from the entrance face, in MGy. The slices share the thickness equally, at least 5 nm each, and there is always at least one. Slices after the electrons have stopped are zero.

  • slice_width (float) –

    Their width, in nm.

  • elastic, single_elastic, inelastic, productive (float) –

    Electrons scattered elastically at least once, exactly once, inelastically, and productive: once elastically, never inelastically.

  • information_coefficient (float) –

    Productive electrons per MGy.

  • best_energy (float) –

    The accelerating voltage the grid search finds best, in kV.

  • best_thickness (float) –

    The thickness the grid search finds best, in nm.

  • density (float) –

    Crystal density in g/cm^3.

  • elastic_mean_free_path, inelastic_mean_free_path (float) –

    At the beam energy, in nm.

  • csda_range (float) –

    Continuous-slowing-down range at the beam energy, in nm.

  • lacking_bindings (tuple[str, ...]) –

    The elements the inelastic model has no binding energies for. When there are any, every value the inelastic model feeds is NaN.

Monte Carlo, GOS and XFEL

A crystal with subprogram: montecarlo, gos or xfel runs RADDOSE-3D's Monte Carlo, photon by photon, through its own entry point: on NumPy, or with PyTorch on a device such as a GPU.

monte_carlo

monte_carlo(
    experiment: Experiment, *, device: str | None = None
) -> list[SimpleRun]

Run RADDOSE-3D's Monte Carlo, Subprogram MONTECARLO, GOS or XFEL.

Compared with RADDOSE-3D statistically, by tests/conformance/test_montecarlo_files.py.

Parameters:

  • experiment (Experiment) –

    A crystal with subprogram: montecarlo, gos or xfel. Its seed seeds the generator; the port does not reproduce RADDOSE-3D's draws, only their distribution.

  • device (str, default: None ) –

    A torch device to follow the photons and electrons on -- "cuda", "cuda:1" or "cpu" -- in float64, with torch's random numbers, which are not NumPy's: the same seed gives a different run, as likely as NumPy's, and repeats it to the last bit on the same model of device. Needs PyTorch (the torch extra). By default, NumPy, on the CPU. On a GPU, photons go in batches as large as a quarter of its memory holds, and the geometry and the electrons' physics are compiled by torch.compile: about 20 s the first time on a machine, and 5 s in each process after, from torch's cache. PYRADDOSE_MC_FUSE=0 in the environment leaves them uncompiled.

Returns:

SimpleRun dataclass

One run: a row of outputMC.CSV and one of outputXFEL.CSV.

Attributes:

  • rd3d_adwc, rd3d_ader (float) –

    RADDOSE-3D-style dose -- the energy of every absorbed photon and Compton electron, left where it was freed -- over the whole crystal and over its exposed region, MGy.

  • mc_adwc, mc_ader (float) –

    The Monte Carlo's dose, the same two ways, MGy.

  • elastic (float) –

    Elastically scattered photons, scaled to the real photon count: numEl.

  • xfel_adwc, xfel_ader (float) –

    outputXFEL.CSV's doses: GOS mode's, or in simple mode the Monte Carlo's own, MGy.

  • diffraction_efficiency (float) –

    numEl over xfel_ader.

  • ions_per_atom, ions_per_non_h_atom (float) –

    Ionisations per atom, and per atom other than hydrogen, in the exposed region.

  • resolved_no_cut, dwd_coarse, dwd (float) –

    vResolvedNoCut, DWDcoarse and DWD.

  • resolved_no_cut_exposed (float) –

    vResolvedNoCut over the exposed region, MGy: what GOS mode prints as its exposed region's dose.

  • gos (bool) –

    Whether the run was in the GOS model.

  • xfel (bool) –

    Whether it was the XFEL subprogram's.

  • printed_ions_per_atom (float) –

    The XFEL subprogram's printed ionisations per atom in the exposed region: as ions_per_atom, but unrounded.

  • ions_per_element (dict[int, float]) –

    outputIonsPerAtom.CSV: ionisations per atom in the exposed region, for each element ionised, by atomic number.

  • diagnostics (dict[str, float]) –

    Electrons followed and the passes it took.