Uncertainty quantification

No cavity is built exactly to its drawing. Uncertainty quantification (UQ) asks how far the figures of merit spread when the dimensions vary within their tolerances. In cavsim2d you add a uq_config to an ordinary run: the analysis then solves a set of perturbed shapes as well as the nominal one, and reports a mean and a standard deviation for each figure of merit instead of a single value.

Uncertainty quantification teaches the basics; this page is the full reference.

Running it

Put the uq_config inside the configuration of the run:

uq_config = {
    'variables': ['A', 'B'],                 # the dimensions that vary
    'delta': [0.2, 0.2],                     # by how much, in mm
    'method': ['Quadrature', 'Stroud3'],     # how the shapes are chosen
    'objectives': ['monopole:freq [MHz]', 'monopole:R/Q [Ohm]'],
}
study.run_eigenmode({'uq_config': uq_config})

study.eigenmode.uq_df                        # nominal, mean and spread, a table
study.eigenmode.plot_fm_scatter(uq=True)     # mean and spread beside the nominal

The same uq_config goes into a wakefield run, a tune or an optimisation:

  • in wakefield_config, it spreads the loss and kick factors and the impedance;

  • in tune_config, the tuner brings the mean frequency to the target, rather than the nominal cavity’s (robust tuning);

  • in an optimisation config, candidates are ranked by their mean and spread (robust optimisation).

The how-to guides at the end of this page show each one.

What delta means

delta is added to the dimension, in the dimension’s own unit: millimetres, or metres for an RF gun. 'perturbation_mode': 'mul' makes it a fraction of the dimension instead (0.01 for 1 %).

How the dimension then varies depends on method:

  • A quadrature rule, ['Quadrature', 'Stroud3'] (the default) or ['Quadrature', 'Stroud5'], and Latin hypercube sampling, ['lhs', N], vary each dimension evenly between -delta and +delta: a uniform spread whose standard deviation is delta divided by \(\sqrt{3}\).

  • ['normal', N] draws N shapes at random from a normal distribution whose standard deviation is delta.

Stroud3 needs the fewest solves, twice the number of varied dimensions, and gives the mean and the standard deviation. ['normal', N] costs N solves, but gives the whole distribution, which cav.eigenmode.plot_fm_distribution() draws.

Reading the results

cav.eigenmode.uq_df is a table of the run’s statistics, one row per objective:

Column

Meaning

nominal

The value of the unperturbed cavity.

mean

The mean over the perturbed shapes.

std

Their standard deviation: the spread the tolerances cause.

skew, kurtosis

The shape of the distribution.

se_mean, se_std

With a sampling method (['normal', N], ['lhs', N]) only: how uncertain the mean and the standard deviation themselves are. Raise N until they are small enough.

study.eigenmode.uq_df puts every cavity’s table in one, indexed by cavity and objective, so study.eigenmode.uq_df.loc['tesla'] is one cavity’s. study.eigenmode.plot_fm_scatter(uq=True) draws the same statistics: each mean with a bar of one standard deviation either side, and the two numbers written in the corner of each panel. show_stats=False leaves the numbers out; the wakefield plots (plot_hom_scatter(uq=True)) and plot_uq_comparison() take it too. A wakefield run’s statistics are in cav.wakefield.uq_df and study.wakefield.uq_df. Both read the saved results, so they also work on a project reopened with Study.load().

Settings

variables

(list of str) The dimensions that vary, by the names the cavity uses for them: 'A', 'Req' and so on for an elliptical cell, 'p2_r' for a spline, 'L3' for an RF gun. cav.tune_variables() lists them.

delta

(list of float) How much each dimension varies; see What delta means.

method

(list, default ['Quadrature', 'Stroud3'] ) How the perturbed shapes are chosen; see What delta means.

perturbation_mode

(str, default 'add' ) 'add' adds delta to the dimension; 'mul' multiplies the dimension by 1 + delta.

objectives

(list of str) The figures of merit to collect, named as in an optimisation, for example 'monopole:freq [MHz]'.

cell

(default 'all' ) With 'all', a variable varies in every type of cell separately: 'A' becomes A_m, A_el and A_er, each with its own spread. Any other value takes the variables exactly as named, so ['A_m'] varies the inner cells’ A alone.

cell_type

(str, default 'mid-cell' ) In a robust tune, the type of cell whose variables vary: 'mid-cell' or 'end-cell'.

cell_complexity

(str, default 'simplecell' ) 'simplecell' varies each type of cell as a whole; 'multicell' varies every half-cell of a multicell cavity on its own; see Choosing a perturbation model.

independent_half_cells

(bool, default False) With 'multicell': draw every half-cell independently, then weld the seams, as described below.

processes

(int, default 1) How many perturbed shapes to solve at once.

Important

A large delta can push a shape past what its dimensions allow, for example make two ellipses overlap, and such a shape cannot be built. Check the range first with cav.inspect(), which draws a cell with sliders for its dimensions.

How-to guides

Choosing a perturbation model

A tolerance can be posed in more than one way, and the choice changes the answer. The models below describe different manufacturing routes; they are not coarse and fine versions of the same thing. Which one fits your cavity depends on how it is actually made, and that is not something the code can decide for you.

How a cavity is divided

cavsim2d indexes an elliptical cavity as 2n half-cells for n cells, ordered left to right. Cell k is the pair (half_cells[2k], half_cells[2k+1]), so the two halves of a cell meet at its equator, and neighbouring cells meet at an iris.

A 3-cell cavity profile with its six half-cells numbered, equators marked inside each cell and irises marked between cells.

Fig. 5 The six half-cells of a 3-cell cavity. Equators lie inside a cell; irises lie between cells.

