def test_return_handle(self): plotM = MatPlot(interval=0) returned_handle = plotM.add([1, 2, 3]) line_handle = plotM[0].get_lines()[0] self.assertIs(returned_handle, line_handle) plotM.clear() plt.close(plotM.fig)
def diffDataset(alldata, diff_dir='y', sigma=2, fig=None, meas_arr_name='measured'): """ Differentiate a dataset and plot the result. Args: alldata (qcodes DataSet) diff_dir (str): direction to differentiate in meas_arr_name (str): name of the measured array to be differentiated fig (int): the number for the figure to plot sigma (float): parameter for gaussian filter kernel """ meas_arr_name = alldata.default_parameter_name(meas_arr_name) meas_array = alldata.arrays[meas_arr_name] imx = qtt.utilities.tools.diffImageSmooth(meas_array.ndarray, dy=diff_dir, sigma=sigma) name = 'diff_dir_%s' % diff_dir name = uniqueArrayName(alldata, name) data_arr = qcodes.DataArray( name=name, label=name, array_id=name, set_arrays=meas_array.set_arrays, preset_data=imx) alldata.add_array(data_arr) if fig is not None: plt.figure(fig) plt.clf() plot = MatPlot(interval=0, num=fig) plot.add(alldata.arrays[name]) plot.fig.axes[0].autoscale(tight=True) plot.fig.axes[1].autoscale(tight=True) return alldata
def _create_plot(i, name, data, counter_two): # Step the color on all subplots no just on plots # within the same axis/subplot # this is to match the qcodes-pyqtplot behaviour. title = "{} #{:03d}".format(CURRENT_EXPERIMENT["sample_name"], data.location_provider.counter) rasterized_note = " rasterized plot full data available in datafile" color = 'C' + str(counter_two) counter_two += 1 plot = MatPlot() inst_meas_name = "{}_{}".format(i._instrument.name, name) inst_meas_data = getattr(data, inst_meas_name) inst_meta_data = __get_plot_type(inst_meas_data, plot) if 'z' in inst_meta_data: xlen, ylen = inst_meta_data['z'].shape rasterized = xlen * ylen > 5000 plot.add(inst_meas_data, rasterized=rasterized) else: rasterized = False plot.add(inst_meas_data, color=color) plot.subplots[0].grid() if rasterized: plot.subplots[0].set_title(title + rasterized_note) else: plot.subplots[0].set_title(title) plot.save("{}_{:03d}.pdf".format(plot.get_default_title(), counter_two)) plot.fig.canvas.draw()
def plot_dataset(dataset: qcodes.DataSet, parameter_names: Optional[list] = None, fig: Optional[int] = 1) -> None: """ Plot a dataset to matplotlib figure window Args: dataset: DataSet to be plotted parameter_names: List of arrays to be plotted fig: Specification if Matplotlib figure window """ if parameter_names is None: parameter_names = [dataset.default_parameter_name()] if parameter_names == 'all': parameter_names = [name for name in dataset.arrays.keys() if not dataset.arrays[name].is_setpoint] default_array = dataset.default_parameter_array() if fig: plt.figure(fig) plt.clf() if len(default_array.shape) >= 2: if len(parameter_names) > 1: arrays = [dataset.default_parameter_array(parameter_name) for parameter_name in parameter_names] plot_handle = MatPlot(*arrays, num=fig) else: plot_handle = MatPlot(dataset.default_parameter_array(parameter_names[0]), num=fig) else: for idx, parameter_name in enumerate(parameter_names): if idx == 0: plot_handle = MatPlot(dataset.default_parameter_array(parameter_name), num=fig) else: plot_handle.add(dataset.default_parameter_array(parameter_name,))
def plot_awg_to_plunger(result, fig=10): """ This function tests the analyse_awg_to_plunger function. Plotting is optional and for debugging purposes. Args: result (dict): result dictionary from the analyse_awg_to_plunger function. fig (int): index of matplotlib window. """ if not result.get('type', None) == 'awg_to_plunger': raise Exception('calibration result not of correct type ') angle = result['angle'] ds = get_dataset(result) _, tr = qtt.data.dataset2image(ds) xscan = tr.pixel2scan(np.array([[0], [0]])) plt.figure(fig) plt.clf() MatPlot(ds.default_parameter_array(), num=fig) if angle is not None: rho = -(xscan[0] * np.cos(angle) - np.sin(angle) * xscan[1]) for offset in [-40, -20, 0, 20, 40]: label = None if offset is 0: label = 'detected angle' qtt.pgeometry.plot2Dline( [np.cos(angle), -np.sin(angle), rho + offset], '--m', alpha=.6, label=label) plt.title('Detected line direction')
def plot_pinchoff(result, ds=None, fig=10, verbose=1): """ Plot result of a pinchoff scan """ if ds is None: ds = qtt.data.get_dataset(result) if not result.get('type', 'none') in ['gatesweep', 'pinchoff']: raise Exception('calibration result of incorrect type') if fig is not None: plt.figure(fig) plt.clf() MatPlot(ds.default_parameter_array(), num=fig) lowvalue = result['lowvalue'] highvalue = result['highvalue'] pinchoff_point = result['pinchoff_point'] midpoint = result['midpoint'] midvalue = result['midvalue'] plot2Dline([0, -1, lowvalue], '--c', alpha=.5, label='low value') plot2Dline([0, -1, highvalue], '--c', alpha=.5, label='high value') plot2Dline([-1, 0, midpoint], ':m', linewidth=2, alpha=0.5, label='midpoint') if verbose >= 2: plt.plot(midpoint, midvalue, '.m', label='midpoint') plot2Dline([-1, 0, pinchoff_point], '--g', linewidth=1, alpha=0.5, label='pinchoff_point')
def test_plot_matplotlib(self, fig=100): """ We need to plot simple 1D and 2D datasets with proper units and labels.""" plt.close(fig) xarray = self.dataset1d.x_set MatPlot(self.dataset1d.default_parameter_array(), num=fig) plt.figure(fig) ax = plt.gca() self.assertEqual(ax.xaxis.label.get_text(), xarray.label + ' (' + str(xarray.unit) + ')') plt.close(fig)
def read_AMP(t_total): t0 = time.time() X = np.linspace(0, t_total, t_total + 1) Y = np.zeros((t_total + 1, ), dtype=np.float32) # Y = np.array plot = MatPlot(x=X, y=Y) # plot = QtPlot() # plot.add(x = X, y = Y) for i in range(t_total): t = time.time() if (t - t0) == i: Y[i] = AMP() plot.update() return Y
def test_make_args_for_pcolormesh(): # We test some common situations # # y in the outer loop setpoints, i.e. of shape (N,) # x is the inner loop setpoints, i.e. of shape (N, M) # z is the data, i.e. of shape (N, M) N = 10 # y M = 25 # x xrange = np.linspace(-1, 1, M) yrange = np.linspace(-10, 0.5, N) # up scans, down scans for xsign, ysign in product([-1, 1], repeat=2): x, y, z = make_simulated_xyz(xsign * xrange, ysign * yrange, step=N // 2 + 1) args_masked = [np.ma.masked_invalid(arg) for arg in [x, y, z]] args = MatPlot._make_args_for_pcolormesh(args_masked, x, y) assert len(args[0]) == M + 1 assert len(args[1]) == N + 1 # an interrupted scan x, y, z = make_simulated_xyz(xsign * xrange, ysign * yrange, step=N // 2 + 1, interrupt_at=M // 2 + 1) args_masked = [np.ma.masked_invalid(arg) for arg in [x, y, z]] args = MatPlot._make_args_for_pcolormesh(args_masked, x, y) assert len(args[0]) == M + 1 assert len(args[1]) == N + 1
def plot1D(dataset, fig=1): """ Simlpe plot function """ if isinstance(dataset, qcodes.DataArray): array = dataset dataset = None else: # assume we have a dataset arrayname = plot_parameter(dataset) array = getattr(dataset, arrayname) if fig is not None and array is not None: MatPlot(array, num=fig)
def plot(self, *args, min_delay=0.5, figsize=None, subplots=None, num=None, **kwargs): plot = MatPlot(*args, figsize=figsize, subplots=subplots, num=num, **kwargs) self.with_bg_task(plot.update, min_delay=min_delay) return plot
def set_sweep_with_calibration(self, repetition=False, plot_average=False, **kw): self.plot_average = plot_average for i in range(self.qubit_number): d = i if i == 1 else 2 self.plot.append( QtPlot(window_title='raw plotting qubit_%d' % d, remote=False)) # self.plot.append(MatPlot(figsize = (8,5))) if plot_average: # self.average_plot.append(QtPlot(window_title = 'average data qubit_%d'%d, remote = False)) self.average_plot.append(MatPlot(figsize=(8, 5))) for seq in range(len(self.sequencer)): self.sequencer[seq].set_sweep() self.make_all_segment_list(seq) if repetition is True: count = kw.pop('count', 1) Count_Calibration = StandardParameter(name='Count', set_cmd=self.function) Sweep_Count_Calibration = Count_Calibration[1:2:1] Count = StandardParameter(name='Count', set_cmd=self.delete) Sweep_Count = Count[1:count + 1:1] self.digitizer, self.dig = set_digitizer(self.digitizer, len(self.X_sweep_array), self.qubit_number, self.seq_repetition) loop1 = Loop(sweep_values=Sweep_Count_Calibration).each(self.dig) Loop_Calibration = loop1.with_bg_task( bg_final_task=self.update_calibration, ) calibrated_parameter = update_calibration if self.Loop is None: self.Loop = Loop(sweep_values=Sweep_Count).each( calibrated_parameter, self.dig) else: raise TypeError('calibration not set') return True
def plot_anticrossing(ds, afit, fig=100, linewidth=2): """ Plot fitted anti-crossing on dataset. Args: afit (dict): fit data from fit_anticrossing ds (None or DataSet): dataset to show fig (int): index of matplotlib window linewidth (integer): plot linewidth, default = 2 Returns: - """ fitpoints = afit['fitpoints'] plt.figure(fig) plt.clf() if ds is not None: MatPlot(ds.default_parameter_array('diff_dir_g'), num=fig) cc = fitpoints['centre'] plt.plot(cc[0], cc[1], '.m', markersize=12, label='fit centre') lp = fitpoints['left_point'] hp = fitpoints['right_point'] op = fitpoints['outer_points'].T ip = fitpoints['inner_points'].T plt.plot([float(lp[0]), float(hp[0])], [float(lp[1]), float(hp[1])], '.--m', linewidth=linewidth, markersize=10, label='transition line') for ii in range(4): if ii == 0: lbl = 'electron line' else: lbl = None plt.plot([op[ii, 0], ip[ii, 0]], [op[ii, 1], ip[ii, 1]], '.-', linewidth=linewidth, color=[0, .7, 0], label=lbl) qtt.pgeometry.plotLabels( np.array((op[ii, :] + ip[ii, :]) / 2).reshape((2, -1)), '%d' % ii)
def data_set_plot(data_set, data_location): Plot = MatPlot() raw_data_set = load_data( location=data_location, io=NewIO, ) data_set_P = convert_to_probability(raw_data_set, threshold=0.025) x_data = data_set_P.arrays['vsg2_frequency_set'].ndarray P_data = data_set_P.arrays['digitizer'].ndarray.T[0] x = x_data y = P_data plt.plot(x, y)
def plot_flips(self , figsize=(8, 3)): up_proportion_arrays = [ val for key, val in self.results.ESR.items() if key.startswith('up_proportion') and 'idxs' not in key ] assert len(up_proportion_arrays) >= 2 plot = MatPlot(up_proportion_arrays, marker='o', ms=5, linestyle='', figsize=figsize) ax = plot[0] ax.set_xlim(-0.5, len(up_proportion_arrays[0])-0.5) ax.set_ylim(-0.015, 1.015) ax.set_xlabel('Shot index') ax.set_ylabel('Up proportion') # Add threshold lines ax.hlines(self.results.NMR.threshold_up_proportion, *ax.get_xlim(), lw=3) ax.hlines(self.results.NMR.threshold_low, *ax.get_xlim(), color='grey', linestyle='--', lw=2) ax.hlines(self.results.NMR.threshold_high, *ax.get_xlim(), color='grey', linestyle='--', lw=2) if 'initialization' in self.results: plot.add(self.results.initialization.up_proportions, marker='o', ms=8, linestyle='', color='grey', zorder=0, alpha=0.5) initialization_filtered_shots = next( val for key, val in self.results["initialization"].items() if key.startswith("filtered_shots") ) else: initialization_filtered_shots = [True] * len(self.results.NMR.filtered_shots) NMR_filtered_shots = self.results.NMR.filtered_shots for k, up_proportion_tuple in enumerate(zip(*up_proportion_arrays)): if not initialization_filtered_shots[k]: color = 'orange' elif not NMR_filtered_shots[k]: color = 'red' else: color = 'green' ax.plot([k, k], sorted(up_proportion_tuple)[-2:], color=color, zorder=-1) plot.tight_layout() # print contrast sorted_up_proportions = np.sort(np.array(up_proportion_arrays), axis=0) up_proportion = np.mean(sorted_up_proportions[-1]) dark_counts = np.mean(sorted_up_proportions[:-1]) contrast = up_proportion - dark_counts print(f'Contrast = {up_proportion:.2f} - {dark_counts:.2f} = {contrast:.2f}') return plot
def show_num(id, useQT=False, **kwargs): """ Show and return plot and data for id in current instrument. Args: id(number): id of instrument useQT: Use pyqtgraph as an alternative to Matplotlib **kwargs: Are passed to plot function Returns: plot, data : returns the plot and the dataset """ if not getattr(CURRENT_EXPERIMENT, "init", True): raise RuntimeError("Experiment not initalized. " "use qc.Init(mainfolder, samplename)") str_id = '{0:03d}'.format(id) t = qc.DataSet.location_provider.fmt.format(counter=str_id) data = qc.load_data(t) plots = [] for value in data.arrays.keys(): if "set" not in value: if useQT: plot = QtPlot( getattr(data, value), fig_x_position=CURRENT_EXPERIMENT['plot_x_position'], **kwargs) title = "{} #{}".format(CURRENT_EXPERIMENT["sample_name"], str_id) plot.subplots[0].setTitle(title) plot.subplots[0].showGrid(True, True) else: plot = MatPlot(getattr(data, value), **kwargs) title = "{} #{}".format(CURRENT_EXPERIMENT["sample_name"], str_id) plot.subplots[0].set_title(title) plot.subplots[0].grid() plots.append(plot) return data, plots
def show_num(id, useQT=False, do_plots=True): """ Show and return plot and data for id in current instrument. Args: id(number): id of instrument do_plots: Default False: if false no plots are produced. Returns: plot, data : returns the plot and the dataset """ if not getattr(CURRENT_EXPERIMENT, "init", True): raise RuntimeError("Experiment not initalized. " "use qc.Init(mainfolder, samplename)") str_id = '{0:03d}'.format(id) t = qc.DataSet.location_provider.fmt.format(counter=str_id) data = qc.load_data(t) if do_plots: plots = [] for value in data.arrays.keys(): if "set" not in value: if useQT: plot = QtPlot( getattr(data, value), fig_x_position=CURRENT_EXPERIMENT['plot_x_position']) title = "{} #{}".format(CURRENT_EXPERIMENT["sample_name"], str_id) plot.subplots[0].setTitle(title) plot.subplots[0].showGrid(True, True) else: plot = MatPlot(getattr(data, value)) title = "{} #{}".format(CURRENT_EXPERIMENT["sample_name"], str_id) plot.subplots[0].set_title(title) plot.subplots[0].grid() plots.append(plot) else: plots = None return data, plots
def plot_dataset(dataset: DataSet, scanjob, save=True) -> None: """ Plot a dataset to matplotlib figure window Args: dataset: DataSet to be plotted scanjob: scanjob of the measurement save: Select if you want to save the plots """ parameter_names = [ name for name in dataset.arrays.keys() if not dataset.arrays[name].is_setpoint ] default_array = dataset.default_parameter_array() # Path for saving base_loc = dataset.default_io.base_location folder = '\\' + dataset.location + '\\' label = str(scanjob.get('dataset_label')) path = base_loc + folder + label # 2D plots if len(default_array.shape) >= 2: for idx, parameter_name in enumerate(parameter_names): plot_handle = MatPlot(dataset.arrays[parameter_name], num=idx) plot_handle.rescale_axis() if save == True: plt.savefig(path + str(idx) + '.png') # 1D plots else: for idx, parameter_name in enumerate(parameter_names): plot_handle = MatPlot(dataset.arrays[parameter_name], num=idx) plot_handle.rescale_axis() if save == True: plt.savefig(path + str(idx) + '.png')
def test_creation(self): ''' Simple test function which created a QtPlot window ''' plotM = MatPlot(interval=0) plt.close(plotM.fig)
def perpLineIntersect(ds, description, vertical=True, points=None, fig=588, diff_dir='xy'): """ Takes three points in a graph and calculates the length of a linepiece between a line through points 1,2 and a vertical/horizontal line through the third point. Uses the currently active figure. Args: ds (dataset): dataset with charge stability diagram and gate voltage in mV vertical (bool): find intersection of point with line vertically (True) or horizontally (False) points (None or array): if None, then let the user select points diff_dir (None or 'xy'): specification of differentiation direction Returns: (dict): 'intersection_point' = intersetcion point 'distance' = length of line from 3rd clicked point to line through clicked points 1 and 2 'clicked_points' = coordinates of the three clicked points """ if diff_dir is not None: diffDataset(ds, diff_dir='xy') array_name = 'diff_dir_xy' else: array_name = ds.default_parameter_name() plt.figure(fig) plt.clf() MatPlot(ds.arrays[array_name], num=fig) ax = plt.gca() ax.set_autoscale_on(False) if description == 'lever_arm' and vertical == True: print('''Please click three points; Point 1: on the addition line for the dot represented on the vertical axis Point 2: further on the addition line for the dot represented on the vertical axis Point 3: on the triple point at the addition line for the dot represented on the horizontal axis where both dot levels are aligned''') elif description == 'lever_arm' and vertical == False: print('''Please click three points; Point 1: on the addition line for the dot represented on the horizontal axis Point 2: further on the addition line for the dot represented on the horizontal axis Point 3: on the triple point at the addition line for the dot represented on the horizontal axis where both dot levels are aligned''') elif description == 'E_charging': print('''Please click three points; Point 1: on the (0, 1) - (0,2) addition line Point 2: further on the (0, 1) - (0,2) addition line Point 3: on the (0, 0) - (0, 1) addition line ''') else: # Do something here such that no three points need to be clicked raise Exception('''Please make sure that the description argument of this function is either 'lever_arm' or 'E_charging' ''') if points is not None: clicked_pts = points else: plt.title('Select three points') plt.draw() plt.pause(1e-3) clicked_pts = qtt.pgeometry.ginput(3, '.c') qtt.pgeometry.plotPoints(clicked_pts, ':c') qtt.pgeometry.plotLabels(clicked_pts) linePoints1_2 = qtt.pgeometry.fitPlane(clicked_pts[:, 0:2].T) yy = clicked_pts[:, [2, 2]] yy[1, -1] += 1 line_vertical = qtt.pgeometry.fitPlane(yy.T) xx = clicked_pts[:, [2, 2]] xx[0, -1] += 1 line_horizontal = qtt.pgeometry.fitPlane(xx.T) if vertical == True: i = qtt.pgeometry.intersect2lines(linePoints1_2, line_vertical) intersectPoint = qtt.pgeometry.dehom(i) line = intersectPoint[:, [0, 0]] line[0, -1] += 1 else: i = qtt.pgeometry.intersect2lines(linePoints1_2, line_horizontal) intersectPoint = qtt.pgeometry.dehom(i) line = intersectPoint[:, [0, 0]] line[1, -1] += 1 linePt3_ints = qtt.pgeometry.fitPlane(line.T) line_length = np.linalg.norm(intersectPoint - clicked_pts[:, 2:3]) # visualize plotAnalysedLines(clicked_pts, linePoints1_2, line_vertical, line_horizontal, linePt3_ints, intersectPoint) return {'intersection_point': intersectPoint, 'distance': line_length, 'clicked_points': clicked_pts, 'array_names': [array.name for array in ds.default_parameter_array().set_arrays]}
NewIO = DiskIO(base_location = 'C:\\Users\\LocalAdmin\\Documents') formatter = HDF5FormatMetadata() try_location = '2017-09-04/17-23-05Finding_ResonanceRabi_Sweep' DS = load_data(location = try_location, io = NewIO,) DS_P = convert_to_probability(DS, 0.025) DS_new = new_data(location = try_location, io = NewIO,) x_data = np.linspace(1,10,10) y_data = np.linspace(11,20,10) #z_data = np.linspace(101,201,101) Mplot = MatPlot(x_data,y_data) Qplot = QtPlot(x_data,y_data) Mplot = MatPlot() config = { 'x': np.linspace(1,20,20), 'y': np.linspace(11,30,20) } #Mplot.traces[0]['config'] = config data = np.array([1,2,3]) data1 = np.array([[1,2,33,5],[5,232,7,3],[1,2,3,4]]) data_array1 = DataArray(preset_data = data, name = 'digitizer', is_setpoint = True)
#y = 1-y pars, pcov = curve_fit(RB_Fidelity, x, y, p0=(0.9, 0.2, 0.3), bounds=((0.5, 0, 0), (1, 0.8, 0.8))) # bounds = ((), ())) #pars, pcov = curve_fit(RB_Fidelity, x, y, # p0 = (-0.9, 0.2, -0.4), # bounds = ((-1, 0, -1),(-0.5, 0.8, 0))) #%% plot_point = fitting_point pt = MatPlot() pt.add(x=x[:plot_point], y=ds.probability_data[:, i, 11:11 + fitting_point].mean(axis=0)[:plot_point], fmt='bp', xlabel='Clifford Numbers', ylabel='$P_{|1>}$', xunit='N', yunit='%') pt.add( x=x[:plot_point], y=RB_Fidelity(x, pars[0], pars[1], pars[2])[:plot_point], fmt='b--', ) #pt.add_to_plot(xlabel = 'Clifford Numbers') #%%
def analyse_awg_to_plunger(result: dict, method: str = 'hough', fig: Optional[int] = None) -> dict: """ Determine the awg_to_plunger conversion factor from a 2D scan, two possible methods: 'hough' it fits the slope of the addition line and calculates the correction to the awg_to_plunger conversion factor from there. if this doesn't work for some reason, method 'click' can be used to find the addition lines by hand/eye. Args: result: result dictionary of the function measure_awg_to_plunger, shape: result = {'type': 'awg_to_plunger', 'awg_to_plunger': None, 'dataset': ds.location}. method: either 'hough' or 'click'. fig : determines of the analysis staps and the result is plotted. Returns: result: including to following entries: angle (float): angle in radians. angle_degrees (float): angle in degrees. correction of awg_to_plunger (float): correction factor. dataset (str): location where the dataset is stored. type(str): type of calibration, 'awg_to_plunger'. """ # getting the dataset from the result from the measure_awg_to_plunger function if result.get('type') != 'awg_to_plunger': raise AssertionError('not of type awg_to_plunger!') ds = get_dataset(result) # choosing a method; # the method 'hough' fits the addition line if method == 'hough': import cv2 im, tr = qtt.data.dataset2image(ds) imextent = tr.scan_image_extent() istep = tr.scan_resolution() _, r = qtt.algorithms.images.straightenImage( im, imextent, mvx=istep, mvy=None) H = r[4] imc = cleanSensingImage(im, sigma=0.93, dy=0) imx, _ = straightenImage(imc, imextent, mvx=istep, verbose=0) imx = imx.astype(np.float64) * \ (100. / np.percentile(imx, 99)) # scale image gray = qtt.pgeometry.scaleImage(imx) edges = cv2.Canny(gray, 50, 150, apertureSize=3) lines = cv2.HoughLines(edges, 1, np.pi / 180, int(gray.shape[0] * .5)) if lines is None: angle_pixel = None angle = None xscan = None angle_deg = None correction = None else: angles = lines[:, 0, 1] angle_pixel = angles[0] # take most voted line fac = 2 xpix = np.array([[0, 0], [-fac * np.sin(angle_pixel), fac * np.cos(angle_pixel)]]).T tmp = qtt.pgeometry.projectiveTransformation(np.linalg.inv(H), xpix) xscan = tr.pixel2scan(tmp) def vec2angle(v): return np.arctan2(v[0], v[1]) angle = vec2angle(xscan[:, 1] - xscan[:, 0]) correction = -1 / np.tan(angle) angle_deg = np.rad2deg(angle) # plotting the analysis steps of the data if fig is not None: plt.figure(fig + 1) plt.clf() plt.imshow(gray) plt.axis('image') if angle_pixel is not None: for offset_in_pixels in [-40, -20, 0, 20, 40]: label = None if offset_in_pixels == 0: label = 'detected angle' qtt.pgeometry.plot2Dline( [np.cos(angle_pixel), np.sin(angle_pixel), offset_in_pixels], 'm', label=label) if angle is not None: plt.title(f'Detected line direction: angle {angle_deg:.2f} [deg]') plt.figure(fig + 2) plt.clf() plt.imshow(edges) plt.axis('image') plt.title('Detected edge points') # the method click relies on the user clicking two points to indicate the addition line elif method == 'click': if fig is not None: plt.figure(fig) plt.clf() MatPlot(ds.default_parameter_array(), num=fig) plt.draw() plt.pause(1e-3) print("Please click two different points on the addition line") offset, slope = click_line(fig=fig) angle_pixel = None angle = -np.pi / 2 - np.tanh(slope) correction = -1 / np.tan(angle) angle_deg = angle / (2 * np.pi) * 360 else: raise Exception('method %s not implemented' % (method,)) # filling the result dictionary result = copy.copy(result) result['_angle_pixel'] = angle_pixel result['angle'] = angle result['angle_degrees'] = angle_deg result['correction of awg_to_plunger'] = correction if method == 'click': result['slope'] = slope result['offset'] = offset # optional, plotting figures showing the analysis if fig is not None: plot_awg_to_plunger(result=result, fig=fig) return result
def _plot_setup(data, inst_meas, useQT=True, startranges=None): title = "{} #{:03d}".format(CURRENT_EXPERIMENT["sample_name"], data.location_provider.counter) rasterized_note = " rasterized plot" num_subplots = 0 counter_two = 0 for j, i in enumerate(inst_meas): if getattr(i, "names", False): num_subplots += len(i.names) else: num_subplots += 1 if useQT: plot = QtPlot(fig_x_position=CURRENT_EXPERIMENT['plot_x_position']) else: plot = MatPlot(subplots=(1, num_subplots)) def _create_plot(plot, i, name, data, counter_two, j, k): """ Args: plot: The plot object, either QtPlot() or MatPlot() i: The parameter to measure name: - data: The DataSet of the current measurement counter_two: The sub-measurement counter. Each measurement has a number and each sub-measurement has a counter. j: The current sub-measurement k: - """ color = 'C' + str(counter_two) counter_two += 1 inst_meas_name = "{}_{}".format(i._instrument.name, name) inst_meas_data = getattr(data, inst_meas_name) inst_meta_data = __get_plot_type(inst_meas_data, plot) if useQT: plot.add(inst_meas_data, subplot=j + k + 1) plot.subplots[j + k].showGrid(True, True) if j == 0: plot.subplots[0].setTitle(title) else: plot.subplots[j + k].setTitle("") plot.fixUnitScaling(startranges) QtPlot.qc_helpers.foreground_qt_window(plot.win) else: if 'z' in inst_meta_data: xlen, ylen = inst_meta_data['z'].shape rasterized = xlen * ylen > 5000 plot.add(inst_meas_data, subplot=j + k + 1, rasterized=rasterized) else: rasterized = False plot.add(inst_meas_data, subplot=j + k + 1, color=color) plot.subplots[j + k].grid() if j == 0: if rasterized: fulltitle = title + rasterized_note else: fulltitle = title plot.subplots[0].set_title(fulltitle) else: if rasterized: fulltitle = rasterized_note else: fulltitle = "" plot.subplots[j + k].set_title(fulltitle) for j, i in enumerate(inst_meas): if getattr(i, "names", False): # deal with multidimensional parameter for k, name in enumerate(i.names): _create_plot(plot, i, name, data, counter_two, j, k) counter_two += 1 else: # simple_parameters _create_plot(plot, i, i.name, data, counter_two, j, 0) counter_two += 1 return plot, num_subplots
def _create_plot(i, name, data, counter_two, display_plot=True): # Step the color on all subplots no just on plots # within the same axis/subplot # this is to match the qcodes-pyqtplot behaviour. title = "{} #{:03d}".format(CURRENT_EXPERIMENT["sample_name"], data.location_provider.counter) rasterized_note = " rasterized plot full data available in datafile" color = 'C' + str(counter_two) counter_two += 1 plot = MatPlot() inst_meas_name = "{}_{}".format(i._instrument.name, name) inst_meas_data = getattr(data, inst_meas_name) inst_meta_data = __get_plot_type(inst_meas_data, plot) if 'z' in inst_meta_data: xlen, ylen = inst_meta_data['z'].shape rasterized = xlen * ylen > 5000 plot.add(inst_meas_data, rasterized=rasterized) else: rasterized = False plot.add(inst_meas_data, color=color) plot.subplots[0].grid() if rasterized: plot.subplots[0].set_title(title + rasterized_note) else: plot.subplots[0].set_title(title) title_list = plot.get_default_title().split(sep) title_list.insert(-1, CURRENT_EXPERIMENT['pdf_subfolder']) title = sep.join(title_list) plot.rescale_axis() plot.tight_layout() plot.save("{}_{:03d}.pdf".format(title, counter_two)) if display_plot: plot.fig.canvas.draw() plt.show() else: plt.close(plot.fig)
#%% time_range = time_range fitting_num = X_num x = np.linspace(0, fitting_num - 1, fitting_num) t = np.linspace(0, time_range, fitting_num) #pars1, pcov = curve_fit(sequence_decay, x, average[0],) pars1, pcov = curve_fit(Exp_Sin_decay, t * 1e6, average[0], p0=(0.2, 0.3, 6, 1.5, 0.3), bounds=((0, -np.inf, 0.2, -np.inf, -np.inf), (np.inf, np.inf, 10, np.inf, np.inf))) pt = MatPlot() pt.add(x=t, y=average[0], xlabel='dephasing_time', ylabel='probability |11>') pt.add(x=t, y=sequence_decay(t * 1e6, pars1[0], pars1[1], pars1[-1])) pt.add( x=t, y=Exp_Sin_decay(t * 1e6, pars1[0], pars1[1], pars1[2], pars1[3], pars1[4]), ) print('T2* in exp1:', pars1[-1], 'us') print('freq:', pars1[2], 'MHz') #pars2, pcov = curve_fit(Exp_Sin_decay, x, average[1],) pars2, pcov = curve_fit(Exp_Sin_decay, t * 1e6, average[1], p0=(0.2, 0.3, 6, 1.5, 0.3), bounds=((0, -np.inf, 0.2, -np.inf, -np.inf),
def _plot_setup(data, inst_meas, useQT=True, startranges=None, auto_color_scale=None, cutoff_percentile=None): title = "{} #{:03d}".format(CURRENT_EXPERIMENT["sample_name"], data.location_provider.counter) rasterized_note = " rasterized plot" num_subplots = 0 counter_two = 0 for j, i in enumerate(inst_meas): if getattr(i, "names", False): num_subplots += len(i.names) else: num_subplots += 1 if useQT: plot = QtPlot(fig_x_position=CURRENT_EXPERIMENT['plot_x_position']) else: plot = MatPlot(subplots=(1, num_subplots)) def _create_plot(plot, i, name, data, counter_two, j, k): """ Args: plot: The plot object, either QtPlot() or MatPlot() i: The parameter to measure name: - data: The DataSet of the current measurement counter_two: The sub-measurement counter. Each measurement has a number and each sub-measurement has a counter. j: The current sub-measurement k: - """ color = 'C' + str(counter_two) if issubclass( i.__class__, MultiChannelInstrumentParameter) or i._instrument is None: inst_meas_name = name else: parent_instr_name = (i._instrument.name + '_') if i._instrument else '' inst_meas_name = "{}{}".format(parent_instr_name, name) try: inst_meas_data = getattr(data, inst_meas_name) except AttributeError: inst_meas_name = "{}{}_0_0".format(parent_instr_name, name) inst_meas_data = getattr(data, inst_meas_name) inst_meta_data = __get_plot_type(inst_meas_data, plot) if useQT: plot.add(inst_meas_data, subplot=j + k + 1) plot.subplots[j + k].showGrid(True, True) if j == 0: plot.subplots[0].setTitle(title) else: plot.subplots[j + k].setTitle("") plot.fixUnitScaling(startranges) QtPlot.qc_helpers.foreground_qt_window(plot.win) else: if 'z' in inst_meta_data: xlen, ylen = inst_meta_data['z'].shape rasterized = xlen * ylen > 5000 po = plot.add(inst_meas_data, subplot=j + k + 1, rasterized=rasterized) auto_color_scale_from_config(po.colorbar, auto_color_scale, inst_meta_data['z'], cutoff_percentile) else: rasterized = False plot.add(inst_meas_data, subplot=j + k + 1, color=color) plot.subplots[j + k].grid() if j == 0: if rasterized: fulltitle = title + rasterized_note else: fulltitle = title plot.subplots[0].set_title(fulltitle) else: if rasterized: fulltitle = rasterized_note else: fulltitle = "" plot.subplots[j + k].set_title(fulltitle) subplot_index = 0 for measurement in inst_meas: if getattr(measurement, "names", False): # deal with multidimensional parameter for name in measurement.names: _create_plot(plot, measurement, name, data, counter_two, subplot_index, 0) subplot_index += 1 counter_two += 1 else: # simple_parameters _create_plot(plot, measurement, measurement.name, data, counter_two, subplot_index, 0) subplot_index += 1 counter_two += 1 return plot, num_subplots
def test_creation(self): """ Simple test function which created a MatPlot window """ plotM = MatPlot(interval=0) plt.close(plotM.fig)
fitting_point = 51 x = np.linspace(0, 1.5e-6, fitting_point)[:fitting_point] y = ds.probability_data[:, i, 0:fitting_point].mean(axis=0) pars, pcov = curve_fit(T2_star_fitting, x, y, p0=(0.8, 0.3, 4e6, 0, 0.5e-6), bounds=((0.25, -np.inf, 1e6, -np.inf, 0), (2, np.inf, 10e6, np.inf, 5))) #pars, pcov = curve_fit(T2_star_fitting2, x, y, # p0 = (0.8, 0.3, 0.5e-6), # bounds = ((0.25,-np.inf,0),(2,np.inf,8e-6))) #%% pt = MatPlot() #pt.add(x = x, y = T1_fitting(x,pars[0],pars[1],pars[2])) pt.add(x=x, y=T2_star_fitting(x, pars[0], pars[1], pars[2], pars[3], pars[4])) #pt.add(x = x, y = T2_star_fitting2(x,pars[0],pars[1],pars[2])) pt.add(x=x, y=ds.probability_data[:, i, start_point:start_point + fitting_point].mean(axis=0)) print('T1 is: ', pars[0] * 1000, 'ms') #pt1 = MatPlot() #pt1.add_to_plot(x = x, y = T1_fitting(x,pars[0],pars[1],pars[2]),fmt='*') #%%
def show_num(ids, samplefolder=None, useQT=False, avg_sub='', do_plots=True, savepng=True, fig_size=[6, 4], clim=None, dataname=None, xlim=None, ylim=None, transpose=False, auto_color_scale: Optional[bool] = None, cutoff_percentile: Optional[Union[Tuple[Number, Number], Number]] = None, **kwargs): """ Show and return plot and data. Args: ids (number, list): id or list of ids of dataset(s) samplefolder (str): Sample folder if loading data from different sample than the initialized. useQT (boolean): If true plots with QTplot instead of matplotlib avg_sub (str: 'col' or 'row'): Subtracts average from either each collumn ('col') or each row ('row') do_plots: (boolean): if false no plots are produced. dataname (str): If given only plots dataset with that name savepng (boolean): If true saves matplotlib figure as png fig_size [6,4]: Figure size in inches clim [cmin,cmax]: Set min and max of colorbar to cmin and cmax respectrively xlim [xmin,xmax]: Set limits on x axis ylim [ymin,ymax]: set limits on y axis transpose (boolean): Transpose data to be plotted (only works for 2D scans and qc.MatPlot) auto_color_scale: if True, the colorscale of heatmap plots will be automatically adjusted to disregard outliers. cutoff_percentile: percentile of data that may maximally be clipped on both sides of the distribution. If given a tuple (a,b) the percentile limits will be a and 100-b. See also the plotting tuorial notebook. **kwargs: Are passed to plot function Returns: data, plots : returns the plots and the datasets """ # default values if auto_color_scale is None: auto_color_scale = qcodes.config.plotting.auto_color_scale.enabled if cutoff_percentile is None: cutoff_percentile = cast( Tuple[Number, Number], tuple(qcodes.config.plotting.auto_color_scale.cutoff_percentile)) if not isinstance(ids, collections.Iterable): ids = (ids, ) data_list = [] keys_list = [] # Define samplefolder if samplefolder == None: check_experiment_is_initialized() samplefolder = qc.DataSet.location_provider.fmt.format(counter='') # Load all datasets into list for id in ids: path = samplefolder + '{0:03d}'.format(id) data = qc.load_data(path) data_list.append(data) # find datanames to be plotted if do_plots: if useQT and len(ids) is not 1: raise ValueError( 'qcodes.QtPlot does not support multigraph plotting. Set useQT=False to plot multiple datasets.' ) if dataname is not None: if dataname not in [ key for key in data.arrays.keys() if "_set" not in key ]: raise RuntimeError('Dataname not in dataset. Input dataname was: \'{}\''.format(dataname), \ 'while dataname(s) in dataset are: \'{}\'.'.format('\', \''.join(data.arrays.keys()))) keys = [dataname] else: keys = [key for key in data.arrays.keys() if "_set" not in key] keys_list.append(keys) if do_plots: unique_keys = list( set([item for sublist in keys_list for item in sublist])) plots = [] num = '' l = len(unique_keys) for j, key in enumerate(unique_keys): array_list = [] xlims = [[], []] ylims = [[], []] clims = [[], []] # Find datasets containing data with dataname == key for data, keys in zip(data_list, keys_list): if key in keys: arrays = getattr(data, key) if transpose and len(arrays.set_arrays) == 2: if useQT: raise AttributeError( 'Transpose only works for qc.MatPlot.') if dataname is None and l != 1: raise ValueError( 'Dataname has to be provided to plot data transposed for dataset with more ' 'than 1 measurement. Datanames in dataset are: \'{}\'.' .format('\', \''.join(unique_keys))) arrays.ndarray = arrays.ndarray.T set0_temp = arrays.set_arrays[0] set1_temp = arrays.set_arrays[1] set0_temp.ndarray = set0_temp.ndarray.T set1_temp.ndarray = set1_temp.ndarray.T arrays.set_arrays = ( set1_temp, set0_temp, ) if avg_sub == 'row': for i in range(np.shape(arrays.ndarray)[0]): arrays.ndarray[i, :] -= np.nanmean( arrays.ndarray[i, :]) if avg_sub == 'col': for i in range(np.shape(arrays.ndarray)[1]): arrays.ndarray[:, i] -= np.nanmean(arrays.ndarray[:, i]) array_list.append(arrays) # Find axis limits for dataset if len(arrays.set_arrays) == 2: xlims[0].append(np.nanmin(arrays.set_arrays[1])) xlims[1].append(np.nanmax(arrays.set_arrays[1])) ylims[0].append(np.nanmin(arrays.set_arrays[0])) ylims[1].append(np.nanmax(arrays.set_arrays[0])) if auto_color_scale: vlims = auto_range_iqr(arrays.ndarray) else: vlims = (np.nanmin(arrays.ndarray), np.nanmax(arrays.ndarray)) clims[0].append(vlims[0]) clims[1].append(vlims[1]) else: xlims[0].append(np.nanmin(arrays.set_arrays[0])) xlims[1].append(np.nanmax(arrays.set_arrays[0])) ylims[0].append(np.nanmin(arrays.ndarray)) ylims[1].append(np.nanmax(arrays.ndarray)) if useQT: plot = QtPlot( array_list[0], fig_x_position=CURRENT_EXPERIMENT['plot_x_position'], **kwargs) title = "{} #{}".format(CURRENT_EXPERIMENT["sample_name"], '{}'.format(ids[0])) plot.subplots[0].setTitle(title) plot.subplots[0].showGrid(True, True) if savepng: print('Save plot only working for matplotlib figure.', \ 'Set useQT=False to save png.') else: plot = MatPlot(array_list, **kwargs) plot.rescale_axis() plot.fig.tight_layout(pad=3) plot.fig.set_size_inches(fig_size) # Set axis limits if xlim is None: plot[0].axes.set_xlim( [np.nanmin(xlims[0]), np.nanmax(xlims[1])]) else: plot[0].axes.set_xlim(xlim) if ylim is None: plot[0].axes.set_ylim( [np.nanmin(ylims[0]), np.nanmax(ylims[1])]) else: plot[0].axes.set_ylim(ylim) if len(arrays.set_arrays) == 2: total_clim = [None, None] for i in range(len(array_list)): # TODO(DV): get colorbar from plot children (should be ax.qcodes_colorbar) if clim is None: internal_clim = np.nanmin(clims[0]), np.nanmax( clims[1]) else: internal_clim = clim if total_clim[0] is None or internal_clim[ 0] < total_clim[0]: total_clim[0] = internal_clim[0] if total_clim[1] is None or internal_clim[ 1] > total_clim[1]: total_clim[1] = internal_clim[1] colorbar = plot[0].qcodes_colorbar apply_color_scale_limits(colorbar, new_lim=tuple(total_clim)) # Set figure titles plot.fig.suptitle(samplefolder) if len(ids) < 6: plot.subplots[0].set_title(', '.join(map(str, ids))) else: plot.subplots[0].set_title(' - '.join( map(str, [ids[0], ids[-1]]))) plt.draw() # Save figure if savepng: if len(ids) == 1: title_png = samplefolder + CURRENT_EXPERIMENT[ 'png_subfolder'] + sep + '{}'.format(ids[0]) else: title_png = samplefolder + CURRENT_EXPERIMENT[ 'png_subfolder'] + sep + '{}-{}'.format( ids[0], ids[-1]) if l > 1: num = '{}'.format(j + 1) plt.savefig(title_png + '_{}_{}.png'.format(num, avg_sub), dpi=500) plots.append(plot) else: plots = None return data_list, plots