API

The two main objects that constitue the scraps framework are the Resonator and ResonatorSweep objects. Additionally, several helper functions exist for building or interacting with these objects. There is also a default function for loading in data from a text file provided, althogh you will likely need to write your own.

Fitting has been semantically separated, and you will likely want to supply your own functions for initializing parameters and fitting data, but some default fit functions are also provided. See the fit functions section of this page.

Plotting is handled by a separate set of plotting functions that take as an argument either a Resonator or ResonatorSweep object.

Resonator class

class scraps.Resonator(name, temp, pwr, freq, I, Q, sigmaI=None, sigmaQ=None)

Fit an S21 measurement of a hanger (or notch) type resonator.

Parameters:
  • name (string) – The resonator name. Does not have to be unique, but each physical resonator in the experiment should have a unique name to avoid confusion when using some of the other tools in scraps.
  • temp (float) – The temperature in (K) that the S21 measurement was taken at.
  • pwr (float) – The power (in dBm) at which the resonator was measured.
  • freq (array-like[nDataPoints]) – The frequency points at which the S21 scan was measured.
  • I (array-like[nDataPoints]) – The in-phase (or real part) of the complex S21 measurement. Units are typically volts, and I should be specified in linear units (as opposed to dB).
  • Q (array-like[nDataPoints]) – The out-of-phase (or imaginary part) of the complex S21 measurement. Units are typically volts, and I should be specified in linear units (as opposed to dB).
  • sigmaI (array-like[nDataPoints] (optional)) – An array of uncertaintly values for each data point in I. Default is None.
  • sigmaQ (array-like[nDataPoints] (optional)) – An array of uncertaintly values for each data point in Q. Default is None.
  • following attributes are automatically calculated and added during (The) –
  • initialization.
name

string – The resonator name passed at initialization.

temp

float – The temperature passed at initialization.

pwr

float – The power passed at initialization.

freq

array-like[nDataPoints] – The frequency points passed at initialization.

I

array-like[nDataPoints] – The I data points passed at initialization.

Q

array-like[nDataPoints] – The Q data points passed at initialization.

sigmaI

array-like[nDataPoints] – The sigmaI values passed at initialization.

sigmaQ

array-like[nDataPoints] – The sigmaQ values passed at initialization.

S21

array-like[nDataPoints] – The complex transmission S21 = I + 1j*Q.

phase

array-like[nDataPoints] – The raw phase phase = np.arctan2(Q, I).

uphase

array-like[nDataPoints] – The unwrapped phase is equivalent to the phase, but with jumps of 2 Pi removed.

mag

array-like[nDataPoints] – The magnitude mag = np.abs(S21) or, equivalently mag = np.sqrt(I**2 + Q**2).

hasFit

bool – Indicates whether or not Resonator.do_lmfit method has been called.

lmfit_result

lmfit.Result object – The result object created by lmfit containing all the fit information. Some of the fit information is futher extracted for convenience in the following Attributes. For an exhaustive list of the attributes of lmfit_result see the docs for lmfit. The most useful attribute of this object is lmfit_result.params, which contains the best-fit parameter values.

residualI

array-like[nDataPoints] – The residual of the fit model against the I data, wieghted by the uncertainties.

residualQ

array-like[nDataPoints] – The residual of the fit model against the Q data, wieghted by the uncertainties.

resultI

array-like[nDataPoints] – The best lmfit fit result to the fit model for I.

resultQ

array-like[nDataPoints] – The best lmfit fit result to the fit model for Q.

resultMag

array-like[nDataPoints]resultMag = np.abs(resultI + 1j*resultQ)

resultPhase

array-like[nDataPoints]resultPhase = np.arctan2(resultQ/resultI)

emcee_result

lmfit.Result object – This object is nearly identical to the lmfit_result object, but also contains the maximum-liklihood values for the varying parameters of the fit model as well as the chains returned by emcee. The most important attribute is probably emcee_result.flatchain, which can be passed directly to pygtc or corner to make a really nice GTC/Triangle/Corner plot. For an exhaustive list of the attributes of emcee_result see the docs for lmfit, specifically the section involving the lmfit implementation of emcee.

mle_vals

list of float – The maximum-liklihood estimate values of the varying parameter in the fit model as calculated by emcee. Unpacked here for convenience from emcee_result.params.

mle_labels

list of string – The parameter names of the values in mle_vals. Provided here for easy passing to pygtc or corner.

magBaseLine

array-like[nDataPoints] – The best initial guess of the baseline of the magnitude. Calculated by fitting a quadratic polynomial to the beginning and end of the magnitdue vs frequency curve.

phaseBaseLine

array-like[nDataPoints] – The best initial guess of the baseline of the phase. Calculated by fitting a line to the beginning and end of the phase vs frequency curve. This is equivalent to calculating the electrical delay in the measurement lines.

params

