def __init__(self,
                 instruments,
                 scripts,
                 name=None,
                 settings=None,
                 log_function=None,
                 data_path=None):
        """
        Standard script initialization
        Args:
            name (optional): name of script, if empty same as class name
            settings (optional): settings for this script, if empty same as default settings
        """
        self._DEFAULT_SETTINGS += PulseBlasterBaseScript._DEFAULT_SETTINGS

        Script.__init__(self,
                        name,
                        settings=settings,
                        scripts=scripts,
                        instruments=instruments,
                        log_function=log_function,
                        data_path=data_path)
Beispiel #2
0
def visualize_magnetic_fields(folder,
                              manual=True,
                              legend_location='upper right',
                              bbox_to_anchor=(1, 1),
                              scatter_plot_axis='x',
                              line_points=None):
    """
    Creates, plots, and saves two plots of NV data. The first is a plot of the fluoresence image, with a tag on each NV
    indicating whether it is split or unsplit. The second is a plot of the magnitude of the splitting and associated
    magnetic field vs the NV x coordinate.

    Args:
        folder: folder of original data
        manual: True if manual processing has been done first, such as by process_esrs in
                b26_toolkit.src.data_analysis.esr_post_processing. False if only the raw data should be used.
        legend_location: location of legend in plot, using standard matplotlib location tags. Use this argument to move
                         the legend if it covers the NVs.

    """
    # load the fit_data
    if manual:
        df = pd.read_csv(os.path.join('./==processed==',
                                      '{:s}/data-manual.csv'.format(folder)),
                         index_col='id',
                         skipinitialspace=True)
    else:
        df = pd.read_csv(os.path.join(
            folder, '{:s}.csv'.format(folder.split('./')[1].replace('/',
                                                                    '-'))),
                         index_col='id',
                         skipinitialspace=True)
    df = df.drop('Unnamed: 0', 1)

    # include manual corrections
    if manual:
        for id, nv_type in enumerate(df['manual_nv_type']):
            if not pd.isnull(nv_type):
                df.set_value(id, 'NV type', nv_type)
                if nv_type == 'split':
                    df.set_value(id, 'B-field (gauss)',
                                 df.get_value(id, 'manual_B_field'))

    # load the image data
    select_points_data = Script.load_data(get_select_points(folder))
    image_data = select_points_data['image_data']
    #     points_data = select_points_data['nv_locations']
    extent = select_points_data['extent']

    pt1x = widgets.FloatText(description='upper point x')
    pt1y = widgets.FloatText(description='upper point y')
    pt2x = widgets.FloatText(description='lower point x')
    pt2y = widgets.FloatText(description='lower point y')

    display(pt1x)
    display(pt1y)
    display(pt2x)
    display(pt2y)

    # prepare figure
    f = plt.figure(figsize=(15, 8))
    gs = gridspec.GridSpec(1, 2, height_ratios=[1, 1])
    ax0 = plt.subplot(gs[0])
    ax1 = plt.subplot(gs[1])

    def onclick(event):
        if event.button == 1:
            pt1x.value = event.xdata
            pt1y.value = event.ydata
        elif event.button == 3:
            pt2x.value = event.xdata
            pt2y.value = event.ydata

    cid = f.canvas.mpl_connect('button_press_event', onclick)

    # plot the map
    ax0.imshow(image_data, extent=extent, interpolation='nearest', cmap='pink')

    for nv_type, color in zip(['split', 'bad', 'no_peak', 'single'],
                              ['g', 'k', 'b', 'r']):
        subset = df[df['NV type'] == nv_type]
        ax0.scatter(subset['xo'], subset['yo'], c=color, label=nv_type)

    ax0.legend(loc=legend_location, bbox_to_anchor=bbox_to_anchor)

    subset = df[df['NV type'] == 'split']
    for i, j, n in zip(subset['xo'], subset['yo'], subset.index):
        corr = +0.005  # adds a little correction to put annotation in marker's centrum
        ax0.annotate(str(n), xy=(i + corr, j + corr), fontsize=8, color='w')
    ax0.set_xlabel('x (V)')
    ax0.set_ylabel('y (V)')

    # plot the fields on a 1D plot
    subset = df[df['NV type'] == 'split']
    if scatter_plot_axis == 'x':
        x_coor = subset['xo']
    elif scatter_plot_axis == 'y':
        x_coor = subset['yo']
    elif scatter_plot_axis == 'line':
        pt1 = line_points[0]
        pt2 = line_points[1]
        x_coor = []
        for x, y in zip(subset['xo'], subset['yo']):
            x_coor.append(distance_point_to_line([x, y], pt1, pt2))
    ax1.plot(x_coor, subset['B-field (gauss)'] / freq_to_mag * 1e-6, 'go')

    for i, j, n in zip(x_coor, subset['B-field (gauss)'] / freq_to_mag * 1e-6,
                       subset.index):
        corr = 0.0005  # adds a little correction to put annotation in marker's centrum
        ax1.annotate(str(n), xy=(i + corr, j + corr))

    subset = df[df['NV type'] == 'single']
    for i, j, n in zip(subset['xo'], subset['yo'], subset.index):
        corr = +0.005  # adds a little correction to put annotation in marker's centrum
        ax0.annotate(str(n), xy=(i + corr, j + corr), fontsize=8, color='w')

    subset = df[df['NV type'] == 'single']
    subset_dict = {'xo': [], 'yo': [], 'B-field (gauss)': [], 'index': []}
    for nv in subset.iterrows():
        if 'fit_4' in nv[1]:
            subset_dict['xo'].append(nv[1][9])
            subset_dict['yo'].append(nv[1][11])
        else:
            subset_dict['xo'].append(nv[1][7])
            subset_dict['yo'].append(nv[1][9])
        subset_dict['index'].append(nv[0])
        if np.isnan(nv[1][6]) and ((nv[1][4]) > 2.92e9 or (nv[1][4]) < 2.82e9):
            subset_dict['B-field (gauss)'].append(
                (nv[1][4] - 2.87e9) * 2 * freq_to_mag)
        else:
            subset_dict['B-field (gauss)'].append(0)

    if scatter_plot_axis == 'x':
        print('HERE')
        x_coor = subset_dict['xo']
    elif scatter_plot_axis == 'y':
        x_coor = subset_dict['yo']
    elif scatter_plot_axis == 'line':
        pt1 = line_points[0]
        pt2 = line_points[1]
        x_coor = []
        for x, y in zip(subset_dict['xo'], subset_dict['yo']):
            x_coor.append(distance_point_to_line([x, y], pt1, pt2))
    ax1.plot(x_coor,
             np.array(subset_dict['B-field (gauss)']) / freq_to_mag * 1e-6,
             'ro')

    for i, j, n in zip(
            x_coor,
            np.array(subset_dict['B-field (gauss)']) / freq_to_mag * 1e-6,
            subset_dict['index']):
        corr = 0.0005  # adds a little correction to put annotation in marker's centrum
        ax1.annotate(str(n), xy=(i + corr, j + corr))

    ax1.set_title('ESR Splittings')
    if scatter_plot_axis == 'x':
        ax1.set_xlabel('x coordinate (V)')
    if scatter_plot_axis == 'y':
        ax1.set_xlabel('y coordinate (V)')
    if scatter_plot_axis == 'line':
        ax1.set_xlabel('Distance to magnet edge (V)')
    ax1.set_ylabel('Splitting (MHz)')
    if not scatter_plot_axis == 'line':
        ax1.set_xlim([extent[0], extent[1]])

    plt.axvline(x=0, color='black', linestyle='dashed', linewidth=2)

    ax2 = ax1.twinx()
    mn, mx = ax1.get_ylim()
    ax2.set_ylim(mn * freq_to_mag * 1e6, mx * freq_to_mag * 1e6)
    ax2.set_ylabel('Magnetic Field Projection (Gauss)')

    # f.set_tight_layout(True)

    print(
        'path',
        os.path.join('./==processed==', folder[2:],
                     'splittings_plot.jpg'.format(os.path.basename(folder))))

    f.savefig(os.path.join(
        './==processed==', folder[2:],
        'splittings_plot.jpg'.format(os.path.basename(folder))),
              bbox_inches='tight',
              pad_inches=0)
        if not delete_list == []:
            delete_list.reverse()
            for index in delete_list:
                pulse_sequences.pop(index)

        # print('delete taus from list:')
        # print(delete_list)
        tau_list = np.delete(np.array(tau_list), delete_list).tolist()

        return pulse_sequences, num_averages, tau_list, measurement_gate_width

    def stop(self):
        """
        Stop currently executed pulse blaster sequence
        NOT CURRENTLY WORKING, WILL CRASH PULSEBLASTER
        """
        # self.instruments['PB']['instance'].stop()
        super(PulseBlasterBaseScript, self).stop()


