qtt.utilities package

Contains various utilities

Submodules

qtt.utilities.debug module

qtt.utilities.debug.dumpstring(txt, tag='dump', showfile=False)[source]

Dump a text string to temperary file on disk

qtt.utilities.debug.functioncalldecorator(f, name=None)[source]

Decorate a function to log input and output arguments

qtt.utilities.debug.logInstrument(instrument)[source]

Decorate all parameters of an instrument with logging methods

qtt.utilities.imagetools module

qtt.utilities.imagetools.Vtrace(cdata, param, fig=None)[source]

Calculate position of next V-trace from fitted model .

Parameters
  • cdata – TODO

  • param – TODO

  • fit (None or integer) – figure handle.

qtt.utilities.imagetools.cleanSensingImage(im, dy=0, sigma=None, order=3, fixreversal=True, removeoutliers=False, verbose=0)[source]

Clean up image from sensing dot.

Parameters
  • im (numpy array) –

  • dy (int or str) – direction for differentiation.

  • order (int) – TODO.

  • fixreversal (bool) – TODO.

  • removeoutliers (bool) –

Returns

processed image.

Return type

ww (image)

qtt.utilities.imagetools.createCross(param, samplesize, l=20, w=2.5, lsegment=10, H=100, scale=None, lines=range(0, 4), istep=1, centermodel=True, linesegment=True, addX=True, verbose=0)[source]

Create a cross model. The parameters are [x, y, width, alpha_1, …, alpha_4, [rotation of polarization line] ] With the optional parameters psi (angle of transition line). The x, y, width are in mV. Angles in radians.

Parameters
  • param (array) – parameters of the model.

  • samplesize (int) – size of image patch in pixels.

  • l (float) – parameters of the model in mV?. lsegment is the length of the 4 addition lines w is width of lines in the model. l is not used by default.

  • w (float) – parameters of the model in mV?. lsegment is the length of the 4 addition lines w is width of lines in the model. l is not used by default.

  • lsegment (float) – parameters of the model in mV?. lsegment is the length of the 4 addition lines w is width of lines in the model. l is not used by default.

  • istep (float) – scan resolution in pixel/mV.

  • scale (None) – parameter not used any more.

  • addX (bool) – if True add polarization line to model.

  • H (float) – intensity of cross.

  • linesegment (bool) – if True create line segments instead of full lines.

Returns

return data.

Return type

modelpatch, (cc, lp, hp, ip, opr, w, H, lsegment)

qtt.utilities.imagetools.evaluateCross(param, im, verbose=0, fig=None, istep=1, istepmodel=1, linewidth=2, usemask=False, use_abs=False, w=2.5)[source]

Calculate cross matching score.

Parameters
  • param (array or list) – used by createCross to create image template.

  • im (numpy array) – TODO.

Returns

cost, patch, cdata, tuple.

See also

createCross.

qtt.utilities.imagetools.fitBackground(im, smooth=True, fig=None, order=3, verbose=1, removeoutliers=False, returndict=None)[source]

Fit smooth background to 1D or 2D image.

Parameters

im (array) – input image.

Returns

vv (array): estimated background.

qtt.utilities.imagetools.fitModel(param0, imx, verbose=1, cfig=None, ksizemv=41, istep=None, istepmodel=0.5, cb=None, use_abs=False, model_line_width=2.5)[source]

Fit model of an anti-crossing .

This is a wrapper around evaluateCross and the scipy optimization routines.

Parameters
  • param0 (array) – parameters for the anti-crossing model.

  • imx (array) – input image.

qtt.utilities.imagetools.lineSegment(im, x0, x1=None, theta=None, w=2, l=12, H=200, ml=0)[source]

Plot half-line into image .

>>> lineSegment(np.zeros( (160,240)), [60,40], [70,40], w=10, l=60)
>>> lineSegment(np.zeros( (160,240)), [60,40], theta=np.deg2rad(20), w=10, l=60)
qtt.utilities.imagetools.semiLine(im, x0, theta, w, l, H=200, dohalf=True)[source]