lmfit.Parameters object – The initial parameter guesses for fitting the S21 data. See lmfit documentation for a complete overview. To get the parameter names, call params.keys(). Default is None. Initialize params by calling Resonator.load_params. Delete params with Resonator.torch_params.

Resonator methods

.load_params()

Resonator.load_params(paramsFn, **kwargs)

Load up a lmfit Parameters object for a custom fit function.

Parameters:
  • paramsFn (method) – The paramsFn method should return a lmfit.Paramters object. This object will be passed to the fit method when do_lmfit or do_emcee is called.
  • kwargs (dict) – A dictionary of keyword arguments to pass to paramsFn.

.torch_params()

Resonator.torch_params()

Reset params attribute to None.

.do_lmfit()

Resonator.do_lmfit(fitFn, label='default', fit_type='IQ', **kwargs)

Run lmfit on an existing resonator object and update the results.

Parameters:
  • fitFn (function) – fitFn must have the signature fitFn(params, res, residual, **kwargs). If residual == True, fitFn must return a 1D list-like object of residuals with form [I residual, Q residual] where [A, B] means concatenate. Otherwise it must return the model data in the same form.
  • label (string) – A label to use as a key when storing results from the fit to the lmfit_results dict.
  • fit_type (string) – Indicates the type of fit to be run. For some types of fits, certain quantities will automatically be calculated and added to the resonator object. For instance, ‘IQ’ will cause the magnitude, phase, I, and Q as well as associated residuals to be calculated.
  • kwargs (optional keywords) – Use this to override any of the lmfit parameter initial guesses or toggle whether the paramter varys. Example: qi=1e6 is equivalent to calling Resonator.params['qi'].value = 1e6. Example: qi_vary=False will set Resonator.params['qi'].vary = False. Any parameter name can be used in this way.

.torch_lmfit()

Resonator.torch_lmfit(label='default')

Reset all the lmfit attributes to None and set hasFit = False.

Parameters:label (string (optional)) – Choose which fit to kill off.
Returns:deleted_fit – Return the fit that was deleted or None
Return type:dict or None

.do_emcee()

Resonator.do_emcee(fitFn, label='default', **kwargs)

Run the Monte-Carlo Markov Chain routine to generate samples for each parameter given a model.

Parameters:
  • fitFn (function) – fitFn must have the signature fitFn(params, res, residual, **kwargs). If residual == True, fitFn must return a 1D list-like object of residuals with form [I residual, Q residual] where [A, B] means concatenate. Otherwise it must return the model data in the same form.
  • label (string (optional)) – A label to assign to the fit results. This will be the dict key they are stored under in the emcee_results dict. Also, if label matches a label in lmfit_results, then that params object will be used to seed the emcee fit.
  • kwargs (optional keyword arguments) – These are passed through to the lmfit.Minimizer.emcee method. See the lmfit documentation for more information.

.torch_emcee()

Resonator.torch_emcee(label='default')

Set the emcee-related attributes to None and hasChain = False. :param label: Which fit to torch :type label: string (optional)

Returns:deleted_fit – The fit that is deleted is returned, or None.
Return type:dict

Resonator helper functions

These functions are designed to make it easy to use the Resonator class.

process_file()

scraps.process_file(fileName, mask=None, meta_only=False, **loadtxt_kwargs)

Load Keysight PNA file data into dict.

Parameters:
  • fileName (string) –

    Path to data. Actual name of the file should be in the format: name + '_' + pwr + '_DBM_TEMP_' + temp + '.S2P' where:

    • name: Must be ‘RES-N’ where N is any single character you like.
    • pwr: The power the resonator sees in dBm, three characters Example: ‘-25’
    • temp: The temperature of the resonator in K, five characters Example: ‘0.150’
  • mask (slice (optional)) – You can pass a slice to cut out some region of data. Example 1: mask = slice(10,-10) will cut out the first 10 and last 10 datapoints. Example 2: maks = slice(None,None,10) will resample your data and take every 10th point. Example 3: mask = slice(None, -50) will cut the last 50 points off your data.
  • meta_only (bool) – Return just the metadata from the filename (True) or all the data (False). Default is False.
  • loadtxt_kwargs (dict (optional)) – This is a pass-through to numpy.loadtxt
Returns:

Dictionary contains the following keys: ‘name’, ‘temp’, ‘pwr’, ‘freq’, ‘I’, ‘Q’. If fileName does not exist, then returns None.

Return type:

dict or None

Note

This assumes the data in the file is in three columns in the order frequency, I, Q.

This is also a terribly written function, and you really should write your own!

makeResFromData()

scraps.makeResFromData(dataDict, paramsFn=None, fitFn=None, fitFn_kwargs=None, paramsFn_kwargs=None)

Create a Resonator object from a data dictionary.

