power_step module

Define an object corresponding to a power step file.

_DEFAULT_SPECIAL_REDUCERS: dict[str | type[Instrument], Callable[[ndarray[tuple[Any, ...], dtype[_ScalarT]]], float]] = {   <class 'multipac_testbench.instruments.power.Power'>: <function take_maximum at 0x7466cbddee80>,     <class 'multipac_testbench.instruments.penning.Penning'>: <function take_maximum at 0x7466cbddee80>}

For Instrument for which taking the median over the trigger window does not make sense. For Penning, this is because the signal takes time to rise and the main info lies after the trigger window. For Power, this is because the signals are delayed wrt to the trigger window.

class PowerStep(filepath, config, sample_index, freq_mhz=None, swr=1.0, info='', sep='\\t', index_col='Index', out_index_col='Sample index', comment='#', create_virtual_instruments=True, **kwargs)[source]

Bases: MultipactorTest

This object is basically a MultipactorTest. But for one power step.

Parameters:
  • filepath (Path)

  • config (dict[str, Any] | str | Path)

  • sample_index (int)

  • freq_mhz (float | None, default: None)

  • swr (float, default: 1.0)

  • info (str, default: '')

  • sep (str, default: '\\t')

  • index_col (str, default: 'Index')

  • out_index_col (str, default: 'Sample index')

  • comment (str, default: '#')

  • create_virtual_instruments (bool, default: True)

log_messages_to_suppress = [   'points were removed in R calculation, where reflected power was ',     "column_header = 'NI9205_dBm' not present in provided file. Skipping",     'Applied trigger_policy = ',     'Adding a post_treater to ',     'not present in provided file. Skipping associated instrument']

Log messages to suppress, as they are very noisy in this context.

_sample_index

Position of the step in the complete MultipactorTest

to_single_values(generic_reducer=None, special_reducers=None, operate_on_raw_data=True)[source]

Convert arrays of Instrument values to single floats.

Parameters:
  • generic_reducer (Callable[[ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]], float] | None, default: None) – Function converting array to float. The default is take_median() applied to the pulse window [pre_trigger, pre_trigger + trigger] as read from TestConditions. Falls back to take_maximum() on the full array if those values are unavailable, and logs an error.

  • special_reducers (Mapping[str | type[Instrument], Callable[[ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]], float]] | None, default: None) – Different functions to apply to specific columns. Keys can be an instrument name string (e.g. "NI9205_Penning1") for a single instrument, or an instrument class (e.g. Penning) to apply to all instruments of that type. String keys take priority over class keys. Defaults to {Penning: take_maximum, Power: take_maximum}. If you really do not want to use defaults, provide an empty dict.

Return type:

Series

Note

As the synchronism of the watt-metre is bad, measured powers are shifted wrt NI9205 measurements. So you will generally want to take the maximum of NI9205_Power1 and NI9205_Power2 columns, which is handled by the default special_reducers.

Parameters:

operate_on_raw_data (bool, default: True)

sweet_plot(*ydata, xdata=None, exclude=(), tail=None, xlabel='', ylabel='', grid=True, title='', threshold_set=None, global_instruments=False, global_multipactor=False, column_names='', test_color=None, png_path=None, png_kwargs=None, csv_path=None, csv_kwargs=None, axes=None, masks=None, drop_repeated_x=False, pre_trig=None, trig=None, **kwargs)[source]

Plot ydata versus xdata.

Todo

Kwargs mixed up between the different methods.