Plot half-line into image .

Parameters
  • im (array) –

  • x0 (array) – starting point of semi-line.

  • theta (float) – angle in radians.

  • w (float) – width.

  • l (float) – length of line segment.

  • H (float) – intensity of line segment.

  • dohalf (bool) – add smoothing?

>>> im=semiLine(np.zeros( (160,240)), [60,40], theta=np.deg2rad(20), w=10, l=60)
>>> plt.imshow(im)

qtt.utilities.json_serializer module

class qtt.utilities.json_serializer.QttSerializer[source]

Bases: qilib.utils.serialization.Serializer

qtt.utilities.json_serializer.decode_json(json_string: str)Any[source]

Decode Python object to JSON

Parameters

json_string – data to be decoded

Returns

Python object

qtt.utilities.json_serializer.decode_numpy_array(item)[source]

Decode a numpy array from JSON

qtt.utilities.json_serializer.decode_numpy_number(item)[source]

Decode a numpy scalar from JSON

qtt.utilities.json_serializer.decode_qcodes_dataset(item)[source]
qtt.utilities.json_serializer.decode_qcodes_instrument(item)[source]
qtt.utilities.json_serializer.encode_json(data: object)str[source]

Encode Python object to JSON

Parameters

data – data to be encoded

Returns

String with formatted JSON

qtt.utilities.json_serializer.encode_numpy_array(item)[source]

Encode a numpy array to JSON

qtt.utilities.json_serializer.encode_numpy_number(item)[source]

Encode a numpy scalar to JSON

qtt.utilities.json_serializer.encode_qcodes_dataset(item)[source]
qtt.utilities.json_serializer.encode_qcodes_instrument(item)[source]
qtt.utilities.json_serializer.load_json(filename: str)object[source]

Write a Python object from a JSON file

Parameters

filename (str) – filename to write data to

Returns

object loaded from JSON file

Return type

object

qtt.utilities.json_serializer.save_json(data: Any, filename: str)[source]

Write a Python object to a JSON file

Parameters
  • data (object) – object to be serialized

  • filename (str) – filename to write data to

qtt.utilities.markup module

This is markup.py - a Python module that attempts to make it easier to generate HTML/XML from a Python program in an intuitive, lightweight, customizable and pythonic way. It works with python 3 (to make mypy happy)!

The code is in the public domain.

Version: 1.10 as of 16 March 2015.

Documentation and further info is at http://markup.sourceforge.net/

Please send bug reports, feature requests, enhancement ideas or questions to nogradi at gmail dot com.

Installation: drop markup.py somewhere into your Python path.

exception qtt.utilities.markup.ArgumentError(tag)[source]

Bases: qtt.utilities.markup.MarkupError

exception qtt.utilities.markup.ClosingError(tag)[source]

Bases: qtt.utilities.markup.MarkupError

exception qtt.utilities.markup.CustomizationError[source]

Bases: qtt.utilities.markup.MarkupError

exception qtt.utilities.markup.DeprecationError(tag)[source]

Bases: qtt.utilities.markup.MarkupError

exception qtt.utilities.markup.InvalidElementError(tag, mode)[source]

Bases: qtt.utilities.markup.MarkupError

exception qtt.utilities.markup.MarkupError[source]

Bases: Exception

All our exceptions subclass this.

exception qtt.utilities.markup.ModeError(mode)[source]

Bases: qtt.utilities.markup.MarkupError

exception qtt.utilities.markup.OpeningError(tag)[source]

Bases: qtt.utilities.markup.MarkupError

class qtt.utilities.markup.dummy[source]

Bases: object

class qtt.utilities.markup.element(tag, case='lower', parent=None)[source]

Bases: object

This class handles the addition of a new element.

close()[source]

Append a closing tag unless element has only opening tag.

open(**kwargs)[source]