Parameters:
  • dataDict (dict) – Must have the following keys: ‘I’, ‘Q’, ‘temp’, ‘pwr’, ‘freq’, ‘name’. Optional keys are: ‘sigmaI’, ‘sigmaQ’
  • paramsFn (function (optional)) – A function that initializes and returns an lmfit parameters object for passing to fitFn.
  • fitFn (function (optional)) – If a fit function is passed, an lmfit minimization will be done automatically.
  • fitFn_kwargs (dict (optional)) – A dict of keyword arguments passed to fitFn.
  • paramsFn_kwargs (dict (optional)) – A dict of keyword arguments passed to paramsFn.
Returns:

res – A Resonator object or None if there is an error loading the data.

Return type:

Resonator object or None

makeResList()

scraps.makeResList(fileFunc, dataPath, resName, **fileFunc_kwargs)

Create a list of resonator objects from a directory of dataDict

Parameters:
  • fileFunc (function) – A function that converts a single data file into a dictionary. The resulting dictionary must have the following keys: ‘I’, ‘Q’, ‘temp’, ‘pwr’, ‘freq’, ‘name’, and may have the following ptional keys: ‘sigmaI’, ‘sigmaQ’
  • dataPath (string) – Path to the directory containing the data files that will be processed by fileFunc.
  • resName (string) – The name of your resonator. This can be anything, but it is useful to use the same name for every data file that comes from the same physical resonator.
  • fileFunc_kwargs (dict) – Keyword arguments to pass through to the fileFunc

indexResList()

scraps.indexResList(resList, temp=None, pwr=None, **kwargs)

Index resList by temp and pwr.

Parameters:
  • resList (list-like) – resList is a list of scraps.Resonator objects
  • temp (numeric) – The temperature of a single Resonator object.
  • pwr (int) – The power of a single Resonator object
  • itemp (boolean (optional)) – Switch to determine whether lookup uses temp or itemp (rounded value of temp). Default is False.
Returns:

index – Index is the index of the Resonator in resList or a list of indices of all matches if only pwr or only temp is specified.

Return type:

int or list

Notes

indexResList does not check for duplicates and will return the first match.

ResonatorSweep class

The ResonatorSweep class inherits python’s dict class. Each key of the dict corresponds to a pandas.DataFrame of data. Because of this, you can add your own custom derived data sets by simply assigning them to a dict entry. As an example:

#Start with a ResonatorSweep object called resSweep that contains a
#key called 'f0', which is the resonant frequency of many different
#resonators. Maybe what you want to plot though, is the reduced
#frequency df = (f-fr)/fr where fr is some reference frequency

#Choose a reference frequency from the existing data
fr = resSweep['f0'].iloc[0,0]

#Pick a descriptive key to describe the data
key = 'df_over_fr'

#Calculate the derived quantity and add it to the ResonatorSweep
resSweep[key] = (resSweep['f0']-fr)/fr

#And now you can plot it by just passing that key when you use the
#plotting tools. If you want errorbars, you'll need to calculate those
#for the derived quantity as well, and store them in: key + '_sigma'.
class scraps.ResonatorSweep(resList, **kwargs)

Dictionary object with custom __init__ method.

Parameters:

resList (list-like) – A list of scraps.Resonator objects. Each object must have the attribute hasFit == True.

Keyword Arguments:
 
  • label (string (optional)) – Selects which set of fit data to build the ResonatorSweep from. Default is ‘default’.
  • index (string{'raw', 'round', 'block'} (optional)) – Selects which method to use for indexing.
  • roundto (int (optional)) – Number to round temperature index to in mK. Default is 5.
tvec

array-like[nUniqeTemps] – Index of temperature values, one for each unique temperature.

pvec

array-like[nUniqePowers] – Index of powers values, one for each unique power.

smartindex

string – Indicates the method of formatting temperature values in tvec. ‘raw’ means to take temperature values as they are, ‘round’ means to round to the neareast X mK, where X is set by roundTo, ‘block’ means to figure out which temperature values are nominally the same and set each block of those temperatures to the same value.

rountTo

float – The number of mK to round to when smartIndex == 'round'.

lmfit_results

dict – A dictionary containing the fit results for different data by key. Initially empty, results are added by calling ResonatorSweep.do_lmfit.

emcee_results

dict – A dictionary containing the MCMC results for different data by key. Initially empty, results are added by calling ResonatorSweep.do_emcee.

lmfit_joint_results

dict – If multiple data sets are fit simultaneously via ResonatorSweep.do_lmfit, the results will appear in this attribute by key, where ``key = ‘key1+key2’ == ‘key2+key1’.

emcee_joint_results

dict – If multiple data sets are fit simultaneously via ResonatorSweep.do_emcee, the results will appear in this attribute by key, where ``key = ‘key1+key2’.

Note

The following keys are added to the self dict:

‘temps’ : pandas.DataFrame
The temperature of each resonator in the sweep.
‘fmin’ : pandas.DataFrame
The minimum value of the magnitude vs frequency curve after subtraction of the best-guess baseline.
‘listIndex’ : pandas.DataFrame
The sweep objects are built from a list of pyres.Resonator objects; this is the index of the original list for each data value in the sweep.

