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.modeisexact(every ion is in a TRIM.DAT file, the default) orbinned(one SRIM run per bin, see the design).binsmapsenergy_keVand/orangle_degto a number of equal-probability bins (an int) or to bin edges (a list);max_binscaps 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).rangeis required and is the support. The density is tabulated onGRID_POINTSpoints; it must be finite and not negative.fn_or_refis either a module-level function (stored aspython:<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
meanandsigma(default support mean ± 5 sigma).
- class srim.beam.Histogram(edges: Any, counts: Any, file: Any = None, range: Any = None)¶
Piecewise-constant density: bin
ispansedges[i]toedges[i+1].countsare weights (they need not be normalised); the density in a bin is its share of the total divided by the bin width.fileis the path a histogram was read from (seefrom_file()); it is None for an inline histogram.YAML takes exactly one of
file;edgeswithcounts; orcentreswithcounts(seeshape_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.histfilefor the layout).A relative
pathis taken frombase_dir(the working directory when None). The histogram’sfileis 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 xis normal withmuandsigma.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_nmandz_nmare the lateral coordinates;depth_nmmust lie inside the target. Positions are exact-mode only.
- class srim.beam.Shape(range: Any = None)¶
Base of the distribution shapes; subclasses set
kindand 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
keyif no probability is left
- degenerate() float | None¶
The value of a zero-width shape, else None.
- equal_probability_edges(n: int) ndarray¶
n + 1edges that cut the distribution intonbins of equal probability.
- interval_mean(low: float, high: float) float¶
Mean of the distribution restricted to
[low, high](exact fornodes()).- Raises:
ValueError – if no probability lies in
[low, high]
- mean() float¶
Mean of the (truncated) distribution.
- nodes() tuple[ndarray, ndarray]¶
(x, F): increasingxand the CDFFfrom 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.
- support() tuple[float, float]¶
The finite support
(low, high): the default support intersected withrange.- Raises:
SpecError – if the range leaves no probability
- to_dict(inline: bool = False) dict[str, Any]¶
{kind: {params..., "range": [lo, hi]}};inlineadds 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,modeandhigh.
- 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
Scanthatrun_beam()runs forspec.For an exact spec with up to 99 999 ions (no
precision, nobatch_ions) this is the one-point scanScan(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 (itsTRIM.INis the one ofTRIM.from_spec(spec)). Otherwise the scan hasionsofspec(or theprecisiongoal) with the spec’s seed, split into units ofbatch_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 firstbatch_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 ofspec.number_ionsextract (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
SpecErrornaming the dotted key.Called by
RunSpec.from_dict(withprefix"spec."for a run file). A spec without distributions and withoutbeampasses unchecked; abeamsection 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), andy_nm,z_nm,depth_nm(0.0 withoution.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 thatrun_beam()makes); nothing else is deleted. Default: none.
- Returns:
with the surface of
srim.output.Results(the per-ion tables have thebatchcolumn, and the bin columnsbeam_batch,bin,bin_energy_keV,bin_angle_degof a binned beam);specis the point’s spec andbeam_binsthe bins table of a binned beam (None otherwise). Use it as a context manager or callclose().- Return type:
- Raises:
FileNotFoundError – when the folder has no
run.yamlorunits.csv(not a finished batched point)SpecError – when
run.yamlis 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(),binsbars) with the defined density (the clipped distribution ofsrim.beam.spec.effective()) as a line. A binned run is drawn as one bar per bin ofparameter(height: probability per unit of the parameter, summed over the bins of the other parameter) with the defined density as a line. Binned runs binenergy_keVandangle_degonly.- Parameters:
results (
srim.output.Resultsorsrim.scan.MergedResults) – the results ofsrim.beam.run_beam()(or of a run of the beam)parameter (str) –
energy_keV(default),angle_deg,azimuth_deg,y_nm,z_nmordepth_nmax (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), orrunner(spec)when a runner is given (output_diris 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 aprecisiontarget runs batches until it is met.- Parameters:
spec (
srim.spec.RunSpec) – the run; validated first (RunSpec.validate())output_dir (path-like, optional) – where the results go. Default: a temporary folder that the returned results delete on
close().precision (
srim.scan.Precision, optional) – run batches until a precision goal is reached instead ofspec.number_ionsionsextract (list, optional) – extractors of the scan (see
srim.scan.Scan); default none (the results are read withopen_results())workers – as for
srim.scan.run_scan()cache – as for
srim.scan.run_scan()on_event – as for
srim.scan.run_scan()runner (callable, optional) –
runner(spec) -> Resultsin place of SRIM (tests and custom back ends; seesrim.scan.run_scan())
- Returns:
Resultsfor one TRIM run,MergedResultsfor a scan point. Useclose()orwith: for a temporary folder that deletes it.- Return type:
- 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:ionis the global ion number andbatchthe 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 aShape; 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 histogramfileis taken frombase_dir(the working directory when None).- Raises:
SpecError – naming
keyfor an unknown kind or parameter, a missing parameter or an invalid value