Append an opening tag.

render(tag, single, between, kwargs)[source]

Append the actual tags to content.

qtt.utilities.markup.escape(text, newline=False)[source]

Escape special html characters.

class qtt.utilities.markup.page(mode='strict_html', case='lower', onetags=None, twotags=None, separator='\n', class_=None)[source]

Bases: object

This is our main class representing a document. Elements are added as attributes of an instance of this class.

add(text)[source]

This is an alias to addcontent.

addcontent(text)[source]

Add some text to the main part of the document

addfooter(text)[source]

Add some text to the bottom of the document

addheader(text)[source]

Add some text to the top of the document

css(filelist)[source]

This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.

init(lang='en', css=None, metainfo=None, title=None, header=None, footer=None, charset=None, encoding=None, doctype=None, bodyattrs=None, script=None, base=None)[source]

This method is used for complete documents with appropriate doctype, encoding, title, etc information. For an HTML/XML snippet omit this method.

lang – language, usually a two character string, will appear

as <html lang=’en’> in html mode (ignored in xml mode)

css – Cascading Style Sheet filename as a string or a list of

strings for multiple css files (ignored in xml mode)

metainfo – a dictionary in the form { ‘name’:’content’ } to be inserted

into meta element(s) as <meta name=’name’ content=’content’> (ignored in xml mode)

base – set the <base href=”…”> tag in <head>

bodyattrs –a dictionary in the form { ‘key’:’value’, … } which will be added

as attributes of the <body> element as <body key=’value’ … > (ignored in xml mode)

script – dictionary containing src:type pairs, <script type=’text/type’ src=src></script>

or a list of [ ‘src1’, ‘src2’, … ] in which case ‘javascript’ is assumed for all

title – the title of the document as a string to be inserted into

a title element as <title>my title</title> (ignored in xml mode)

header – some text to be inserted right after the <body> element

(ignored in xml mode)

footer – some text to be inserted right before the </body> element

(ignored in xml mode)

charset – a string defining the character set, will be inserted into a

<meta http-equiv=’Content-Type’ content=’text/html; charset=myset’> element (ignored in xml mode)

encoding – a string defining the encoding, will be put into to first line of

the document as <?xml version=’1.0’ encoding=’myencoding’ ?> in xml mode (ignored in html mode)

doctype – the document type string, defaults to

<!DOCTYPE HTML PUBLIC ‘-//W3C//DTD HTML 4.01 Transitional//EN’> in html mode (ignored in xml mode)

metainfo(mydict)[source]

This convenience function is only useful for html. It adds meta information via the <meta> element, the argument is a dictionary of the form { ‘name’:’content’ }.

scripts(mydict)[source]

Only useful in html, mydict is dictionary of src:type pairs or a list of script sources [ ‘src1’, ‘src2’, … ] in which case ‘javascript’ is assumed for type. Will be rendered as <script type=’text/type’ src=src></script>

class qtt.utilities.markup.russell[source]

Bases: object

A dummy class that contains anything.

qtt.utilities.markup.unescape(text)[source]

Inverse of escape.

qtt.utilities.tools module

qtt.utilities.tools.addPPT_dataset(dataset, title=None, notes=None, show=False, verbose=1, paramname='measured', printformat='fancy', customfig=None, extranotes=None, **kwargs)[source]

Add slide based on dataset to current active Powerpoint presentation.

Dummy implementation.

qtt.utilities.tools.addPPTslide(title=None, fig=None, txt=None, notes=None, figsize=None, subtitle=None, maintext=None, show=False, verbose=1, activate_slide=True, ppLayout=None, extranotes=None, background_color=None, maximum_notes_size: int = 10000)[source]

Add slide to current active Powerpoint presentation.

Dummy implementation.

qtt.utilities.tools.cfigure(*args, **kwargs)[source]

Create Matplotlib figure with copy to clipboard functionality.

By pressing the ‘c’ key figure is copied to the clipboard.

qtt.utilities.tools.checkPickle(obj, verbose=0)[source]

Check whether an object can be pickled.

Parameters
  • obj (object) – object to be checked.

  • verbose (int) – verbosity (0 == silent).

Returns

True of the object can be pickled.

Return type

c (bool)

qtt.utilities.tools.clickGatevals(plot, drawmode='ro')[source]

Get gate values for all gates at clicked point in a heatmap.

Parameters
  • plot (qcodes MatPlot object) – plot of measurement data.

  • drawmode (string) – plotting style.

Returns

values of the gates at clicked point.

Return type

gatevals (dict)

qtt.utilities.tools.code_version(repository_names=None, package_names=None, get_dirty_status=False, verbose=0)[source]
Returns the python version, module version for; numpy, scipy, qupulse

and the git guid and dirty status for; qcodes, qtt, spin-projects and pycqed, if present on the machine. NOTE: currently the dirty status is not working correctly due to a bug in dulwich…

Parameters
  • repository_names ([str]) – a list with repositories, e.g. [‘qtt’, ‘qcodes’].

  • package_names ([str]) – a list with pip packages, e.g. [‘numpy’, ‘scipy’].

  • get_dirty_status (bool) – selects whether the local code has changed for the repositories.

  • verbose (int) – output level.

Returns

python, modules and git repos status.

Return type

status (dict)

qtt.utilities.tools.connect_slot(target)[source]

Create a slot by dropping signal arguments.

qtt.utilities.tools.create_figure_ppt_callback(fig, title=None, notes=None, position=(0.9, 0.925, 0.075, 0.05))[source]

Create a callback on a matplotlib figure to copy data to PowerPoint slide.

The figure is copied to PowerPoint using @ref addPPTslide.

Parameters
  • fig (int) – handle to matplotlib window.

  • title (None or str) – title for the slide.

  • notes (None or str or DataSet) – notes to add to the slide.

  • position (list) – position specified as fraction left, right, width, height.

Example

>>> plt.figure(10)
>>> plt.plot(np.arange(100), np.random.rand(100), 'o', label='input data')
>>> create_figure_ppt_callback(10, 'test')
>>> plt.show()
qtt.utilities.tools.cutoffFilter(x, thr, omega)[source]

Smooth cutoff filter.

Filter definition from: http://paulbourke.net/miscellaneous/imagefilter/

Example

>>> plt.clf()
>>> x=np.arange(0, 4, .01)
>>> _=plt.plot(x, cutoffFilter(x, 2, .25), '-r')
qtt.utilities.tools.deprecated(func)[source]

This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.

qtt.utilities.tools.diffImage(im, dy, size=None)[source]

Simple differentiation of an image.

Parameters
  • im (numpy array) – input image.

  • dy (integer or string) – method of differentiation. For an integer it is the axis of differentiation. Allowed strings are ‘x’, ‘y’, ‘xy’.

  • size (str) – describes the size e.g. ‘same’.

qtt.utilities.tools.diffImageSmooth(im, dy='x', sigma=2)[source]

Simple differentiation of an image.

Parameters
  • im (array) – input image.

  • dy (string or integer) – direction of differentiation. can be ‘x’ (0) or ‘y’ (1) or ‘xy’ (2) or ‘g’ (3).

  • sigma (float) – parameter for gaussian filter kernel.

qtt.utilities.tools.flatten(lst)[source]

Flatten a list.

Parameters

lst (list) – list to be flattened.

Returns

flattened list.

Return type

list

Example

>>> flatten([ [1,2], [3,4], [10] ])
[1, 2, 3, 4, 10]
qtt.utilities.tools.fourierHighPass(imx, nc=40, omega=4, fs=1024, fig=None)[source]

Implement simple high pass filter using the Fourier transform.

qtt.utilities.tools.freezeclass(cls)[source]

Decorator to freeze a class.