This has a consequence that is easy to miss. The first cell pairs end_l with a mid half, so Req_el and Req_m refer to the same physical equator. Setting them to different values does not describe a cavity you could build.

What welding does

Each part of a real cavity is formed on its own, so its dimensions carry their own error. Where two parts meet, the finished cavity has one dimension rather than two. cavsim2d follows the same sequence: it perturbs every part independently, then welds each seam by averaging the two values that meet there.

Two half-cells drawn with different equator radii, showing a 10 mm step at the equator, beside the same pair after averaging, which closes the step.

Fig. 6 Left: two half-cells whose equator radius was drawn independently, so the profile does not close. Right: after welding, both carry the average and the profile is continuous.

Welding does more than close the gap in the drawing. It also narrows the distribution, because averaging two independent draws of standard deviation \(\sigma\) leaves a single value with standard deviation \(\sigma/\sqrt{2}\). A model that welds a joint predicts less scatter than one that does not, and that difference is physical rather than numerical.

The three models

The same 3-cell cavity shown three times, with its half-cells shaded by which independently formed part they belong to, and each seam marked as a weld or as internal to one part.

Fig. 7 The same cavity under each model. Shading groups the half-cells that come from one independently formed part. A solid line is a welded seam, where two draws are averaged; a dashed line lies inside a single part, so nothing is averaged there.

The three models differ in how finely the cavity is divided, and therefore in how many seams are welds:

  • base has two parts, so only the two mid-to-end equators are welds.

  • multicup has one part per half-cell, so every equator and every iris is a weld.

  • dumbbell has one part per dumb-bell, so the equators are welds and the irises sit inside a part.

Three grids of half-cell index against parameter, coloured by which random variable drives each slot, for the base, multicup and dumb-bell models.

Fig. 8 Which half-cells share a random variable. Equal numbers mean one draw is written to both slots.

'base'

One tolerance per cell type. Every mid half-cell shares a draw, and so do the two end half-cells, which gives 14 random variables no matter how many cells the cavity has. If the two end cells are different designs they get their own variables, giving 21. This is usually what a tolerance on a drawing means.

'multicup'

Every half-cell formed independently: 14n variables for n cells. Both the irises and the equators are welds, and each averages two independent draws.

'dumbbell'

Dumb-bells formed as units, which is how these cavities are usually assembled. Each half keeps its own A, B, a, b, L and Req, but the two halves of a dumb-bell share a single iris radius, since that joint is machined rather than welded. That gives 13n + 1 variables and leaves only the equators as welds.

Build a model with perturbation_slots(), which reads the geometry to decide whether the end cells share a draw:

from cavsim2d import EllipticalCavity, perturbation_slots

cav = EllipticalCavity(3, MID, END_L, END_R, beampipe='both')
for kind in ('base', 'multicup', 'dumbbell'):
    print(kind, len(perturbation_slots(cav, kind)))

Pass split_ends=True to give the two end cells their own variables even when they are the same design. Use it when the two end cups are formed separately, so their errors are independent rather than sharing one tooling error.

Two paths through the solver

uq_config reaches the geometry by one of two paths, and they differ in what they can represent.

Simplecell path

The default. With cell_complexity set to 'simplecell', the perturbation is applied to the model’s own parameters — A_m, Req_el and so on. It is the cheaper of the two, and enough whenever one tolerance per cell type is what you mean.

Caution

Every cell takes its equator radius from Req_m on this path, so a perturbation of Req_el or Req_er has no effect on the geometry that gets solved. If Req is among your variables with cell='all', you are varying one equator radius rather than three, and the reported spread is correspondingly narrow. Use the multicell path if you need the equators to vary independently.

Multicell path

Set cell_complexity='multicell' and independent_half_cells=True. Every half-cell then carries its own parameters, the draws are independent, and each seam is welded afterwards as described above. Use this path whenever the parts are formed separately.

Which path supports which model:

Model

Simplecell path

Multicell path

base

yes

yes

multicup

no

yes

dumbbell

no

yes

The simplecell path works on parameters that describe a cell type rather than an individual part, so it can express base but nothing finer. multicup and dumbbell both need per-half-cell parameters, and therefore the multicell path.

uq_config = {
    'variables': ['A', 'B', 'a', 'b', 'Ri', 'L', 'Req'],
    'delta': [0.3] * 7,                     # absolute tolerance, mm
    'method': ['normal', 500],
    'cell_complexity': 'multicell',
    'independent_half_cells': True,
    'objectives': ['monopole:freq [MHz]', 'monopole:R/Q [Ohm]'],
    'processes': 6,
}

study.run_eigenmode({'boundary_conditions': 'mm', 'uq_config': uq_config})

Comparing models and rules

plot_uq_comparison() draws several labelled UQ result sets side by side, one panel per figure of merit. Give it uq.json paths, the directories holding them, or loaded dictionaries:

from cavsim2d import plot_uq_comparison

plot_uq_comparison({'base': 'runs/base/uq', 'multicup': 'runs/multicup/uq'},
                   nominal=cav.eigenmode.qois)

The default view plots the mean with a \(\pm 1\sigma\) error bar. That bar shows the spread of the ensemble, not the uncertainty of the mean itself, which is smaller by a factor of \(\sqrt{N}\).

To compare spreads rather than centres, pass kind='sd', which puts the standard deviation on the axis, optionally as a ratio against a named result set:

plot_uq_comparison({'MC': 'runs/mc/uq', 'Stroud3': 'runs/s3/uq'},
                   kind='sd', reference='MC')

A 20% difference in standard deviation is hard to judge by eye from the length of an error bar, so reach for kind='sd' when the question is whether two methods agree on the spread. uq_comparison_table() returns the same numbers as a DataFrame if you would rather read them than look at them.