Parameters:
  • *ydata (ABCMeta) – Class of the instruments to plot.

  • xdata (ABCMeta | None, default: None) – Class of instrument to use as x-data. If there is several instruments which have this class, only one ydata is allowed and number of x and y instruments must match. The default is None, in which case data is plotted vs sample index.

  • exclude (Sequence[str], default: ()) – Name of the instruments that you do not want to see plotted.

  • tail (int | None, default: None) – Specify this to only plot the last tail points. Useful to select only the last power cycle.

  • xlabel (str, default: '') – Label of x axis.

  • ylabel (str | Iterable, default: '') – Label of y axis.

  • grid (bool, default: True) – To show the grid.

  • title (str | list[str], default: '') – Title of the plot or of the subplots.

  • threshold_set (ThresholdSet | None, default: None) – If provided, mark lower (circle) and upper (star) thresholds on top of every Instrument data.

  • global_instruments (bool, default: False) – If instruments not position-specific (eg ForwardPower) should have their thresholds plotted.

  • global_multipactor (bool, default: False) – If multipactor not position-specific (eg thresholds created by merging several other multipactor arrays) should have their thresholds plotted.

  • column_names (str | list[str], default: '') – To override the default column names. This is used in particular with the method TestCampaign.sweet_plot() when all_on_same_plot=True.

  • test_color (str | None, default: None) – Color used by TestCampaign.sweet_plot() when all_on_same_plot=True. It overrides the Instrument color and is used to discriminate every MultipactorTest from another.

  • png_path (Path | None, default: None) – If specified, save the figure at png_path.

  • csv_path (Path | None, default: None) – If specified, save the data used to produce the plot in csv_path.

  • csv_kwargs (dict | None, default: None) – Keyword arguments passed to plot.save_dataframe().

  • masks (dict[str, ndarray[tuple[Any, ...], dtype[bool]]] | None, default: None) – A dictionary where each key is a suffix used to label the split columns, and each value is a boolean mask of the same length as the input data. Keys must start with two underscores (__) to enable consistent column naming and compatibility with downstream styling logic (e.g., grouping lines by base column in plots). If multiple masks are True at the same row index, a ValueError is raised.

  • drop_repeated_x (bool, default: False) – If True, remove consecutive rows with identical x values.

  • pre_trig (int | None, default: None) – Index at which the pulse should start. If both pre_trig and trig are provided, the times with power on are highlighted in red.

  • trig (int | None, default: None) – Pulse duration in indexes. If both pre_trig and trig are provided, the times with power on are highlighted in red.

  • **kwargs – Other keyword arguments passed to pandas.DataFrame.plot(), _set_y_data(), create_df_to_plot(), set_labels().

  • png_kwargs (dict | None, default: None)

  • axes (list[Axes] | None, default: None)

Return type:

tuple[list[Axes], DataFrame]

Returns:

  • axes – Objects holding the plot.

  • df_to_plot – DataFrame holding the data that is plotted.

property trigger: int | None

Trigger sample index. Shorthand for test_conditions.trigger.

_add_thresholds_on_axes(*ydata, dic_axes, threshold_set, plot_extrema, global_instruments=False, global_multipactor=False)

Mark position of lower and upper thresholds on pre-existing plot.

Parameters:
  • *ydata (ABCMeta) – Type(s) of Instrument(s) to plot.

  • dic_axes (dict[ABCMeta, Axes]) – Links every type of Instrument with the Axes it must be plotted on.

  • threshold_set (ThresholdSet) – Defines the position of the multipator thresholds of the current multipactor test.

  • plot_extrema (bool) – Add instrument to plot values at the power minima and maxima. Makes most sense with voltage/power instruments.

  • global_instruments (bool, default: False) – If global instruments in instruments should be included.

  • global_multipactor (bool, default: False) – If non-local multipactor should be plotted.

Return type:

DataFrame

Returns:

Instruments data at thresholds, as plotted in the figure.

_instruments_by_class(instrument_class, measurement_points=None, instruments_to_ignore=())

Get all instruments of desired class from measurement_points.

But remove the instruments to ignore.

Parameters:
Return type:

list[Instrument]

Returns:

All the instruments matching the required conditions.

_instruments_by_name(instrument_names)

Get all instruments of desired name from measurement_points.

Parameters:
  • instrument_name – Name of the desired instruments.

  • instrument_names (Sequence[str])

Return type:

list[Instrument]

Returns:

All the instruments matching the required conditions.

_plot_instruments_single_time_step(step_idx, keep_one_frame_over, axes_instruments, artists=None, last_frame=None)

Plot all instruments signal at proper axe and time step.

Parameters:
Return type:

Sequence[Artist] | None

_power_growth_array(growth_array_kw=None)

Determine where power grows, decreases, is stable.

Parameters:

growth_array_kw (dict[str, Any] | None, default: None)

Return type:

