multipactor_test module
Define an object to store and treat data from pick-ups.
Todo
Allow to trim data (remove noisy useless data at end of exp)
Todo
name of pick ups in animation
Todo
histograms for mp voltages? Maybe then add a gaussian fit, then we can determine the 3sigma multipactor limits?
Todo
to_ignore, to_exclude arguments should have more consistent names.
- exception MissingInstrumentError[source]
Bases:
ValueErrorCustom exception raised when an
Instrumentis missing.- add_note()
Exception.add_note(note) – add a note to the exception
- args
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class MultipactorTest(filepath, config, freq_mhz=None, swr=1.0, info='', trigger=None, sep=',', trigger_policy='keep_all', index_col='Sample index', is_raw=False, create_virtual_instruments=True, remove_metadata_columns=False, **kwargs)[source]
Bases:
objectHolds a mp test with several probes.
- Parameters:
filepath (
Path)swr (
float, default:1.0)info (
str, default:'')sep (
str, default:',')trigger_policy (
Literal['keep_all','trim','average','first','last','max','min'], default:'keep_all')index_col (
str, default:'Sample index')is_raw (
bool, default:False)create_virtual_instruments (
bool, default:True)remove_metadata_columns (
bool, default:False)
- 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)
- power_step_set: PowerStepSet | None
PowerStepSetthis test was built from, if any. Enables interactive plots.
- add_post_treater(post_treater, instrument_class=<class 'multipac_testbench.instruments.instrument.Instrument'>, only_pick_up_which_name_is=())[source]
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)
- remove_post_treater(post_treater=None, index=None, instrument_class=<class 'multipac_testbench.instruments.instrument.Instrument'>, only_pick_up_which_name_is=())[source]
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 overindex.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:
- add_instrument(instrument, measurement_point)[source]
Manually add an instrument.
- Parameters:
instrument (
Instrument)measurement_point (
str|IMeasurementPoint)
- Return type:
- property instruments: list[Instrument]
Get all stored instruments.
- _set_x_data(xdata, predicate=None, exclude=())[source]
Set the data that will be used for x-axis.
- Parameters:
xdata (
ABCMeta|None) – Class of an instrument, or None (in this case, use default index).exclude (
Sequence[str], default:()) – Name of instruments to exclude. Deprecated, preferpredicate.predicate (
Callable[[ABCMeta|Instrument|str],bool] |None, default:None) –Instrumentfiltering function.
- Return type:
- 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)[source]
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 usingpredicate.predicate (
Callable[[ABCMeta|Instrument|str],bool] |None, default:None) –Instrumentfiltering function.column_names (
str|list[str], default:'') – To override the default column names. This is used in particular with the methodTestCampaign.sweet_plot(), whenall_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 areTrueat the same row index, aValueErroris raised.raw (
bool, default:False) – To get raw data (generally acquisition voltage) instead of physical data.kwargs – Other keyword arguments.
- Return type:
- 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_namesis provided, it overrides the giveny_columns.color – Dictionary linking column names in
df_to_plotto HTML colors. Used to keep the same color between different instruments at the samePickUp.
- determine_thresholds(multipac_detector, instrument_class, power_growth_array_kw=None, threshold_reducer=None, threshold_predicate=None, instrument_predicate=None, **kwargs)[source]
Determine lower and upper multipactor thresholds.
- Parameters:
multipac_detector (
Callable[[ndarray[tuple[Any,...],dtype[double]]],ndarray[tuple[Any,...],dtype[bool]]]) – Function that takes in thedataof anInstrumentand returns an array, where True means multipactor and False no multipactor.instrument_class (
ABCMeta) – Type of instrument on whichmultipac_detectorshould be applied.power_growth_array_kw (
dict[str,Any] |None, default:None) – Keyword arguments passed toPowerSetpoint.growth_array().threshold_reducer (
Literal['any','all'] |None, default:None) – If provided, we consider that multipactor appears when one detectingInstrumentdetected it ("any"), or only when all detectingInstrumentmeasured it ("all").threshold_predicate (
ThresholdFilter|None, default:None) – Function filtering the thresholds. Applied afterthreshold_reducer.instrument_predicate (
Callable[[ABCMeta|Instrument|str],bool] |None, default:None) –Instrumentfiltering function.
- Return type:
- Returns:
Object holding all lower and upper thresholds, detected by
multipac_detectorapplied on every instance ofinstrument_class.
- _power_growth_array(growth_array_kw=None)[source]
Determine where power grows, decreases, is stable.
- _instruments_by_class(instrument_class, measurement_points=None, instruments_to_ignore=())[source]
Get all instruments of desired class from
measurement_points.But remove the instruments to ignore.
- Parameters:
instrument_class (
ABCMeta) – Class of the desired instruments.measurement_points (
Sequence[IMeasurementPoint] |None, default:None) – The measurement points from which you want the instruments. The default is None, in which case we look into everyIMeasurementPointattribute of self.instruments_to_ignore (
Sequence[Instrument|str], default:()) – TheInstrumentor instrument names you do not want.
- Return type:
- Returns:
All the instruments matching the required conditions.
- _instruments_by_name(instrument_names)[source]
Get all instruments of desired name from
measurement_points.- Parameters:
- Return type:
- Returns:
All the instruments matching the required conditions.
- get_measurement_points(names=None, to_exclude=())[source]
Get all or some measurement points.
- Parameters:
names (
Sequence[str] |None, default:None) – If given, only theIMeasurementPointwhich name is innameswill be returned.to_exclude (
Sequence[str|IMeasurementPoint], default:()) – List of objects or objects names to exclude from returned list.
- Return type:
- Returns:
The desired objects.
- get_measurement_point(name=None, to_exclude=())[source]
Get all or some measurement points. Ensure there is only one.
- Parameters:
name (
str|None, default:None) – If given, only theIMeasurementPointwhich name is innameswill be returned.to_exclude (
Sequence[str|IMeasurementPoint], default:()) – List of objects or objects names to exclude from returned list.
- Return type:
- Returns:
The desired object.
- get_instruments(instruments_id=None, predicate=None, measurement_points_to_exclude=(), instruments_to_ignore=())[source]
Get all instruments matching
instrument_id.- Parameters:
instruments_id (
ABCMeta|Sequence[ABCMeta] |Sequence[str] |Sequence[Instrument] |None, default:None) – IdentifiesInstrument. Can be one or severalInstrumenttypes (egCurrentProbe),Instrumentinstances orInstrument.name.predicate (
Callable[[ABCMeta|Instrument|str],bool] |None, default:None) –Instrumentfiltering function.measurement_points_to_exclude (
Collection[IMeasurementPoint] |Collection[str], default:()) – Exclude some measurement points from the filtering. Deprecated, prefer usingpredicate.instruments_to_ignore (
ABCMeta|Sequence[ABCMeta] |Sequence[str] |Sequence[Instrument], default:()) – Instruments to exclude from filtering. Deprecated, prefer usingpredicate.
- Return type:
- Returns:
List of desired instruments.
- get_instrument(instrument_id, raise_missing_error=True, predicate=None, measurement_points_to_exclude=(), instruments_to_ignore=())[source]
- 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:
instrument_id (
ABCMeta|Instrument|str|Sequence[ABCMeta] |Sequence[str] |Sequence[Instrument]) – Identifies one (or several)Instrument. If severalInstrumentinstances can be returned, you must specifypredicateto filter all instances but one.raise_missing_error (
bool, default:True) – If an error should be raised when no correspondingInstrumentis found.predicate (
Callable[[ABCMeta|Instrument|str],bool] |None, default:None) –Instrumentfiltering function.to_exclude – Exclude some measurement points from the filtering. Deprecated, prefer using
predicate.instruments_to_ignore (
ABCMeta|Sequence[ABCMeta] |Sequence[str] |Sequence[Instrument], default:()) – Instruments to exclude from filtering. Deprecated, prefer usingpredicate.measurement_points_to_exclude (
Collection[IMeasurementPoint] |Collection[str], default:())
- Returns:
A single
Instrumentinstance. If several instances were found, we raise a warning but still return anInstrument(the first one; may change between executions!).- Raises:
MissingInstrumentError – When no matching
Instrumentwas found, ifraise_missing_erroris set to True.
- get_instruments_at(position, instrument_id=None, tol=1e-10, **kwargs)[source]
Return all instruments located at a given position.
- Parameters:
position (
float) – The position in meter to match. If it isnp.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:
- Returns:
Matching instruments.
- reconstruct_voltage_along_line(name, probes_to_ignore=())[source]
Reconstruct the voltage profile from the e field probes.
- Parameters:
name (
str)probes_to_ignore (
Sequence[str|FieldProbe], default:())
- Return type:
- 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)[source]
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:
threshold_set (
ThresholdSet|Mapping[MultipactorTest,ThresholdSet]) – Object telling where multipactor happens.ydata (
ABCMeta, default:<class 'abc.ABCMeta'>) – Type of instrument of which you want data in y-axis. In general, you will wantFieldProbeorForwardPower.use_theoretical_swr (
bool, default:False) – To insert theoretical SWR defined byMultipactorTest.swrinstead of the value taken fromSWRVirtualInstrument.d_cm (
float, default:1.0955) – System gap in \(\mathrm{cm}\).fd_col (
str, default:'$f\\\\cdot d~[\\\\mathrm{MHz cm}]') – Name of the column that will hold the \(f\cdot d\) product.
- Return type:
- Returns:
Holds value of
ydatainstruments at lower and upper thresholds, as well as the \(f\cdot d\) values.
- data_for_somersalo_scaling_law(threshold_set, use_theoretical_r=False, **kwargs)[source]
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
ThresholdSetcreated withthreshold_reducer="all".- Parameters:
threshold_set (
ThresholdSet|dict[MultipactorTest,ThresholdSet]) – Object telling where multipactor happens.use_theoretical_r (
bool, default:False) – If set to True, we use the \(R\) corresponding to the user-defined \(SWR\).kwargs – Other keyword arguments passed to
ThresholdSet.data_at_thresholds().
- Return type:
- Returns:
Holds the forward power at the last upper and lower thresholds, as well as corresponding \(R\) values (same time steps).
- data_for_perez_scaling_law(threshold_set, xdata, use_theoretical_xdata=False, **kwargs)[source]
Get the data necessary to plot the Perez scaling law.
In particular, the last measured voltage thresholds, and \(SWR\) or \(R\) according to
xdataat corresponding time steps.Use it with local multipactor, ie avoid
ThresholdSetcreated with athreshold_reducer.- Parameters:
threshold_set (
ThresholdSet|dict[MultipactorTest,ThresholdSet]) – Object telling where multipactor happens.xdata (
ABCMeta) – Desired type ofxdata, generallySWRorReflectionCoefficient.use_theoretical_xdata (
bool, default:False) – To use theoreticalxdata. Works only for reflection coefficient and standing wave ratio.kwargs – Currently unused.
- 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.
- 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, raw=False, **kwargs)[source]
Plot
ydataversusxdata.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 oneydatais allowed and number ofxandyinstruments 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 lasttailpoints. Useful to select only the last power cycle.xlabel (
str, default:'') – Label of x 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 everyInstrumentdata.global_instruments (
bool, default:False) – If instruments not position-specific (egForwardPower) 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 methodTestCampaign.sweet_plot()whenall_on_same_plot=True.test_color (
str|None, default:None) – Color used byTestCampaign.sweet_plot()whenall_on_same_plot=True. It overrides theInstrumentcolor and is used to discriminate everyMultipactorTestfrom another.png_path (
Path|None, default:None) – If specified, save the figure atpng_path.csv_path (
Path|None, default:None) – If specified, save the data used to produce the plot incsv_path.csv_kwargs (
dict|None, default:None) – Keyword arguments passed toplot.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 areTrueat the same row index, aValueErroris raised.drop_repeated_x (
bool, default:False) – If True, remove consecutive rows with identical x values.raw (
bool, default:False) – If True, plots raw data instead of physical data.**kwargs – Other keyword arguments passed to
pandas.DataFrame.plot(),_set_y_data(),create_df_to_plot(),set_labels().
- Return type:
- Returns:
axes – Objects holding the plot.
df_to_plot – DataFrame holding the data that is plotted.
- interactive_sweet_plot(*ydata, xdata=None, **kwargs)[source]
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 callsPowerStep.sweet_plot()on the associatedPowerStep.Note
Only works when
xdataisNone(x-axis = Sample index) and when this object was created viaPowerStepSet.to_multipactor_test(), which setspower_step_set. Falls back to a plainsweet_plot()otherwise.- Parameters:
*ydata (
ABCMeta) – Passed tosweet_plot()and to the per-stepPowerStep.sweet_plot()on click.xdata (
ABCMeta|None, default:None) – Passed tosweet_plot(). Must beNonefor interactivity.**kwargs – Passed to
sweet_plot().
- Return type:
- Returns:
axes – Objects holding the overview plot.
df_to_plot – DataFrame holding the data that is plotted.
- _add_thresholds_on_axes(*ydata, dic_axes, threshold_set, plot_extrema, global_instruments=False, global_multipactor=False)[source]
Mark position of lower and upper thresholds on pre-existing plot.
- Parameters:
*ydata (
ABCMeta) – Type(s) ofInstrument(s) to plot.dic_axes (
dict[ABCMeta,Axes]) – Links every type ofInstrumentwith theAxesit 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 ininstrumentsshould be included.global_multipactor (
bool, default:False) – If non-local multipactor should be plotted.
- Return type:
- Returns:
Instruments data at thresholds, as plotted in the figure.
- 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)[source]
Plot
ydatainstances data at multipactor threshold.When
ydataisForwardPowerorFieldProbe, 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 withForwardPowerorFieldProbe.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) – IfInstrumentat different positions should be kept on the same plot.plot_extrema (
bool, default:False) – Addto_plotvalues at the power minima and maxima. Makes most sense with voltage/power instruments. Resulting plot may be very crowded ifsame_figure == True.global_instruments (
bool, default:False) – If instruments not position-specific (egForwardPower) 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 thematplotlib.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 thepandas.DataFrame.to_csv()method.axes (
Axes|None, default:None) – Axes to re-use. Needssample_plot=True.plot_kwargs (
dict[str,Any] |None, default:None) – Kwargs passed the plot function.test_color (
str|None, default:None) – Color used byTestCampaign.plot_thresholds()whenall_on_same_plot=True. It overrides theInstrumentcolor and is used to discriminate everyMultipactorTestfrom 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.
- 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)[source]
Represent measured signals with probe position.
Todo
last_framebadly handled: gif will be as long as if thelast_framewas not set, except that images won’t be updated after the last frame.- Parameters:
- Return type:
- _prepare_animation_fig(to_plot, measurement_points_to_exclude=(), instruments_to_ignore_for_limits=(), instruments_to_ignore=(), **fig_kw)[source]
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:
- Returns:
fig – Figure holding the axes.
axes_instruments – Links the instruments to plot with the Axes they should be plotted on.
- _plot_instruments_single_time_step(step_idx, keep_one_frame_over, axes_instruments, artists=None, last_frame=None)[source]
Plot all instruments signal at proper axe and time step.
- scatter_instruments_data(instruments_to_plot, measurement_points_to_exclude=(), thresholds_set=None, png_path=None, **fig_kw)[source]
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…
- statistics(thresholds_set, instrument_class, global_instruments=False, global_multipactor=False, csv_path=None, csv_kwargs=None, **kwargs)[source]
Compute some statistics on
instrument_classat 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 (egForwardPower) 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 incsv_path.csv_kwargs (
dict[str,Any] |None, default:None) – Keyword arguments passed toplot.save_dataframe().kwargs – Other keyword arguments passed to
ThresholdSet.data_at_thresholds().
- Return type:
- group_columns_by_detector_position(df, test, instrument_nature=None)[source]
Group threshold dataframe headers by position of detecting instrument.
- Parameters:
df (
DataFrame) – Dataframe as returned byThresholdSet.data_at_thresholds().test (
MultipactorTest) – Object containing all theInstrument.instrument_nature (
ABCMeta|None, default:None) – If provided, we remove instruments which type is notinstrument_nature.
- Return type:
- Returns:
Mapping of every detecting instrument position in
df, to the list of detecting instruments at the same position.