If the do_lmfit method has been run, these keys are also added:

‘chisq’ : pandas.DataFrame
The Chi-squared value of each fit in the sweep.
‘redchi’ : pandas.DataFrame
The reduced Chi-squared value of each fit in the sweep.
‘feval’ : pandas.DataFrame
The number of function evaluations for each fit in the sweep.
paramNames : pandas.DataFrame
There is a key for each parameter value in the Resonator.params attribute.
paramNames + ‘_sigma’ : pandas.DataFrame
There is a key for the uncertainty on each paramter value returned by the fit. Key name is paramName + ‘_sigma’

If the do_emcee method has been run, these keys are also added:

paramNames + ‘_mle’ : pandas.DataFrame
The maximum-liklihood estimate from the MCMC sampling.
paramNames + ‘_mc’ : pandas.DataFrame
The 50th percentile value of the posterior distribution from MCMC sampling.
paramNames + ‘_sigma_plus_mc’ : pandas.DataFrame
The plus errorbar on the MCMC data. Calculated as the difference between the 84th percentile value and the 50th percentile value.
paramNames + ‘_sigma_minus_mc’ : pandas.DataFrame
The minus errorbar on the MCMC data. Calculated as the difference between the 50th percentile value and the 16th percentile value.

ResonatorSweep methods

.do_lmfit()

ResonatorSweep.do_lmfit(fit_keys, models_list, params_list, model_kwargs=None, param_kwargs=None, **kwargs)

Run simulatneous fits on the temp/pwr data for several parameters. Results are stored in either the lmfit_results or lmfit_joint_results attribute depending on whether one or multiple keys are passed to fit_keys.

Parameters:
  • fit_keys (list-like) – A list of keys that correspond to existing data. Any combination of keys from self.keys()` is acceptable, but duplicates are not permitted.
  • models_list (list-like) – A list of fit functions, one per key in fit_keys. Function must return a residual of the form: residual = (model-data)/sigma where residual, model, and data are all numpy arrays. Function signature is model_func(params, temps, powers, data=None, sigmas=None). If data==None the functions must return the model calculated at temps and powers. The model functions should also gracefully handle np.NaN or None values.
  • params_list (list-like) – A list of lmfit.Parameters objects, one for each key in fit_keys. Parameters sharing the same name will be merged so that the fit is truly joint. Alternately, a list of functions that return lmfit.Parameters objects may be passed. In this case, one should use param_kwargs to pass any needed options to the functions.
  • model_kwargs (list-like (optional)) – A list of dict objects to pass to the individual model functions as kwargs. None is also an acceptable entry if there are no kwargs to pass to a model function. Default is None.
  • param_kwargs (list-like (optional)) – A list of dict objects to pass to the individual params functions as kwargs. None is also an acceptable entry if there are no kwargs to pass to a model function. Default is None.
  • lmfit_kwargs (dict (optional)) – Keyword arguments to pass options to the fitter
  • kwargs (dict (optional)) – Supported keyword arugments are ‘min_temp’, ‘max_temp’, ‘min_pwr’, and ‘max_pwr’. These set limits on which data to fit.
Keyword Arguments:
 
  • min_temp (numeric) – Lower limit of temperature to fit. Default is 0.
  • max_temp (numeric) – Upper limit of temerature to fit. Default is infinity.
  • min_pwr (numeric) – Lower limit of temperature to fit. Default is -infinity.
  • max_pwr (numeric) – Upper limit of temperature to fit. Default is infinity.
  • raw_data (string {'lmfit', 'emcee', 'mle'}) – Whether to use the values returned by lmfit, or the values returned by the emcee fitter (either the 50th percentile or the maximum liklihood). This also chooses which set of errorbars to use: either those from the lmfit covariance matrix, or those from the 16th and 84th percentiles of the posterior probablility distribution. Default is ‘lmfit’.

Note

If the fits are succesful, the resulting fit data (ie the best fit surface) will be added to the self dict in the form of a pandas.DataFrame under the following keys:

For a joint fit (len(fit_keys) > 1):

'lmfit_joint_'+joint_key+'_'+key for each key in fit_keys

For a single fit (len(fit_keys) == 1):

'lmfit_'+key

.do_emcee()

ResonatorSweep.do_emcee(fit_keys, models_list, params_list=None, model_kwargs=None, param_kwargs=None, emcee_kwargs=None, **kwargs)

Run simulatneous MCMC sampling on the temp/pwr data for several parameters. Results are stored in either the emcee_results or emcee_joint_results attribute depending on whether one or multiple keys are passed to fit_keys.

Parameters:
  • fit_keys (list-like) – A list of keys that correspond to existing data. Any combination of keys from self.keys()` is acceptable, but duplicates are not permitted.
  • models_list (list-like) – A list of fit functions, one per key in fit_keys. Function must return a residual of the form: residual = (model-data)/sigma where residual, model, and data are all numpy arrays. Function signature is model_func(params, temps, powers, data=None, sigmas=None). If data==None the functions must return the model calculated at temps and powers. The model functions should also gracefully handle np.NaN or None values.
  • params_list (list-like) – A list of lmfit.Parameters objects, one for each key in fit_keys. Parameters sharing the same name will be merged so that the fit is truly joint. Alternately, a list of functions that return lmfit.Parameters objects may be passed. In this case, one should use param_kwargs to pass any needed options to the functions. Default is None and is equivalent to setting use_lmfit_params = True.
  • model_kwargs (list-like (optional)) – A list of dict objects to pass to the individual model functions as kwargs. None is also an acceptable entry if there are no kwargs to pass to a model function. Default is None.
  • param_kwargs (list-like (optional)) – A list of dict objects to pass to the individual params functions as kwargs. None is also an acceptable entry if there are no kwargs to pass to a model function. Default is None.
  • emcee_kwargs (dict (optional)) – Keyword arguments to pass options to the fitter