ndarray[tuple[Any, ...], dtype[double]]

_prepare_animation_fig(to_plot, measurement_points_to_exclude=(), instruments_to_ignore_for_limits=(), instruments_to_ignore=(), **fig_kw)

Create the figure and axes for the animation.

Parameters:
  • to_plot (Sequence[ABCMeta]) – Classes of instruments you want to see.

  • measurement_points_to_exclude (tuple[str, ...], default: ()) – Measurement points that should not appear.

  • instruments_to_ignore_for_limits (tuple[str, ...], default: ()) – Instruments to plot, but that can go off limits.

  • instruments_to_ignore (Sequence[Instrument | str], default: ()) – Instruments that will not even be plotted.

  • fig_kw – Other keyword arguments for Figure.

Return type:

tuple[Figure, dict[Axes, list[Instrument]]]

Returns:

  • fig – Figure holding the axes.

  • axes_instruments – Links the instruments to plot with the Axes they should be plotted on.

_set_x_data(xdata, predicate=None, exclude=())

Set the data that will be used for x-axis.

Parameters:
Return type:

tuple[list[Series], list[str] | None]

Returns:

  • list[pd.Series] – Contains the data used for x axis.

  • list[str] | None – Name of the column(s) used for x axis.

_set_y_data(data_to_plot, *ydata, exclude=(), predicate=None, column_names='', masks=None, raw=False, **kwargs)

Set the y-data that will be plotted.

Parameters:
  • data_to_plot (list[Series | DataFrame]) – List already containing the x-data, or nothing if the index is to be used.

  • *ydata (ABCMeta) – The class of the instruments to plot.

  • exclude (Sequence[str], default: ()) – Name of some instruments to exclude. Deprecated, prefer using predicate.

  • predicate (Callable[[ABCMeta | Instrument | str], bool] | None, default: None) – Instrument filtering function.

  • column_names (str | list[str], default: '') – To override the default column names. This is used in particular with the method TestCampaign.sweet_plot(), when all_on_same_plot=True.

  • masks (dict[str, ndarray[tuple[Any, ...], dtype[bool]]] | None, default: None) – A dictionary where each key is a suffix used to label the split columns, and each value is a boolean mask of the same length as the input data. Keys must start with two underscores (__) to enable consistent column naming and compatibility with downstream styling logic (e.g., grouping lines by base column in plots). If multiple masks are True at the same row index, a ValueError is raised.

  • raw (bool, default: False) – To get raw data (generally acquisition voltage) instead of physical data.

  • kwargs – Other keyword arguments.

Return type:

tuple[list[Series], list[list[str]], dict[str, str]]

Returns:

  • data_to_plot – List containing all the series that will be plotted.

  • y_columns – Contains, for every subplot, the name of the columns to plot. If column_names is provided, it overrides the given y_columns.

  • color – Dictionary linking column names in df_to_plot to HTML colors. Used to keep the same color between different instruments at the same PickUp.

add_instrument(instrument, measurement_point)

Manually add an instrument.

Parameters:
Return type:

None

add_post_treater(post_treater, instrument_class=<class 'multipac_testbench.instruments.instrument.Instrument'>, only_pick_up_which_name_is=())

Add post-treatment functions to instruments.

Todo

Find out why following lines result in strange plot linestyles.

measurement_points: list[IMeasurementPoint] = self.pick_ups
if self.global_diagnostics is not None:
    measurement_points.append(self.global_diagnostics)
Parameters:
Return type:

None

animate_instruments_vs_position(instruments_to_plot, gif_path=None, fps=50, keep_one_frame_over=1, interval=None, only_first_frame=False, last_frame=None, **fig_kw)

Represent measured signals with probe position.

Todo

last_frame badly handled: gif will be as long as if the last_frame was not set, except that images won’t be updated after the last frame.

Parameters:
  • instruments_to_plot (Sequence[ABCMeta])

  • gif_path (Path | None, default: None)

  • fps (int, default: 50)

  • keep_one_frame_over (int, default: 1)

  • interval (int | None, default: None)

  • only_first_frame (bool, default: False)

  • last_frame (int | None, default: None)

Return type:

FuncAnimation | list[Axes]