qtt.utilities.tools.get_git_versions(repos, get_dirty_status=False, verbose=0)[source]
Returns the repository head guid and dirty status and package version number if installed via pip.

The version is only returned if the repo is installed as pip package without edit mode. NOTE: currently the dirty status is not working correctly due to a bug in dulwich…

Parameters
  • repos ([str]) – a list with repositories, e.g. [‘qtt’, ‘qcodes’].

  • get_dirty_status (bool) – selects whether to use the dulwich package and collect the local code changes for the repositories.

  • verbose (int) – verbosity (0 == silent).

Retuns:

r (dict): dictionary with repo names, head guid and (optionally) dirty status for each given repository.

qtt.utilities.tools.get_module_versions(modules, verbose=0)[source]

Returns the module version of the given pip packages.

Parameters
  • modules ([str]) – a list with pip packages, e.g. [‘numpy’, ‘scipy’].

  • verbose (int) – verbosity (0 == silent).

Returns

dictionary with package names and version number for each given module.

Return type

r (dict)

qtt.utilities.tools.get_python_version(verbose=0)[source]

Returns the python version.

qtt.utilities.tools.in_ipynb()[source]
qtt.utilities.tools.is_spyder_environment()[source]

Return True if the process is running in a Spyder environment

qtt.utilities.tools.logging_context(level: int = 20, logger: Optional[logging.Logger] = None)[source]

A context manager that changes the logging level

Parameters
  • level – Logging level to set in the context

  • logger – Logger to update, if None then update the default logger

qtt.utilities.tools.monitorSizes(verbose=0)[source]

Return monitor sizes.

qtt.utilities.tools.negfloat(x)[source]

Helper function

qtt.utilities.tools.plot1D(dataset, fig=1)[source]

Simple plot function.

qtt.utilities.tools.plot2Dline(line, *args, **kwargs)[source]

Plot a 2D line in a matplotlib figure.

Parameters

line (array) – 3x1 array.

>>> plot2Dline([-1,1,0], 'b')
qtt.utilities.tools.plot_parameter(data, default_parameter='amplitude')[source]

Return parameter to be plotted.

qtt.utilities.tools.pythonVersion()[source]
qtt.utilities.tools.rdeprecated(txt=None, expire=None)[source]

This is a decorator which can be used to mark functions as deprecated.

It will result in a warning being emitted when the function is used. After the expiration data the decorator will generate an Exception.

Parameters
  • txt (str) – reason for deprecation.

  • expire (str) – date of expiration.

qtt.utilities.tools.resampleImage(im)[source]

Resample the image so it has the similar sample rates (samples/mV) in both axis.

Parameters

im (DataArray) – input image.

Returns

resampled image. setpoints (list of 2 numpy arrays): setpoint arrays from resampled image.

Return type

imr (numpy array)

qtt.utilities.tools.resetgates(gates, activegates, basevalues=None, verbose=2)[source]

Reset a set of gates to default values.

Parameters
  • gates – list of gates.

  • activegates (list or dict) – list of gates to reset.

  • basevalues (dict) – new values for the gates.

  • verbose (int) – output level.

qtt.utilities.tools.reshape_metadata(dataset, printformat='dict', add_scanjob=True, add_gates=True, add_analysis_results=True, verbose=0)[source]

Reshape the metadata of a DataSet.

Parameters
  • dataset (DataSet or qcodes.Station) – a dataset of which the metadata will be reshaped.

  • printformat (str) – can be ‘dict’ or ‘txt’,’fancy’ (text format).

  • add_scanjob (bool) – If True, then add the scanjob at the beginning of the notes.

  • add_analysis_results (bool) – If True, then add the analysis_results at the beginning of the notes.

  • add_gates (bool) – If True, then add the scanjob at the beginning of the notes.

  • verbose (int) – verbosity (0 == silent).

Returns

the reshaped metadata.

Return type

str

qtt.utilities.tools.scanTime(dd)[source]

Return date a scan was performed.