if __name__ == '__main__':
    script = {}
    instr = {}
    script, failed, instr = Script.load_and_append(
        {'ExecutePulseBlasterSequence': 'ExecutePulseBlasterSequence'}, script,
        instr)

    print(script)
    print(failed)
    print(instr)
Beispiel #4
0
def perform_affine_transform(img_path_old, img_path_new, done_queue,
                             return_queue):
    import time

    pt11_widget = widgets.HTML("Pt 1: 0,0")
    pt12_widget = widgets.HTML("Pt 2: 0,0")
    pt13_widget = widgets.HTML("Pt 3: 0,0")
    pt21_widget = widgets.HTML("Pt 1: 0,0")
    pt22_widget = widgets.HTML("Pt 2: 0,0")
    pt23_widget = widgets.HTML("Pt 3: 0,0")

    display(pt11_widget)
    display(pt12_widget)
    display(pt13_widget)
    display(pt21_widget)
    display(pt22_widget)
    display(pt23_widget)

    #     f = plt.figure(figsize=(12, 6))

    #     ax0 = plt.subplot(121)
    #     ax1 = plt.subplot(122)

    f = plt.figure(figsize=(16, 8))
    gs = gridspec.GridSpec(1, 2, width_ratios=[1, 2])
    ax0 = plt.subplot(gs[0])
    ax1 = plt.subplot(gs[1])

    def onclick_old(event):
        if ax0.in_axes(event):
            if event.key == '1':
                pt11_widget.value = 'Pt 1: ' + str(event.xdata) + ',' + str(
                    event.ydata)
            elif event.key == '2':
                pt12_widget.value = 'Pt 2: ' + str(event.xdata) + ',' + str(
                    event.ydata)
            elif event.key == '3':
                pt13_widget.value = 'Pt 3: ' + str(event.xdata) + ',' + str(
                    event.ydata)
        elif ax1.in_axes(event):
            if event.key == '1':
                pt21_widget.value = 'Pt 1: ' + str(event.xdata) + ',' + str(
                    event.ydata)
            elif event.key == '2':
                pt22_widget.value = 'Pt 2: ' + str(event.xdata) + ',' + str(
                    event.ydata)
            elif event.key == '3':
                pt23_widget.value = 'Pt 3: ' + str(event.xdata) + ',' + str(
                    event.ydata)

    cid = f.canvas.mpl_connect('button_press_event', onclick_old)

    data_im_old = Script.load_data(img_path_old)
    image_old = data_im_old['image_data']
    extent_old = data_im_old['extent']
    nv_pts_old = data_im_old['nv_locations']

    plot_fluorescence_new(image_old, extent_old, ax0)
    f.get_axes()[2].remove()

    data_im_new = Script.load_data(img_path_new)
    image_new = data_im_new['image_data']
    extent_new = data_im_new['extent']
    nv_pts_new = data_im_new['nv_locations']

    plot_fluorescence_new(image_new, extent_new, ax1)
    f.get_axes()[2].remove()

    plt.show()

    while done_queue.empty():
        time.sleep(.5)

    pt11 = map(
        float,
        pt11_widget.value.replace(" ", "").replace(':', ',').split(',')[1:3])
    pt12 = map(
        float,
        pt12_widget.value.replace(" ", "").replace(':', ',').split(',')[1:3])
    pt13 = map(
        float,
        pt13_widget.value.replace(" ", "").replace(':', ',').split(',')[1:3])
    pt21 = map(
        float,
        pt21_widget.value.replace(" ", "").replace(':', ',').split(',')[1:3])
    pt22 = map(
        float,
        pt22_widget.value.replace(" ", "").replace(':', ',').split(',')[1:3])
    pt23 = map(
        float,
        pt23_widget.value.replace(" ", "").replace(':', ',').split(',')[1:3])

    Avec = calc_transform_matrix((pt11, pt12, pt13), (pt21, pt22, pt23))
    Amat = [[Avec[0], Avec[1], Avec[2]], [Avec[3], Avec[4], Avec[5]],
            [0, 0, 1]]

    shifted_nv_pts_old = []

    for pt in nv_pts_old:
        circ = patches.Circle((pt[0], pt[1]), .0005, fc='k', ec='k')
        ax0.add_patch(circ)

        vec = [pt[0], pt[1], 1]
        vec_prime = np.dot(Amat, vec)

        circ = patches.Circle((vec_prime[0], vec_prime[1]),
                              .0005,
                              fc='k',
                              ec='k')
        ax1.add_patch(circ)

        shifted_nv_pts_old.append([vec_prime[0], vec_prime[1]])

    for pt in nv_pts_new:
        circ = patches.Circle((pt[0], pt[1]), .0005, fc='g', ec='g')
        ax1.add_patch(circ)

    tree = scipy.spatial.KDTree(shifted_nv_pts_old)
    _, new_to_old_map = tree.query(nv_pts_new, distance_upper_bound=.005)
    #kd tree returns value of len(new_to_old_map) if no match found, change this to -1
    new_to_old_map = [
        x if x != len(nv_pts_old) else -1 for x in new_to_old_map
    ]

    return_queue.put(new_to_old_map)