Keyword Arguments:
 
  • min_temp (numeric) – Lower limit of temperature to fit. Default is 0.
  • max_temp (numeric) – Upper limit of temerature to fit. Default is infinity.
  • min_pwr (numeric) – Lower limit of temperature to fit. Default is -infinity.
  • max_pwr (numeric) – Upper limit of temperature to fit. Default is infinity.
  • use_lmfit_params (bool) – Whether or not to use the resulting best-fit lmfit.Paramters object that resulted from calling ResonatorSweep.do_lmfit() as the starting value for the MCMC sampler. Default is True.
  • raw_data (string {'lmfit', 'emcee', 'mle'}) – Whether to use the values returned by lmfit, or the values returned by the emcee fitter (either the 50th percentile or the maximum liklihood). This also chooses which set of errorbars to use: either those from the lmfit covariance matrix, or those from the 16th and 84th percentiles of the posterior probablility distribution. Default is ‘lmfit’.

Note

If the fits are succesful, the resulting fit data (ie the best fit surface) will be added to the self dict in the form of a pandas.DataFrame under the following keys:

For a joint fit (len(fit_keys) > 1):

'emcee_joint_'+joint_key+'_'+key for each key in fit_keys

For a single fit (len(fit_keys) == 1):

'emcee_'+key

Plotting tools

plotResListData()

scraps.plotResListData(resList, plot_types=['IQ'], **kwargs)

Plot resonator data and fits.

Parameters:
  • resList (list-like) – A list of pyres.Resonator objects. A single Resonator object can be passed, as long as it is in a list.
  • plot_types (list, optional) –

    A list of plots to create, each one specified by a string. Possible plot types are:

    • ’IQ’: Plots the real part of the transmission (I) vs the imaginary
      part (Q). This is the default plot.
    • ’rIQ’: Plots the residual of I vs the residual of Q. This plot is
      only available if the do_lmfit method of each Resonator object has been called. The I and Q residuals are normalized by the uncertainty of the I and Q data respectively. If this is not explicitly supplied, it is calculated by taking the standard deviation of the first 10 data points.
    • ’LinMag’: Plots the magnitude of the tranmission in Volts vs
      frequency.
    • ’LogMag’: Plots the magnitude of the transmission in dB vs frequency.
      LogMag = 20*np.log10(LinMag).
    • ’rMag’: Plots the difference of LinMag and the best-fit magnitude vs
      frequency. This plot is only available if the do_lmfit method of each Resonator object has been called.
    • ’Phase’: Plots the phase of the transmision vs frequency.
      Phase = np.arctan2(Q, I).
    • ’rPhase’: Plots the difference of Phase and the best-fit phase vs
      frequency. This plot is only available if the do_lmfit method of each Resonator object has been called.
    • ’uPhase’: Plots the unwrapped phase vs frequency.
      uPhase = np.unwrap(Phase).
    • ’ruPhase’: Plots the difference of uPhase and the unwrapped best-fit
      phase vs frequency. This plot is only available if the do_lmfit method of each Resonator object has been called.
    • ’I’: Plots the real part of the transmission vs frequency.
    • ’rI’: Plots the residual of I vs frequency. The residual is weighted
      by the uncertainty in I. This plot is only available if the do_lmfit method of each Resonator object has been called.
    • ’Q’: Plots the imaginary part of the transmission vs frequency.
    • ’rQ’: Plots the residual of Q vs frequency. The residual is weighted
      by the uncertainty in Q. This plot is only available if the do_lmfit method of each Resonator object has been called.