data_for_perez_scaling_law(threshold_set, xdata, use_theoretical_xdata=False, **kwargs)

Get the data necessary to plot the Perez scaling law.

In particular, the last measured voltage thresholds, and \(SWR\) or \(R\) according to xdata at corresponding time steps.

Use it with local multipactor, ie avoid ThresholdSet created with a threshold_reducer.

Parameters:
Return type:

tuple[DataFrame, dict[str, tuple[float, float, float] | None]]

Returns:

  • df – Holds the last voltage thresholds, as well as corresponding \(R\) or \(SWR\) values. Column headers look like: "NI9205_E4 @ upper threshold (according to NI9205_MP4l)".

  • label_to_color – Maps every y-column of the dataframe to a specific color.

data_for_somersalo_scaling_law(threshold_set, use_theoretical_r=False, **kwargs)

Get the data necessary to plot the Somersalo scaling law.

In particular, the last detected power thresholds, and the reflection coefficient \(R\) at the corresponding time steps. Lower and upper thresholds are returned, even if Somersalo scaling law does not concern the upper threshold.

Use it with global multipactor, ie with ThresholdSet created with threshold_reducer="all".

Parameters:
Return type:

DataFrame

Returns:

Holds the forward power at the last upper and lower thresholds, as well as corresponding \(R\) values (same time steps).

data_for_susceptibility(threshold_set, ydata=<class 'abc.ABCMeta'>, use_theoretical_swr=False, d_cm=1.0955, fd_col='$f\\\\cdot d~[\\\\mathrm{MHz cm}]', **kwargs)

Get the data required to create the susceptibility plot.

In particular, voltage or power thresholds according to ydata, SWR, and \(f\cdot d\) product.

Parameters:
Return type:

DataFrame

Returns:

Holds value of ydata instruments at lower and upper thresholds, as well as the \(f\cdot d\) values.

determine_thresholds(multipac_detector, instrument_class, power_growth_array_kw=None, threshold_reducer=None, threshold_predicate=None, instrument_predicate=None, **kwargs)

Determine lower and upper multipactor thresholds.

Parameters:
Return type:

ThresholdSet

Returns:

Object holding all lower and upper thresholds, detected by multipac_detector applied on every instance of instrument_class.

property freq_mhz: float

Frequency in \(\mathrm{MHz}\).

get_instrument(instrument_id, raise_missing_error=True, predicate=None, measurement_points_to_exclude=(), instruments_to_ignore=())
Overloads:
  • self, instrument_id (INSTRUMENT_ID | INSTRUMENTS_ID), raise_missing_error (Literal[False]), predicate (INSTRUMENT_FILTER | None), measurement_points_to_exclude (MEASUREMENT_POINTS_ID), instruments_to_ignore (INSTRUMENTS_ID) → Instrument | None

  • self, instrument_id (INSTRUMENT_ID | INSTRUMENTS_ID), raise_missing_error (Literal[True]), predicate (INSTRUMENT_FILTER | None), measurement_points_to_exclude (MEASUREMENT_POINTS_ID), instruments_to_ignore (INSTRUMENTS_ID) → Instrument

Get a single instrument matching instrument_id.

Parameters:
Returns:

A single Instrument instance. If several instances were found, we raise a warning but still return an Instrument (the first one; may change between executions!).

Raises:

MissingInstrumentError – When no matching Instrument was found, if raise_missing_error is set to True.

get_instruments(instruments_id=None, predicate=None, measurement_points_to_exclude=(), instruments_to_ignore=())

Get all instruments matching instrument_id.

Parameters:
Return type:

list[Instrument]

Returns:

List of desired instruments.

get_instruments_at(position, instrument_id=None, tol=1e-10, **kwargs)

Return all instruments located at a given position.

Parameters:
  • position (float) – The position in meter to match. If it is np.nan, we return global instruments.

  • instrument_id (ABCMeta | str | Instrument | None, default: None) – Filter instruments by class, name, or instance. If not provided, we look for all stored instruments.

  • tol (float, default: 1e-10) – Absolute tolerance used when comparing positions.

  • **kwargs – Passed to MultipactorTest.get_instruments().

Return type:

list[Instrument]