qtt.utilities.tools.set_ppt_slide_background(slide, color, verbose=0)[source]

Sets the background color of PPT slide.

Parameters
  • slide (object) – PowerPoint COM object for slide.

  • color (tuple) – tuple with RGB color specification.

  • verbose (int) – verbosity (0 == silent).

qtt.utilities.tools.setupMeasurementWindows(*args, **kwargs)[source]
qtt.utilities.tools.showImage(im, extent=None, fig=None, title=None)[source]

Show image in figure window.

Parameters
  • im (array) – TODO.

  • extent (list) – matplotlib style image extent.

  • fig (None or int) – figure window to show image.

  • title (None or str) – figure title.

qtt.utilities.tools.slopeClick(drawmode='r--', **kwargs)[source]

Calculate slope for line piece of two points clicked by user. Works with matplotlib but not with pyqtgraph. Uses the currently active figure.

Parameters

drawmode (string) – plotting style.

Returns

coordinates of the two clicked points. signedslope (float): slope of linepiece connecting the two points.

Return type

coords (2 x 2 array)

qtt.utilities.tools.smoothFourierFilter(fs=100, thr=6, omega=2, fig=None)[source]

Create smooth ND filter for Fourier high or low-pass filtering.

Example

>>> F=smoothFourierFilter([24,24], thr=6, omega=2)
>>> _=plt.figure(10); plt.clf(); _=plt.imshow(F, interpolation='nearest')
qtt.utilities.tools.static_var(varname, value)[source]

Helper function to create a static variable.

qtt.utilities.tools.stripDataset(dataset)[source]

Make sure a dataset can be pickled .

Parameters

dataset (qcodes DataSet) – TODO.

Returns

the dataset from the function argument.

Return type

dataset (qcodes DataSet)

qtt.utilities.tools.timeProgress(data)[source]

Simple progress meter, should be integrated with either loop or data object.

qtt.utilities.tools.updatePlotTitle(qplot, basetxt='Live plot')[source]

Update the plot title of a QtPlot window.

qtt.utilities.tools.update_dictionary(alldata, **kwargs)[source]

Update elements of a dictionary.

Parameters
  • alldata (dict) – dictionary to be updated.

  • kwargs (dict) – keyword arguments.

qtt.utilities.visualization module

qtt.utilities.visualization.plot_double_gaussian_fit(result_dict: dict, xdata: numpy.ndarray)None[source]

Plot a two Gaussians from a double Gaussian fit

Parameters
  • result_dict – Result of the double Gaussian fitting

  • xdata – Independent data

qtt.utilities.visualization.plot_horizontal_line(x: float, color: str = 'c', alpha: float = 0.5, label: Optional[str] = None)Any[source]

Plot vertical alignment line

Parameters
  • x – Position on horizontal axis to plot the line

  • color – Color specification of the line

  • alpha – Value to use for the transparency of the line

  • label – Label for the line

Returns

Handle to the plotted line

qtt.utilities.visualization.plot_single_traces(traces: numpy.ndarray, time: Optional[numpy.ndarray] = None, trace_color: Optional[numpy.ndarray] = None, offset: Union[None, bool, float] = None, fig: int = 1, maximum_number_of_traces: int = 40)[source]

Plot single traces with offset for separation

Parameters
  • traces – Array with single traces in the rows

  • time – Option array for time axis

  • trace_color – Specification of trace color

  • offset – Offset to use between traces. For None automatically determine the offset

  • fig – Specification of Matplotlib window

  • maximum_number_of_traces – Maximum number of traces to plot

qtt.utilities.visualization.plot_vertical_line(x: float, color: str = 'c', alpha: float = 0.5, label: Optional[str] = None)Any[source]

Plot vertical alignment line

Parameters
  • x – Position on horizontal axis to plot the line

  • color – Color specification of the line

  • alpha – Value to use for the transparency of the line

  • label – Label for the line

Returns

Handle to the plotted line