Keyword Arguments:
 
  • plot_fits (list-like, optional) – A list of boolean flags, one for each plot type specified. Determines whether or not to overplot the best fit on the data. This is only effective if the do_lmfit method of each Resonator object has been called. Default is all False.
  • powers (list-like, optional) – A list of power values to plot. Default is to plot all of the unique powers that exist in the list of Resonator objects.
  • max_pwr (float) – An upper bound on the powers to plot. Applies to values passed to powers also.
  • min_pwr (float) – A lower bound on the powers to plot. Applies to values passed to powers also.
  • temps (list-like, optional) – A list of temperature values to plot. Default is to plot all of the unique temperatures that exist in the list of Resonator obejcts.
  • max_temp (float) – An upper bound on the temperatures to plot. Applies to values passed to temps also.
  • min_temp (float) – A lower bound on the temperatures to plot. Applies to values passed to temps also.
  • use_itemps ({False, True}, optional) – If a ResonatorSweep object has been generated from the resList it may have added the itemp attrubute to each ResonatorObject in the list. Specifying use_itemps = True will force the plotting routine to use those tempeartures.
  • freq_units ({'GHz', 'Hz', 'kHz', 'MHz', 'THz'}, optional) – The units for the frequency axis, if it exists. Defaul is ‘GHz’.
  • detrend_phase ({False, True}, optional) – Whether or not to remove a linear trend from the Phase data. A typical reason for a steep linear offset in the phase is an uncorrected electrical delay due to long transmission lines.
  • num_cols (int, optional) – The number of columns to include in the grid of subplots. Default is 1.
  • fig_size (int, optional) – The size of an individual subplot in inches. Default is 3.
  • force_square ({False, True}, optional) – Whether or not to force each subplot axis to be perfectly square.
  • show_colorbar ({True, False}, optional) – Whether or not to add a colorbar to the right edge of the figure. The colorbar will correspond to the limits of the colored data. Default is True.
  • color_by ({'temps', 'pwrs'}, optional) – If multiple temperatures and multiple powers are passed, this selects which variable will set the color of the plots. Default is ‘temps’.
  • color_map (str, optional) – The name of any colormap returned by calling matplotlib.pyplot.colormaps() is a valid option. Default is ‘coolwarm’.
  • waterfall (numeric, optional) – The value used to space out LogMag vs frequency plots. Currently only available for LogMag. Default is 0.
  • plot_kwargs (dict, optional) – A dict of keyword arguments to pass through to the individual plots. Attempting to set ‘color’ will result in an error.
  • fit_kwargs (dict, optional) – A dict of keyword arguments to pass through to the fit plots. Default is a dashed black line.
Returns:

figS – A matplotlib.pyplot figure object.

Return type:

matplotlib.pyplot.figure

plotResSweepParamsVsX()

scraps.plotResSweepParamsVsX(resSweep, plot_keys=None, ignore_keys=None, xvals='temperature', **kwargs)

Plot parameter data vs temperature from a ResonatorSweep object.

Parameters:
  • resSweep (scraps.ResonatorSweep object or list of objects) – The object containing the data you want to look at. It is also possible to pass a list of these objects and it will combine them into one plot.
  • plot_keys (list-like (optional)) – A list of strings corresponding to avaiable plot data. The available keys depend on your parameter definitions and may be found by executing print(resSweep.keys()). Some keys may point to empty (NaN) objects. Default is to plot all of the keys that exist. If you pass plot_keys you may not pass ignore_ignore keys.
  • ignore_keys (list-like (optional)) – A list of strings corresponding to plots that should not be made. This is useful if you want to plot most of the avaialble data, but ignore one or two sets of data. Default is None. If you pass ignore_keys you may not pass plot_keys.
  • xvals (string) – What axis you want to plot by. Deafult is ‘temperature’. Could also be ‘power’. Future releases may include other options.
  • color_by (string) – Set this to ‘index’ if you pass multiple res sweeps and want to color them by index.
Keyword Arguments:
 
  • plot_labels (list-like) – A list of strings to use to label the y-axes of the plots. There must be one for each plot requested. None is acceptable for any position in the list and will default to using the key as the label. Default is to use the key as the label.
  • unit_multipliers (list-like) – A list of numbers to multiply against the y-axes data. There must be one for each plot requested. None is acceptable for any position in the list and will default to 1. Default is 1.
  • fitter (string {'lmfit', 'emcee'}) – Which fit data to use when overlaying best fits. Default is ‘lmfit’.
  • num_cols (int) – The number of columns to create in the plot grid. Default is 1. The number of rows will be calculated based on num_cols and the number of requested plots.
  • powers (list) – List of powers to plot. Default is to plot all available. If xvals is ‘power’ this kwarg is ignored.
  • temperatures (list) – List of temperatures to plot. Default is to plot all available. If xvals is ‘temperature’ this kwarg is ignored.
  • xmax (numeric) – Don’t plot any xvals above this value. Default is infinity.
  • xmin (numeric) – Don’t plot any xvals below this value. Default is 0 for temperature and -infinity for power.
  • errorbars ({None, 'lmfit', 'emcee'}) – Add error bars to the data. Pulls from either the least-squares or the MCMC fits. Default is None.
  • fig_size (numeric) – Size in inches for each plot in the figure.
  • color_map (string) – Specifies the colormap to use. Any value in matplotlib.pyplot.colormaps() is a valid option.
  • show_colorbar ({True, False}, optional) – Whether or not to add a colorbar to the right edge of the figure. The colorbar will correspond to the limits of the colored data. Default is True.
  • force_square (bool) – Whether or not to force each subplot to have perfectly square axes.
  • plot_kwargs (dict or list of dicts) – Dict of keyword args to pass through to the plotting function. Default is {‘linestyle’:’–’, label=’Power X dB’}. If errorbars is not None, then default linestyle is {‘linestyle’:’o’}. Attempting to set ‘color’ or ‘yerr’ will result in an exception. Use the color_map and errorbars keywords to set those. If you passed in a list of objects to resSweep, then you can also pass a list of plot_kwargs, one for each sweep object.