Returns:

Matching instruments.

get_measurement_point(name=None, to_exclude=())

Get all or some measurement points. Ensure there is only one.

Parameters:
Return type:

IMeasurementPoint

Returns:

The desired object.

get_measurement_points(names=None, to_exclude=())

Get all or some measurement points.

Parameters:
Return type:

Sequence[IMeasurementPoint]

Returns:

The desired objects.

property info: str

Human-readable label for this test.

property instruments: list[Instrument]

Get all stored instruments.

interactive_sweet_plot(*ydata, xdata=None, **kwargs)

Like sweet_plot, but clicking opens the corresponding PowerStep plot.

Clicking on the figure takes the x-position of the click, resolves the nearest sample_index, and calls PowerStep.sweet_plot() on the associated PowerStep.

Note

Only works when xdata is None (x-axis = Sample index) and when this object was created via PowerStepSet.to_multipactor_test(), which sets power_step_set. Falls back to a plain sweet_plot() otherwise.

Parameters:
Return type:

tuple[list[Axes], DataFrame]

Returns:

  • axes – Objects holding the overview plot.

  • df_to_plot – DataFrame holding the data that is plotted.

output_filepath(out_folder, extension)

Create consistent path for output files.

Parameters:
Return type:

Path

plot_thresholds(ydata, threshold_set, xdata=None, title='', same_figure=True, plot_extrema=False, global_instruments=False, global_multipactor=False, png_path=None, png_kwargs=None, csv_path=None, csv_kwargs=None, axes=None, plot_kwargs=None, test_color=None, **kwargs)

Plot ydata instances data at multipactor threshold.

When ydata is ForwardPower or FieldProbe, the figure represents the evolution of the power/voltage multpactor threshold during the test. But this method can be used with any instrument type.

Todo

Add a way to fit exponential (?) law on the thresholds. Will need to change the x-axis.

Parameters:
  • ydata (ABCMeta) – Class of instrument to plot. Makes most sense with ForwardPower or FieldProbe.

  • threshold_set (ThresholdSet | dict[MultipactorTest, ThresholdSet]) – Object containing the indexes of thresholds, as well as the position of multipactor.

  • xdata (ABCMeta | None, default: None) – Class of instrument to use as x-data.

  • title (str, default: '') – If provided, overrides automatic title.

  • same_figure (bool, default: True) – If Instrument at different positions should be kept on the same plot.

  • plot_extrema (bool, default: False) – Add to_plot values at the power minima and maxima. Makes most sense with voltage/power instruments. Resulting plot may be very crowded if same_figure == True.

  • global_instruments (bool, default: False) – If instruments not position-specific (eg ForwardPower) should be plotted.

  • global_multipactor (bool, default: False) – If multipactor not position-specific (eg thresholds created by merging several other multipactor arrays) should be plotted.

  • png_path (Path | None, default: None) – If provided, figure will be saved there.

  • png_kwargs (dict[str, Any] | None, default: None) – Keyword arguments for the matplotlib.figure.Figure.savefig() method.

  • csv_path (Path | None, default: None) – If provided, plotted data will be saved there.

  • csv_kwargs (dict | None, default: None) – Keyword arguments for the pandas.DataFrame.to_csv() method.

  • axes (Axes | None, default: None) – Axes to re-use. Needs sample_plot=True.

  • plot_kwargs (dict[str, Any] | None, default: None) – Kwargs passed the plot function.

  • test_color (str | None, default: None) – Color used by TestCampaign.plot_thresholds() when all_on_same_plot=True. It overrides the Instrument color and is used to discriminate every MultipactorTest from another.

Return type:

tuple[Axes | ndarray[tuple[Any, ...], dtype[Axes]], DataFrame]

Returns:

  • axes – Hold plotted axes.

  • df_thresholds – The data used to produce the plot.

reconstruct_voltage_along_line(name, probes_to_ignore=())

Reconstruct the voltage profile from the e field probes.

Parameters:
Return type:

None

remove_post_treater(post_treater=None, index=None, instrument_class=<class 'multipac_testbench.instruments.instrument.Instrument'>, only_pick_up_which_name_is=())

Remove post-treatment functions from instruments.

