srim.beam

Beam distributions: probability shapes for the beam parameters of a run.

class srim.beam.BeamOptions(mode: str = 'exact', bins: dict = <factory>, max_bins: int = 2000)

The beam: section of a run spec.

mode is exact (every ion is in a TRIM.DAT file, the default) or binned (one SRIM run per bin, see the design). bins maps energy_keV and/or angle_deg to a number of equal-probability bins (an int) or to bin edges (a list); max_bins caps the combined bins of a binned beam.

to_dict() → dict[str, Any]

{mode, bins?, max_bins?}; optional keys only when not the default.

class srim.beam.Fixed(value: Any, range: Any = None)

A single value (a degenerate shape; shape_from_dict() returns it as a float).

class srim.beam.Function(fn_or_ref: Any, range: Any = None)

A density given by a Python function f(x) (vectorised over numpy arrays).

range is required and is the support. The density is tabulated on GRID_POINTS points; it must be finite and not negative. fn_or_ref is either a module-level function (stored as python:<module>:<name>) or such a reference string, imported when first used.

class srim.beam.Gaussian(mean: Any, sigma: Any, range: Any = None)

Normal distribution with mean and sigma (default support mean ± 5 sigma).

class srim.beam.Histogram(edges: Any, counts: Any, file: Any = None, range: Any = None)

Piecewise-constant density: bin i spans edges[i] to edges[i+1].

counts are weights (they need not be normalised); the density in a bin is its share of the total divided by the bin width. file is the path a histogram was read from (see from_file()); it is None for an inline histogram.

YAML takes exactly one of file; edges with counts; or centres with counts (see shape_from_dict()).

property counts: list[float]

The bin counts (a copy; the sampled distribution is fixed at construction).

property edges: list[float]

The bin edges (a copy; the sampled distribution is fixed at construction).

classmethod from_centres(centres: Any, counts: Any, file: Any = None, range: Any = None)

A histogram from bin centres: inner edges at the midpoints, outer edges half a neighbouring width beyond the first and last centre.

classmethod from_file(path: Any, base_dir: Any = None, range: Any = None) → Histogram

A histogram read from a text file (see srim.beam.histfile for the layout).

A relative path is taken from base_dir (the working directory when None). The histogram’s file is the absolute, resolved path.

Raises:

SpecError – naming the file, and the line for a bad row

class srim.beam.LogNormal(mu: Any, sigma: Any, range: Any = None)

Log-normal distribution: ln x is normal with mu and sigma.

The default support is exp(mu ± 5 sigma), tabulated on a logarithmic grid.

class srim.beam.PositionSpec(y_nm: float | Shape = 0.0, z_nm: float | Shape = 0.0, depth_nm: float | Shape = 0.0)

Where the ions start, in the target’s lateral frame (nm) and depth (nm).

Each value is a number or a distribution. y_nm and z_nm are the lateral coordinates; depth_nm must lie inside the target. Positions are exact-mode only.

class srim.beam.Shape(range: Any = None)

Base of the distribution shapes; subclasses set kind and implement the hooks.

kind

the YAML key of the shape

Type:

str

range

user truncation (low, high); the support is the default support intersected with it

Type:

tuple of float, or None

cdf(x: Any) → Any

P(X <= x).

clip(low: float, high: float, key: str) → Shape

This shape truncated to [low, high] (a physical domain, e.g. energy >= 0).

Raises:

SpecError – naming key if no probability is left

degenerate() → float | None

The value of a zero-width shape, else None.

equal_probability_edges(n: int) → ndarray

n + 1 edges that cut the distribution into n bins of equal probability.

interval_mean(low: float, high: float) → float

Mean of the distribution restricted to [low, high] (exact for nodes()).

Raises:

ValueError – if no probability lies in [low, high]

mean() → float

Mean of the (truncated) distribution.

nodes() → tuple[ndarray, ndarray]

(x, F): increasing x and the CDF F from 0 to 1 at those points.

The sampled distribution is the piecewise-linear CDF through these nodes. A zero-width shape gives the step x = [v, v], F = [0, 1].

pdf(x: Any) → Any

Density of the piecewise-linear CDF of nodes() (zero outside the support).

A zero-width shape has no density and gives zeros.

probabilities(edges: Any) → ndarray

Probability of each bin between consecutive edges.

sample(rng: Generator, n: int) → ndarray

n values drawn with rng (inverse CDF of nodes()).

support() → tuple[float, float]

The finite support (low, high): the default support intersected with range.

Raises:

SpecError – if the range leaves no probability

to_dict(inline: bool = False) → dict[str, Any]

{kind: {params..., "range": [lo, hi]}}; inline adds content that is not otherwise in the dict (histogram data, function source) for hashing.

class srim.beam.Triangular(low: Any, mode: Any, high: Any, range: Any = None)

Triangular distribution with low, mode and high.

class srim.beam.Uniform(low: Any, high: Any, range: Any = None)

Uniform distribution on [low, high].

srim.beam.beam_scan(spec, *, batch_ions=None, precision=None, extract=None)

The Scan that run_beam() runs for spec.

For an exact spec with up to 99 999 ions (no precision, no batch_ions) this is the one-point scan Scan(spec, ions=spec.number_ions, seed=spec.seed, keep_seed=True): its point runs with the spec’s own seed, so the run is the run of the spec (its TRIM.IN is the one of TRIM.from_spec(spec)). Otherwise the scan has ions of spec (or the precision goal) with the spec’s seed, split into units of batch_ions (an exact beam of more than 99 999 ions is split into units of 99 999 ions by default).