plotResSweepParamsVsTemp()

Note: this has been deprecated in favor of plotResSweepParamsVsX .. autofunction :: scraps.plotResSweepParamsVsTemp

plotResSweepParamsVsPwr()

Note: this has been deprecated in favor of plotResSweepParamsVsX .. autofunction :: scraps.plotResSweepParamsVsPwr

plotResSweep3D()

scraps.plotResSweep3D(resSweep, plot_keys, **kwargs)

Make 3D surface or mesh plots of any key in the ResonatorSweep object as functions of temperature and power.

Parameters:
  • resSweep (ResonatorSweep object) – A pyres.ResonatorSweep object containing all of the data to be plotted.
  • plot_keys (list-like) – List of strings where each string is a key corresponding to a plot that should be made. For a list of acccetable keys, run print resSweep.keys().
Keyword Arguments:
 
  • min_temp (numeric (optional)) – The minimum temperature to plot. Defaults to min(temperatures).
  • max_temp (numeric (optional)) – The maximum temperature to plot. Defaults to max(temperatres).
  • min_pwr (numeric (optional)) – The minimum power to plot. Defaults to min(powers).
  • max_pwr (numeric (optional)) – The maximum power to plot. Defauts to max(powers).
  • unit_multipliers (list (optional)) – Values to scale the z-axis by. Default is 1. len(unit_multipliers) == len(plot_keys).
  • plot_labels (list (optional)) – Labels for the z-axis. Default is the plot key. len(plot_labels) == len(plot_keys).
  • num_cols (int (optional)) – The number of columns in the resulting plot grid. Default is 1.
  • fig_size (numeric (optional)) – The size of an individual subplot in inches. Default is 3.
  • plot_lmfits (bool (optional)) – Whether or not to show a fit. The fit must exist! Default is False. Deprecated! Use plot_fits.
  • plot_fits (list (optional)) – A list of fit keys to plot. Fits must exist for all parameters specified in plot_keys. Example: plot_fits = [‘lmfit’, ‘lmfit_joint_f0+qi’] will plot the lmfit results for each key in plot_keys, and the joint fit results from the ‘f0+qi’ fit for each key in plot_keys. If only one fit result is desired, a single string may be passed instead of a list.
  • plot_kwargs (dict (optional)) – A dictionary of keyword arguments to pass the plotting function. Default is None.

Note

This function is currently a little buggy, because I can’t figure out how to intelligently adjust the label positions, sizes, etc to deal with large numbers in the ticks. The current workaround is to pick a large fig_size (so far anything larger than 5 seems ok) and then scale the plot as needed in some other application.

You can also use something like the following to adjust the ticks on a specific axis:

figX.axes[0].tick_params(axis='z', pad=8)
figX.axes[0].zaxis.labelpad = 13

Fit models

Each fit model consists of two functions. One that returns a lmfit.Parameters object, and one that takes parameters and data and returns a residual.

I and Q vs frequency

The built-in fit model is called complx_IQ.py and is located in the fitsS21 folder. It has two functions, one that calculates best guess values for each of the ten fit parameters, and one that applies those guesses to the data and calculates the residual.

cmplxIQ_params()

scraps.cmplxIQ_params(res, **kwargs)

Initialize fitting parameters used by the cmplxIQ_fit function.

Parameters:

res (scraps.Resonator object) – The object you want to calculate parameter guesses for.

Keyword Arguments:
 
  • fit_quadratic_phase (bool) – This determines whether the phase baseline is fit by a line or a quadratic function. Default is False for fitting only a line.
  • hardware (string {'VNA', 'mixer'}) – This determines whether or not the Ioffset and Qoffset parameters are allowed to vary by default.
  • use_filter (bool) – Whether or not to use a smoothing filter on the data before calculating parameter guesses. This is especially useful for very noisy data where the noise spikes might be lower than the resonance minimum.
  • filter_win_length (int) – The length of the window used in the Savitsky-Golay filter that smoothes the data when use_filter == True. Default is 0.1 * len(data) or 3, whichever is larger.
Returns:

params

Return type:

lmfit.Parameters object