Parameters:
  • only_pick_up_which_name_is (Collection[str], default: ()) – To select only some measurement points by their name.

  • post_treater (Callable[[ndarray[tuple[Any, ...], dtype[double]]], ndarray[tuple[Any, ...], dtype[double]]] | None, default: None) – Post-treater to remove. Has priority over index.

  • index (int | None, default: None) – Index of post-treater to remove.

  • instrument_class (ABCMeta, default: <class 'multipac_testbench.instruments.instrument.Instrument'>) – Type of instruments concerned by removing.

Return type:

None

scatter_instruments_data(instruments_to_plot, measurement_points_to_exclude=(), thresholds_set=None, png_path=None, **fig_kw)

Plot the data measured by instruments.

This plot results in important amount of points. It becomes interesting when setting different colors for multipactor/no multipactor points and can help see trends.

Todo

Also show from global diagnostic

Todo

User should be able to select: reconstructed or measured electric field.

Todo

Fix this. Or not? This is not the most explicit way to display data…

Parameters:
Return type:

tuple[Figure, list[Axes]]

statistics(thresholds_set, instrument_class, global_instruments=False, global_multipactor=False, csv_path=None, csv_kwargs=None, **kwargs)

Compute some statistics on instrument_class at thresholds.

Parameters:
  • thresholds_set (ThresholdSet) – Calculated multipactor thresholds.

  • instrument_class (ABCMeta) – Class of instruments under study.

  • global_instruments (bool, default: False) – If instruments not position-specific (eg ForwardPower) should have their thresholds plotted.

  • global_multipactor (bool, default: False) – If multipactor not position-specific (eg thresholds created by merging several other multipactor arrays) should have their thresholds plotted.

  • csv_path (Path | None, default: None) – If specified, save the data used to produce the plot in csv_path.

  • csv_kwargs (dict[str, Any] | None, default: None) – Keyword arguments passed to plot.save_dataframe().

  • kwargs – Other keyword arguments passed to ThresholdSet.data_at_thresholds().

Return type:

DataFrame

property swr: float

Expected Standing Wave Ratio.

power_step_set: PowerStepSet | None

PowerStepSet this test was built from, if any. Enables interactive plots.

pick_ups

Where all diagnostics at a specific pick-up are defined (e.g. current probe)

global_diagnostics

Where all diagnostics which are not a specific position are stored (e.g. forward/reflected power)

class PowerStepSet(folder, config, freq_mhz=None, swr=1.0, info='', sep='\\t', index_col='Index', out_index_col='Sample index', file_recognizer=None, comment='#', create_virtual_instruments=True, are_raw=True, **kwargs)[source]

Bases: object

Define all the files constituting a MultipactorTest.

Parameters:
  • folder (Path)

  • config (dict[str, Any] | str | Path)

  • freq_mhz (float | None, default: None)

  • swr (float, default: 1.0)

  • info (str, default: '')

  • sep (str, default: '\\t')

  • index_col (str, default: 'Index')

  • out_index_col (str, default: 'Sample index')

  • file_recognizer (Callable[[Path], bool] | None, default: None)

  • comment (str, default: '#')

  • create_virtual_instruments (bool, default: True)

  • are_raw (bool, default: True)

_config: dict[str, Any]
get_power_step(sample_index)[source]

Return the PowerStep with the given sample_index.

Parameters:

sample_index (int) – The index as stored in PowerStep._sample_index.

Raises:

KeyError – If no PowerStep with that index exists.

Return type:

PowerStep

to_multipactor_test_file(csv_path, reducer=None, index_col='Sample index', special_reducers=None, sep=',', **kwargs)[source]

Create a file that can be loaded by MultipactorTest.

Parameters:
Return type:

None

to_multipactor_test(csv_path, reducer=None, special_reducers=None, **kwargs)[source]

Write the summary CSV and load it as a MultipactorTest.

Convenience wrapper around to_multipactor_test_file() that additionally back-links the returned MultipactorTest to this PowerStepSet, enabling MultipactorTest.interactive_sweet_plot().

Parameters:
Return type:

MultipactorTest

Returns:

A fully-constructed MultipactorTest with power_step_set set to self.