Parameters:
  • spec (srim.spec.RunSpec) – the run; validated first

  • batch_ions (int, optional) – units of this many ions (default: 99 999 for a larger exact beam, else none)

  • precision (srim.scan.Precision, optional) – run batches until this precision goal is reached instead of spec.number_ions

  • extract (list, optional) – extractors of the scan; default none

srim.beam.check_beam(spec, prefix: str = '') → None

Validate the beam part of a run spec; raise SpecError naming the dotted key.

Called by RunSpec.from_dict (with prefix "spec." for a run file). A spec without distributions and without beam passes unchecked; a beam section with no distribution is refused.

srim.beam.effective(spec) → dict[str, float | Shape]

The values a run samples from: distributions cut to their physical domain.

Keys: energy_keV (cut to (0, inf)), angle_deg (cut to [0, 90)), azimuth_deg (cut to [0, 360); a distributed spec without an azimuth gets the uniform full turn, anything else 0.0), and y_nm, z_nm, depth_nm (0.0 without ion.position). The spec itself is not changed: to_dict() keeps what was written.

srim.beam.fingerprint(spec) → str | None

SHA-256 hex digest of the source text of every Python-function distribution in spec.

The energy, angle, azimuth and position distributions are taken in that order; each function contributes its dotted key and the text srim.beam.shapes._source_of() gives it. None when the spec has no function, so the digest of a spec without one is not affected. Histogram content is not part of it (it is in the spec’s inline dict).

srim.beam.open_results(point_dir, cleanup=None) → MergedResults

The results of a finished batched scan point, merged as one result.

Parameters:
  • point_dir (path-like) – a point’s folder, <scan folder>/points/<id>

  • cleanup (path-like, optional) – a folder that close() deletes with the results (the temporary scan folder that run_beam() makes); nothing else is deleted. Default: none.

Returns:

with the surface of srim.output.Results (the per-ion tables have the batch column, and the bin columns beam_batch, bin, bin_energy_keV, bin_angle_deg of a binned beam); spec is the point’s spec and beam_bins the bins table of a binned beam (None otherwise). Use it as a context manager or call close().

Return type:

MergedResults

Raises:
  • FileNotFoundError – when the folder has no run.yaml or units.csv (not a finished batched point)

  • SpecError – when run.yaml is not a valid run file

srim.beam.plot_beam(results, parameter='energy_keV', ax=None, bins=50)

Plot a distributed beam’s parameter: the defined density and the sampled beam.

An exact run is drawn as a density histogram of the sampled ions (sampled_ions(), bins bars) with the defined density (the clipped distribution of srim.beam.spec.effective()) as a line. A binned run is drawn as one bar per bin of parameter (height: probability per unit of the parameter, summed over the bins of the other parameter) with the defined density as a line. Binned runs bin energy_keV and angle_deg only.

Parameters:
  • results (srim.output.Results or srim.scan.MergedResults) – the results of srim.beam.run_beam() (or of a run of the beam)

  • parameter (str) – energy_keV (default), angle_deg, azimuth_deg, y_nm, z_nm or depth_nm

  • ax (matplotlib Axes, optional) – where to draw; a new figure’s Axes if omitted

  • bins (int) – histogram bins of an exact run

Return type:

matplotlib.axes.Axes

Raises:
  • ValueError – for an unknown parameter, a parameter that is fixed in the run (nothing to plot), or a binned run and a parameter it does not bin

  • ImportError – when matplotlib is not installed (pip install "pysrim2[plot]")

srim.beam.run_beam(spec, *, output_dir=None, precision=None, extract=None, workers=None, cache=None, runner=None, on_event=None)

Run a run spec, distributed beam or not, and return its results.

An exact spec with up to 99 999 ions (and no precision) is one TRIM run: TRIM.from_spec(spec).run(output_dir=output_dir), or runner(spec) when a runner is given (output_dir is then not written). Otherwise the spec is a one-point scan (srim.scan.run_scan()): an exact beam of more ions is split into units of 99 999 ions, a binned beam runs one SRIM run per bin, and a precision target runs batches until it is met.

Parameters:
Returns:

Results for one TRIM run, MergedResults for a scan point. Use close() or with: for a temporary folder that deletes it.

Return type:

srim.output.Results or srim.scan.MergedResults

Raises:
  • SpecError – for an invalid spec (naming the dotted key)

  • RuntimeError – when a run of the scan failed or was stopped (the message has the row’s error)

srim.beam.sampled_ions(results) → DataFrame

The ions an exact run ran, one row each, read from its TRIM.DAT file(s).

The columns of srim.beam.exact.sample_ions() (ion, the parameters in SRIM’s units and the direction cosines). For results of several exact units (a split run, srim.scan.MergedResults) the units are concatenated: ion is the global ion number and batch the unit’s index.

Raises:

ValueError – for binned results (they have beam_bins) or any run without a TRIM.DAT file

srim.beam.shape_from_dict(value: Any, key: str, base_dir: Any = None) → float | Shape

The distribution given by a YAML value.

A number, or a mapping {fixed: {value: v}}, gives a float. A one-key mapping {kind: {params...}} gives a Shape; a zero-width shape gives its float. The shape is validated here (a function’s density too), so a bad distribution fails when the spec is read. A relative histogram file is taken from base_dir (the working directory when None).

Raises:

SpecError – naming key for an unknown kind or parameter, a missing parameter or an invalid value