cmplxIQ_fit()

scraps.cmplxIQ_fit(paramsVec, res, residual=True, **kwargs)

Return complex S21 resonance model or, if data is specified, a residual.

Parameters:
  • params (list-like) – A an lmfit.Parameters object containing (df, f0, qc, qi, gain0, gain1, gain2, pgain0, pgain1, pgain2)
  • res (scraps.Resonator object) – A Resonator object.
  • residual (bool) – Whether to return a residual (True) or to return the model calcuated at the frequencies present in res (False).
Keyword Arguments:
 
  • freqs (list-like) – A list of frequency points at which to calculate the model. Only used if residual=False
  • remove_baseline (bool) – Whether or not to remove the baseline during calculation (i.e. ignore pgain and gain polynomials). Default is False.
  • only_baseline (bool) – Whether or not to calculate and return only the baseline. Default is False.
Returns:

model or (model-data)/eps – If residual=True is specified, the return is the residuals weighted by the uncertainties. If residual=False, the return is the model values calculated at the frequency points. The returned array is in the form I + Q or residualI + residualQ.

Return type:

numpy.array

Two-level system (TLS) and Mattis-Bardeen effect (BMD)

This model is for fitting frequency shifts and internal quality factors as functions of temperature and input power. It is a very simple model, employs a lot of simplifying assumptions, and should be regarded with extreme skepticism. However, it qualitatively describes the dominant behavior of most resonators and so is useful as an example.

There is no accompanying parameter-generation function. See Example 3 for usage.

qi_tlsAndMBT()

scraps.fitsSweep.qi_tlsAndMBT(params, temps, powers, data=None, eps=None, **kwargs)

A model of internal quality factor vs temperature and power, weighted by uncertainties.

Parameters:
  • params (lmfit.Parameters object) – Parameters must include ['Fd', 'q0', 'f0', 'alpha', 'delta0'].
  • temps (numpy.Array) – Array of temperature values to evaluate model at. May be 2D.
  • powers (numpy.Array) – Array of power values to evaluate model at. May be 2D.
  • data (numpy.Array) – Data values to compare to model. May also be None, in which case function returns model.
  • eps (numpy.Array) – Uncertianties with which to weight residual. May also be None, in which case residual is unwieghted.
Returns:

residual – The weighted or unweighted vector of residuals if data is passed. Otherwise, it returns the model.

Return type:

numpy.Array

Note

The following constraint must be satisfied:

all(numpy.shape(x) == numpy.shape(data) for x in [temps, powers, eps])

It is almost certain that this model does NOT apply to your device as the assumptions it makes are highly constraining and ignore several material parameters. It is included here more as an example for how to write a model than anything else, and it does at least qualitatively describe the behavior of most superconducting resonators.

This model is taken from J. Gao’s Caltech dissertation (2008) and the below equations are from that work.

(2.54) gives for MBD: 1/Q(T)-1/Q(0) = alpha * R(T)/X(0)

(5.72) and (5.65) give for TLS: 1/Q(T)-1/Q(0) = Fd*tanh(hf/2kT)/sqrt(1+P/P0)

R(T)/X(0) calculated from (2.80), (2.89), and (2.90), using the deltaBCS function in this module for returning gap as a function of temperature.

f0_tlsAndMBT()

scraps.fitsSweep.f0_tlsAndMBT(params, temps, powers, data=None, eps=None, **kwargs)

A model of frequency shift vs temperature and power, weighted by uncertainties.

Parameters:
  • params (lmfit.Parameters object) – Parameters must include ['Fd', 'df', 'fRef', 'alpha', 'delta0'].
  • temps (numpy.Array) – Array of temperature values to evaluate model at. May be 2D.
  • powers (numpy.Array) – Array of power values to evaluate model at. May be 2D.
  • data (numpy.Array) – Data values to compare to model. May also be None, in which case function returns model.
  • eps (numpy.Array) – Uncertianties with which to weight residual. May also be None, in which case residual is unwieghted.
Returns:

residual – The weighted or unweighted vector of residuals if data is passed. Otherwise, it returns the model.

Return type:

numpy.Array

Note

The following constraint must be satisfied:

all(numpy.shape(x) == numpy.shape(data) for x in [temps, powers, eps])

It is almost certain that this model does NOT apply to your device as the assumptions it makes are highly constraining and ignore several material parameters. It is included here more as an example for how to write a model than anything else, and it does at least qualitatively describe the behavior of most superconducting resonators.

This model is taken from J. Gao’s Caltech dissertation (2008) and the below equations are from that work.

(2.54) gives for MBD (f(T)-f(0))/f(0) = -alpha*0.5*(X(T)-X(0))/X(0)

(5.71) gives for TLS “” = Fd/pi * (usual TLS expression from Phillips)

(X(T)-X(0))/X(0) calculated from (2.80), (2.89), and (2.90), using the deltaBCS function in this module for returning gap as a function of temperature.