{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# QCoDeS Example with Standford Research SR86x Lock-in Amplifier with Buffered Readout\n", "\n", "This notebook provides a code example of usage of the driver for Standford Research SR86x lock-in amplifier. Special attention is given to reading the captured data from the lock-in's internal buffer.\n", "\n", "This notebook covers several capturing modes including starting capture at trigger, and capturing one sample per trigger. For the purpose of this example, a Tektronix AWG5208 will be used to send trigger signals. One can also use `qcodes.instrument_drivers.QuTech.IVVI` with its `trigger` method, or else." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setting up infrastructure for the examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Imports" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "%matplotlib notebook\n", "\n", "# Useful utilities\n", "import time\n", "import matplotlib.pyplot as plt \n", "import numpy\n", "from pprint import pprint # for pretty printing lists and dictionaries\n", "\n", "# QCoDeS\n", "import qcodes\n", "\n", "# Drivers\n", "from qcodes.instrument_drivers.stanford_research.SR860 \\\n", " import SR860 # the lock-in amplifier\n", "from qcodes.instrument_drivers.tektronix.AWG5208 \\\n", " import AWG5208 # used for sending trigger signals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Initialize the driver" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Connected to: Stanford_Research_Systems SR860 (serial:003223, firmware:V1.47) in 0.25s\n" ] } ], "source": [ "lockin = SR860(\"lockin\", \"GPIB0::4::INSTR\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basics of reading values from the lock-in\n", "\n", "Lock-in amplifier measures a number of values. The most frequently used ones are available in the driver directly as QCODES parameters:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "X = 3.1690581181e-07\n", "Y = 2.9734803775e-07\n", "R = 4.2155235747e-07\n", "P = 45.936515808\n" ] } ], "source": [ "print(f'X = { lockin.X() }')\n", "print(f'Y = { lockin.Y() }')\n", "print(f'R = { lockin.R() }')\n", "print(f'P = { lockin.P() }')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Actually, the full list of values (or 'parameters', not to be confused with QCODES parameters) that the lock-in amplifier measures is available in the following dictionary (refer to the page 132 of the instrument's manual for more information):" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['X',\n", " 'Y',\n", " 'R',\n", " 'P',\n", " 'aux_in1',\n", " 'aux_in2',\n", " 'aux_in3',\n", " 'aux_in4',\n", " 'Xnoise',\n", " 'Ynoise',\n", " 'aux_out1',\n", " 'aux_out2',\n", " 'phase',\n", " 'amplitude',\n", " 'sine_outdc',\n", " 'frequency',\n", " 'frequency_ext']\n" ] } ], "source": [ "pprint(list(lockin.PARAMETER_NAMES.keys()))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the `get_values` method of the driver to obtain values of 2 or 3 of those parameters. The values that are returned by this method are guaranteed to be coming from the same measurement, as opposed to requesting values sequentially by calling `lockin.X()` and then `lockin.Y()`. The method returns a tuple of values." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(-2.1813903572e-07, 1.6225968125e-07, 3.1462531069e-07)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lockin.get_values('X', 'Y', 'Xnoise')" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2.696416459e-07, 152.20687866)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lockin.get_values('R', 'P')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data channels\n", "\n", "Lock-in amplifier has a notion of data channels. Each data channel can be assigned to a measured parameter mentioned above. Each data channel is being displayed on the insturment's screen, and has a corresponding color.\n", "\n", "Let's list the data channels using the `data_channels` list:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Lock-in amplifier has the following data channels:\n", "DAT1 (green)\n", "DAT2 (blue)\n", "DAT3 (yellow)\n", "DAT4 (orange)\n" ] } ], "source": [ "msg = f'Lock-in amplifier has the following data channels:\\n'\n", "msg += '\\n'.join([f'{dch.cmd_id_name} ({dch.color})' for dch in lockin.data_channels])\n", "print(msg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These channels are also accessible individually from the lock-in amplifier driver instance with `data_channel_` attributes.\n", "\n", "Each of the channels has a `color`, `cmd_id` that is used in VISA commands, and `cmd_id_name` that can be (but is not) used in VISA commands, and is just there for reference.\n", "\n", "Most importantly, each data channel has an `assigned_parameter` to it. The available parameter are coming from the same list of parameters from above." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'aux_in3'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lockin.data_channel_3.assigned_parameter('aux_in3')\n", "lockin.data_channel_3.assigned_parameter()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The main feature of the data channels is that the lock-in amplifier has commands to retrieve all of their values at once. This feature is similar to `get_values` method, but instead of specifying the parameter names, the values of the data channels are returned.\n", "\n", "`get_data_channels_values` method returns a tuple of the values of the data channels." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(-1.3243408148e-07, -1.4647376645e-07, -0.00053787231445, -132.11825562)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lockin.get_data_channels_values()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to see which are the assigned parameters for all the data channels, `get_data_channels_parameters` method can be used. Note that this method has a keyword argument `query_instrument` that allows you to choose not to query the values from the instrument in order to save time on VISA communication." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('X', 'Y', 'aux_in3', 'P')" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lockin.get_data_channels_parameters()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, a convenience method available that returns a dictionary of data channels assigned parameters with the associated values. Note that this method also has a keyword argument `requery_names` that allows you to choose whether the assigned parameter names are queried from the instrument. In this case, by default the names are not queried." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'P': -95.362594604,\n", " 'X': -3.9464794099e-08,\n", " 'Y': -4.204223103e-07,\n", " 'aux_in3': -0.00045776367188}" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lockin.get_data_channels_dict()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setting up for the buffer readout examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set capture configuration\n", "\n", "The lock-in needs to know what values shall be captured. Let's capture \"X\" and \"Y\"." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "lockin.input_config('a')\n", "lockin.buffer.capture_config('X,Y')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set lock-in parameters\n", "\n", "Let's tune the lock-in so that it measures something reasonable. Let's not attach any cables to the lock-in, and try to perform a measurement of the noise that the instrument is capturing. The most obvious noise source is the grid, 50 Hz, hence let's set the frequency of the lock-in amplifier somewhere below that frequency to see modulations instead of a flat value that we could have measured at 50 Hz." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "lockin.input_range(10e-3) # V\n", "\n", "lockin.sensitivity(500e-3) # V\n", "lockin.frequency(27.3645) # Hz\n", "lockin.time_constant(10e-3) # s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Initialize AWG" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Connected to: TEKTRONIX AWG5208 (serial:B020205, firmware:FV:6.0.0242.0) in 0.12s\n" ] } ], "source": [ "awg = AWG5208(\"awg\", address='TCPIP0::169.254.254.84::inst0::INSTR')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## One-shot immediate capture\n", "\n", "We are going to capture a number of data points (also referred to as samples) at a capture rate, retrieve data from the buffer, and plot it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set capture rate\n", "\n", "The lock-in will be capturing data at some rate. Let's set this rate:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Capture rate is set to 1220.703125\n" ] } ], "source": [ "lockin.buffer.capture_rate(1220.7)\n", "print(f\"Capture rate is set to {lockin.buffer.capture_rate()}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In case you want to capture data at a maximum possible rate, but you do not remember the value of the maximum possible capture rate, the convenient `set_capture_rate_to_maximum` method can be used: " ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Capture rate is set to its maximum: 39062.5\n" ] } ], "source": [ "lockin.buffer.set_capture_rate_to_maximum()\n", "print(f\"Capture rate is set to its maximum: {lockin.buffer.capture_rate()}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Capture data\n", "\n", "Now let's acquire some data:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The number of acquired X data points is 678\n", "The number of acquired Y data points is 678\n" ] } ], "source": [ "sample_count = 678\n", "\n", "# Set the capture length (which is a portion of the buffer size) \n", "# to fit the number of samples that we want to capture.\n", "# For more information about the maximum buffer size, \n", "# and other buffer-related properties, refer to the instrument manual.\n", "lockin.buffer.set_capture_length_to_fit_samples(sample_count)\n", "\n", "# Start capturing data immediately, \n", "# and without overwriting the buffer in case it gets full.\n", "# For more information about the capture modes, refer to the instrument manual.\n", "lockin.buffer.start_capture(\"ONE\", \"IMM\")\n", "\n", "# We call this blocking method to wait until \n", "# the requested number of samples is captured.\n", "lockin.buffer.wait_until_samples_captured(sample_count)\n", "\n", "# Stop capturing.\n", "lockin.buffer.stop_capture()\n", "\n", "# Retrieve the data from the buffer.\n", "# The returned data is a dictionary where keys are names of the variables\n", "# from the capture config, and values are the captured values.\n", "data = lockin.buffer.get_capture_data(sample_count)\n", "\n", "print(f\"The number of acquired X data points is {len(data['X'])}\")\n", "print(f\"The number of acquired Y data points is {len(data['Y'])}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For convenience, the measurement code from above is encapsulated into a convenient `capture_samples` method of the lock-in buffer:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "scrolled": true }, "outputs": [], "source": [ "data = lockin.buffer.capture_samples(sample_count)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's plot the captured data:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", "window.mpl = {};\n", "\n", "\n", "mpl.get_websocket_type = function() {\n", " if (typeof(WebSocket) !== 'undefined') {\n", " return WebSocket;\n", " } else if (typeof(MozWebSocket) !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", " alert('Your browser does not have WebSocket support.' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.');\n", " };\n", "}\n", "\n", "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", " this.supports_binary = (this.ws.binaryType != undefined);\n", "\n", " if (!this.supports_binary) {\n", " var warnings = document.getElementById(\"mpl-warnings\");\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", " warnings.textContent = (\n", " \"This browser does not support binary websocket messages. \" +\n", " \"Performance may be slow.\");\n", " }\n", " }\n", "\n", " this.imageObj = new Image();\n", "\n", " this.context = undefined;\n", " this.message = undefined;\n", " this.canvas = undefined;\n", " this.rubberband_canvas = undefined;\n", " this.rubberband_context = undefined;\n", " this.format_dropdown = undefined;\n", "\n", " this.image_mode = 'full';\n", "\n", " this.root = $('
');\n", " this._root_extra_style(this.root)\n", " this.root.attr('style', 'display: inline-block');\n", "\n", " $(parent_element).append(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", " this._init_toolbar(this);\n", "\n", " var fig = this;\n", "\n", " this.waiting = false;\n", "\n", " this.ws.onopen = function () {\n", " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", " fig.send_message(\"send_image_mode\", {});\n", " if (mpl.ratio != 1) {\n", " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", " }\n", " fig.send_message(\"refresh\", {});\n", " }\n", "\n", " this.imageObj.onload = function() {\n", " if (fig.image_mode == 'full') {\n", " // Full images could contain transparency (where diff images\n", " // almost always do), so we need to clear the canvas so that\n", " // there is no ghosting.\n", " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", " }\n", " fig.context.drawImage(fig.imageObj, 0, 0);\n", " };\n", "\n", " this.imageObj.onunload = function() {\n", " fig.ws.close();\n", " }\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", "}\n", "\n", "mpl.figure.prototype._init_header = function() {\n", " var titlebar = $(\n", " '
');\n", " var titletext = $(\n", " '
');\n", " titlebar.append(titletext)\n", " this.root.append(titlebar);\n", " this.header = titletext[0];\n", "}\n", "\n", "\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "\n", "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "mpl.figure.prototype._init_canvas = function() {\n", " var fig = this;\n", "\n", " var canvas_div = $('
');\n", "\n", " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", "\n", " function canvas_keyboard_event(event) {\n", " return fig.key_event(event, event['data']);\n", " }\n", "\n", " canvas_div.keydown('key_press', canvas_keyboard_event);\n", " canvas_div.keyup('key_release', canvas_keyboard_event);\n", " this.canvas_div = canvas_div\n", " this._canvas_extra_style(canvas_div)\n", " this.root.append(canvas_div);\n", "\n", " var canvas = $('');\n", " canvas.addClass('mpl-canvas');\n", " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", "\n", " this.canvas = canvas[0];\n", " this.context = canvas[0].getContext(\"2d\");\n", "\n", " var backingStore = this.context.backingStorePixelRatio ||\n", "\tthis.context.webkitBackingStorePixelRatio ||\n", "\tthis.context.mozBackingStorePixelRatio ||\n", "\tthis.context.msBackingStorePixelRatio ||\n", "\tthis.context.oBackingStorePixelRatio ||\n", "\tthis.context.backingStorePixelRatio || 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", " var rubberband = $('');\n", " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", "\n", " var pass_mouse_events = true;\n", "\n", " canvas_div.resizable({\n", " start: function(event, ui) {\n", " pass_mouse_events = false;\n", " },\n", " resize: function(event, ui) {\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " stop: function(event, ui) {\n", " pass_mouse_events = true;\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " });\n", "\n", " function mouse_event_fn(event) {\n", " if (pass_mouse_events)\n", " return fig.mouse_event(event, event['data']);\n", " }\n", "\n", " rubberband.mousedown('button_press', mouse_event_fn);\n", " rubberband.mouseup('button_release', mouse_event_fn);\n", " // Throttle sequential mouse events to 1 every 20ms.\n", " rubberband.mousemove('motion_notify', mouse_event_fn);\n", "\n", " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", "\n", " canvas_div.on(\"wheel\", function (event) {\n", " event = event.originalEvent;\n", " event['data'] = 'scroll'\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", " mouse_event_fn(event);\n", " });\n", "\n", " canvas_div.append(canvas);\n", " canvas_div.append(rubberband);\n", "\n", " this.rubberband = rubberband;\n", " this.rubberband_canvas = rubberband[0];\n", " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", " this.rubberband_context.strokeStyle = \"#000000\";\n", "\n", " this._resize_canvas = function(width, height) {\n", " // Keep the size of the canvas, canvas container, and rubber band\n", " // canvas in synch.\n", " canvas_div.css('width', width)\n", " canvas_div.css('height', height)\n", "\n", " canvas.attr('width', width * mpl.ratio);\n", " canvas.attr('height', height * mpl.ratio);\n", " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", "\n", " rubberband.attr('width', width);\n", " rubberband.attr('height', height);\n", " }\n", "\n", " // Set the figure to an initial 600x600px, this will subsequently be updated\n", " // upon first draw.\n", " this._resize_canvas(600, 600);\n", "\n", " // Disable right mouse context menu.\n", " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", " return false;\n", " });\n", "\n", " function set_focus () {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", "}\n", "\n", "mpl.figure.prototype._init_toolbar = function() {\n", " var fig = this;\n", "\n", " var nav_element = $('
')\n", " nav_element.attr('style', 'width: 100%');\n", " this.root.append(nav_element);\n", "\n", " // Define a callback function for later on.\n", " function toolbar_event(event) {\n", " return fig.toolbar_button_onclick(event['data']);\n", " }\n", " function toolbar_mouse_event(event) {\n", " return fig.toolbar_button_onmouseover(event['data']);\n", " }\n", "\n", " for(var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", " // put a spacer in here.\n", " continue;\n", " }\n", " var button = $('');\n", " button.click(method_name, toolbar_event);\n", " button.mouseover(tooltip, toolbar_mouse_event);\n", " nav_element.append(button);\n", " }\n", "\n", " // Add the status bar.\n", " var status_bar = $('');\n", " nav_element.append(status_bar);\n", " this.message = status_bar[0];\n", "\n", " // Add the close button to the window.\n", " var buttongrp = $('
');\n", " var button = $('');\n", " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", " buttongrp.append(button);\n", " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", " titlebar.prepend(buttongrp);\n", "}\n", "\n", "mpl.figure.prototype._root_extra_style = function(el){\n", " var fig = this\n", " el.on(\"remove\", function(){\n", "\tfig.close_ws(fig, {});\n", " });\n", "}\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(el){\n", " // this is important to make the div 'focusable\n", " el.attr('tabindex', 0)\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", " }\n", " else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", "\n", "}\n", "\n", "mpl.figure.prototype._key_event_extra = function(event, name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", " if (!manager)\n", " manager = IPython.keyboard_manager;\n", "\n", " // Check for shift+enter\n", " if (event.shiftKey && event.which == 13) {\n", " this.canvas_div.blur();\n", " event.shiftKey = false;\n", " // Send a \"J\" for go to next cell\n", " event.which = 74;\n", " event.keyCode = 74;\n", " manager.command_mode();\n", " manager.handle_keydown(event);\n", " }\n", "}\n", "\n", "mpl.figure.prototype.handle_save = function(fig, msg) {\n", " fig.ondownload(fig, null);\n", "}\n", "\n", "\n", "mpl.find_output_cell = function(html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", " if (data['text/html'] == html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", "}\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", "if (IPython.notebook.kernel != null) {\n", " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", "}\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Set the figure size to be more convenient then the defaults\n", "fig = plt.figure(figsize=(6, 3))\n", "\n", "# plot values of all the captured variables\n", "plt.plot(lockin.buffer.X.get(), label='X')\n", "plt.plot(lockin.buffer.Y.get(), label='Y')\n", "plt.xlabel(\"Sample, #\")\n", "plt.ylabel(\"Measured value, V\")\n", "\n", "plt.legend() # show legend\n", "plt.tight_layout() # adjust the figure so that all the labels fit" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Capture after trigger is sent\n", "\n", "In this example, we are going to initiate data capture via a trigger signal. Lock-in amplifier SR860 reacts on the falling edge of the trigger signal. We are going to use a marker of an AWG channel to send the trigger signal." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setup AWG to emit a simple trigger signal\n", "\n", "The following code is specific to the AWG5208 that is used in this example. One is welcome to use waveform generation frameworks like `broadbean` rather than the low-level kind of interaction with the AWG driver below." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "awg.sample_rate(3000) # S/s\n", "\n", "# Create a waveform where the analog channel plays 0s,\n", "# while the marker channel plays a falling edge from 1 to 0.\n", "waveform_ch1 = numpy.zeros((2, 3000)) # the waveform will have a length of 1s\n", " # (3000 samples for 3000 S/s sample rate)\n", "waveform_ch1[1, :-1500] = 1 # falling from 1 to 0 (a.u.), \n", " # at 0.5s after the start of the waveform\n", "elements = numpy.array([waveform_ch1]) # we only have one element in the sequence\n", "waveforms = numpy.array([elements]) # we will use only 1 channel\n", "\n", "# Create a sequence file from the \"waveform\" array\n", "seq_name = 'single_trigger_marker_1'\n", "seqx = awg.makeSEQXFile(\n", " trig_waits=[0], nreps=[1], event_jumps=[0], event_jump_to=[0], go_to=[1],\n", " wfms=waveforms, amplitudes=[1.0], seqname=seq_name)\n", "\n", "# Send the sequence file to AWG internal disk\n", "seqx_file_name = seq_name + '.seqx'\n", "awg.sendSEQXFile(seqx, seqx_file_name)\n", "\n", "awg.clearSequenceList()\n", "awg.clearWaveformList()\n", "\n", "# Load the sequence file from AWG internal disk\n", "awg.loadSEQXFile(seqx_file_name)\n", "\n", "# Full resolution of the AWG channel is 16 bits for AWG5208,\n", "# but we take 1 bit for the marker channel\n", "awg.ch1.resolution = 16 - 1\n", "\n", "awg.ch1.awg_amplitude(1) # V\n", "\n", "# Load a particular sequence to the channel\n", "awg.ch1.setSequenceTrack(seq_name, 0)\n", "# Assign a loaded waveform to the channel\n", "awg.ch1.setWaveform(awg.waveformList[0])\n", "\n", "# Set the marker's high as high as possible \n", "# so that the lock-in detects the falling edge\n", "awg.ch1.marker1_high(1.75) # V\n", "awg.ch1.marker1_low(0) # V\n", "\n", "awg.ch1.state(1) # turns the channel \"on\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set capture rate\n", "\n", "Even though we will be triggering the capture via trigger, the lock-in will still be capturing data at some rate. Let's set this rate:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "scrolled": true }, "outputs": [], "source": [ "lockin.buffer.capture_rate(4882.8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Capture data" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The number of acquired X data points is 321\n", "The number of acquired Y data points is 321\n" ] } ], "source": [ "sample_count = 321\n", "\n", "# Set the capture length (which is a portion of the buffer size) \n", "# to fit the number of samples that we want to acquire.\n", "# For more information about the maximum buffer size, \n", "# and other buffer-related properties, refer to the instrument manual.\n", "lockin.buffer.set_capture_length_to_fit_samples(sample_count)\n", "\n", "# Start capturing data when a trigger signal is recieved, \n", "# and without overwriting the buffer in case it gets full.\n", "# This basically arms the lock-in amplifier.\n", "# For more information about the capture modes, refer to the instrument manual.\n", "lockin.buffer.start_capture(\"ONE\", \"TRIG\")\n", "\n", "# Play the AWG sequence that contains the trigger signal.\n", "# Basically, this call indirectly triggers the lock-in to start capturing data.\n", "awg.play()\n", "\n", "# We call this blocking function to wait \n", "# until the requested number of samples is captured.\n", "lockin.buffer.wait_until_samples_captured(sample_count)\n", "\n", "# Stop capturing.\n", "lockin.buffer.stop_capture()\n", "\n", "# Stop the AWG sequence playback\n", "awg.stop()\n", "\n", "# Retrieve the data from the buffer.\n", "# The returned data is a dictionary where keys are names of the variables\n", "# from the capture config, and values are the captured values.\n", "data = lockin.buffer.get_capture_data(sample_count)\n", "\n", "print(f\"The number of acquired X data points is {len(data['X'])}\")\n", "print(f\"The number of acquired Y data points is {len(data['Y'])}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For convenience, the measurement code from above is encapsulated into a method of the lock-in buffer `capture_samples_after_trigger`:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "scrolled": true }, "outputs": [], "source": [ "try:\n", " \n", " # Note the second argument - it is a callable\n", " # that is responsible for emitting the trigger signal\n", " data = lockin.buffer.capture_samples_after_trigger(sample_count, awg.play)\n", " \n", "finally: # the try-finally block is here purely\n", " # to ensure that the AWG is stopped anyway\n", " awg.stop()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's plot the captured data:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", "window.mpl = {};\n", "\n", "\n", "mpl.get_websocket_type = function() {\n", " if (typeof(WebSocket) !== 'undefined') {\n", " return WebSocket;\n", " } else if (typeof(MozWebSocket) !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", " alert('Your browser does not have WebSocket support.' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.');\n", " };\n", "}\n", "\n", "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", " this.supports_binary = (this.ws.binaryType != undefined);\n", "\n", " if (!this.supports_binary) {\n", " var warnings = document.getElementById(\"mpl-warnings\");\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", " warnings.textContent = (\n", " \"This browser does not support binary websocket messages. \" +\n", " \"Performance may be slow.\");\n", " }\n", " }\n", "\n", " this.imageObj = new Image();\n", "\n", " this.context = undefined;\n", " this.message = undefined;\n", " this.canvas = undefined;\n", " this.rubberband_canvas = undefined;\n", " this.rubberband_context = undefined;\n", " this.format_dropdown = undefined;\n", "\n", " this.image_mode = 'full';\n", "\n", " this.root = $('
');\n", " this._root_extra_style(this.root)\n", " this.root.attr('style', 'display: inline-block');\n", "\n", " $(parent_element).append(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", " this._init_toolbar(this);\n", "\n", " var fig = this;\n", "\n", " this.waiting = false;\n", "\n", " this.ws.onopen = function () {\n", " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", " fig.send_message(\"send_image_mode\", {});\n", " if (mpl.ratio != 1) {\n", " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", " }\n", " fig.send_message(\"refresh\", {});\n", " }\n", "\n", " this.imageObj.onload = function() {\n", " if (fig.image_mode == 'full') {\n", " // Full images could contain transparency (where diff images\n", " // almost always do), so we need to clear the canvas so that\n", " // there is no ghosting.\n", " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", " }\n", " fig.context.drawImage(fig.imageObj, 0, 0);\n", " };\n", "\n", " this.imageObj.onunload = function() {\n", " fig.ws.close();\n", " }\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", "}\n", "\n", "mpl.figure.prototype._init_header = function() {\n", " var titlebar = $(\n", " '
');\n", " var titletext = $(\n", " '
');\n", " titlebar.append(titletext)\n", " this.root.append(titlebar);\n", " this.header = titletext[0];\n", "}\n", "\n", "\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "\n", "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "mpl.figure.prototype._init_canvas = function() {\n", " var fig = this;\n", "\n", " var canvas_div = $('
');\n", "\n", " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", "\n", " function canvas_keyboard_event(event) {\n", " return fig.key_event(event, event['data']);\n", " }\n", "\n", " canvas_div.keydown('key_press', canvas_keyboard_event);\n", " canvas_div.keyup('key_release', canvas_keyboard_event);\n", " this.canvas_div = canvas_div\n", " this._canvas_extra_style(canvas_div)\n", " this.root.append(canvas_div);\n", "\n", " var canvas = $('');\n", " canvas.addClass('mpl-canvas');\n", " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", "\n", " this.canvas = canvas[0];\n", " this.context = canvas[0].getContext(\"2d\");\n", "\n", " var backingStore = this.context.backingStorePixelRatio ||\n", "\tthis.context.webkitBackingStorePixelRatio ||\n", "\tthis.context.mozBackingStorePixelRatio ||\n", "\tthis.context.msBackingStorePixelRatio ||\n", "\tthis.context.oBackingStorePixelRatio ||\n", "\tthis.context.backingStorePixelRatio || 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", " var rubberband = $('');\n", " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", "\n", " var pass_mouse_events = true;\n", "\n", " canvas_div.resizable({\n", " start: function(event, ui) {\n", " pass_mouse_events = false;\n", " },\n", " resize: function(event, ui) {\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " stop: function(event, ui) {\n", " pass_mouse_events = true;\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " });\n", "\n", " function mouse_event_fn(event) {\n", " if (pass_mouse_events)\n", " return fig.mouse_event(event, event['data']);\n", " }\n", "\n", " rubberband.mousedown('button_press', mouse_event_fn);\n", " rubberband.mouseup('button_release', mouse_event_fn);\n", " // Throttle sequential mouse events to 1 every 20ms.\n", " rubberband.mousemove('motion_notify', mouse_event_fn);\n", "\n", " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", "\n", " canvas_div.on(\"wheel\", function (event) {\n", " event = event.originalEvent;\n", " event['data'] = 'scroll'\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", " mouse_event_fn(event);\n", " });\n", "\n", " canvas_div.append(canvas);\n", " canvas_div.append(rubberband);\n", "\n", " this.rubberband = rubberband;\n", " this.rubberband_canvas = rubberband[0];\n", " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", " this.rubberband_context.strokeStyle = \"#000000\";\n", "\n", " this._resize_canvas = function(width, height) {\n", " // Keep the size of the canvas, canvas container, and rubber band\n", " // canvas in synch.\n", " canvas_div.css('width', width)\n", " canvas_div.css('height', height)\n", "\n", " canvas.attr('width', width * mpl.ratio);\n", " canvas.attr('height', height * mpl.ratio);\n", " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", "\n", " rubberband.attr('width', width);\n", " rubberband.attr('height', height);\n", " }\n", "\n", " // Set the figure to an initial 600x600px, this will subsequently be updated\n", " // upon first draw.\n", " this._resize_canvas(600, 600);\n", "\n", " // Disable right mouse context menu.\n", " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", " return false;\n", " });\n", "\n", " function set_focus () {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", "}\n", "\n", "mpl.figure.prototype._init_toolbar = function() {\n", " var fig = this;\n", "\n", " var nav_element = $('
')\n", " nav_element.attr('style', 'width: 100%');\n", " this.root.append(nav_element);\n", "\n", " // Define a callback function for later on.\n", " function toolbar_event(event) {\n", " return fig.toolbar_button_onclick(event['data']);\n", " }\n", " function toolbar_mouse_event(event) {\n", " return fig.toolbar_button_onmouseover(event['data']);\n", " }\n", "\n", " for(var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", " // put a spacer in here.\n", " continue;\n", " }\n", " var button = $('');\n", " button.click(method_name, toolbar_event);\n", " button.mouseover(tooltip, toolbar_mouse_event);\n", " nav_element.append(button);\n", " }\n", "\n", " // Add the status bar.\n", " var status_bar = $('');\n", " nav_element.append(status_bar);\n", " this.message = status_bar[0];\n", "\n", " // Add the close button to the window.\n", " var buttongrp = $('
');\n", " var button = $('');\n", " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", " buttongrp.append(button);\n", " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", " titlebar.prepend(buttongrp);\n", "}\n", "\n", "mpl.figure.prototype._root_extra_style = function(el){\n", " var fig = this\n", " el.on(\"remove\", function(){\n", "\tfig.close_ws(fig, {});\n", " });\n", "}\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(el){\n", " // this is important to make the div 'focusable\n", " el.attr('tabindex', 0)\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", " }\n", " else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", "\n", "}\n", "\n", "mpl.figure.prototype._key_event_extra = function(event, name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", " if (!manager)\n", " manager = IPython.keyboard_manager;\n", "\n", " // Check for shift+enter\n", " if (event.shiftKey && event.which == 13) {\n", " this.canvas_div.blur();\n", " event.shiftKey = false;\n", " // Send a \"J\" for go to next cell\n", " event.which = 74;\n", " event.keyCode = 74;\n", " manager.command_mode();\n", " manager.handle_keydown(event);\n", " }\n", "}\n", "\n", "mpl.figure.prototype.handle_save = function(fig, msg) {\n", " fig.ondownload(fig, null);\n", "}\n", "\n", "\n", "mpl.find_output_cell = function(html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", " if (data['text/html'] == html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", "}\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", "if (IPython.notebook.kernel != null) {\n", " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", "}\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Set the figure size to be more convenient then the defaults\n", "fig = plt.figure(figsize=(6, 3))\n", "\n", "# plot values of all the captured variables\n", "for var_name in data:\n", " plt.plot(data[var_name], label=var_name)\n", "plt.xlabel(\"Sample, #\")\n", "plt.ylabel(\"Measured value, V\")\n", "\n", "plt.legend() # show legend\n", "plt.tight_layout() # adjust the figure so that all the labels fit" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" }, "nbsphinx": { "execute": "never" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "247px" }, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }