예제 #1
0
def plot_find_nv_pos(path, convert_to_um=True):
    '''


    Args:
        path: the filename of the
        convert_to_um:

    Returns:

    '''
    findnv_paths = glob.glob(
        os.path.abspath(path +
                        '/data_subscripts/*/data_subscripts/*find_nv*/'))
    findnv_paths += glob.glob(
        os.path.abspath(path + '/data_subscripts/*find_nv*'))
    x = []
    y = []
    datetimes = []
    for p in findnv_paths:
        data = Script.load_data(p)
        #     print(data['maximum_point']['x'])
        x.append(data['maximum_point']['x'])
        y.append(data['maximum_point']['y'])
        datetimes.append(Script.load_time(os.path.basename(p)))
    t0 = datetimes[0]
    t = [date - t0 for date in datetimes]
    times = [temp_time.seconds / (60 * 60)
             for temp_time in t]  # convert times to hours
    x = np.array(x) - np.mean(np.array(x))
    y = np.array(y) - np.mean(np.array(y))

    if convert_to_um:
        x = x * V_to_dist
        y = y * V_to_dist

    labeltime = 'time (hrs)'
    labely = 'y position '
    labelx = 'x position'
    if convert_to_um:
        labely += '(um)'
        labelx += '(um)'
    else:
        labely += '(V)'
        labelx += '(V)'

    fig, ax = plt.subplots(1, 3, figsize=(20, 4))
    ax[0].plot(times, x, marker='o', linestyle='')
    ax[0].set_xlabel(labeltime)
    ax[0].set_ylabel(labelx)
    ax[1].plot(times, y, marker='o', linestyle='')
    ax[1].set_xlabel(labeltime)
    ax[1].set_ylabel(labely)
    ax[2].plot(x, y, marker='o', linestyle='')
    ax[2].set_xlabel(labelx)
    ax[2].set_ylabel(labely)

    return x, y
예제 #2
0
def plot_find_nv_pos(path, convert_to_um=True):
    '''


    Args:
        path: the filename of the
        convert_to_um:

    Returns:

    '''
    findnv_paths = glob.glob(os.path.abspath(path + '/data_subscripts/*/data_subscripts/*find_nv*/'))
    findnv_paths += glob.glob(os.path.abspath(path + '/data_subscripts/*find_nv*'))
    x = []
    y = []
    datetimes = []
    for p in findnv_paths:
        data = Script.load_data(p)
        #     print(data['maximum_point']['x'])
        x.append(data['maximum_point']['x'])
        y.append(data['maximum_point']['y'])
        datetimes.append(Script.load_time(os.path.basename(p)))
    t0 = datetimes[0]
    t = [date - t0 for date in datetimes]
    times = [temp_time.seconds/(60*60) for temp_time in t]# convert times to hours
    x = np.array(x)-np.mean(np.array(x))
    y = np.array(y)-np.mean(np.array(y))

    if convert_to_um:
        x = x*V_to_dist
        y = y*V_to_dist

    labeltime = 'time (hrs)'
    labely = 'y position '
    labelx = 'x position'
    if convert_to_um:
        labely += '(um)'
        labelx += '(um)'
    else:
        labely += '(V)'
        labelx += '(V)'

    fig, ax = plt.subplots(1, 3, figsize = (20, 4))
    ax[0].plot(times, x, marker='o', linestyle='')
    ax[0].set_xlabel(labeltime)
    ax[0].set_ylabel(labelx)
    ax[1].plot(times, y, marker='o', linestyle='')
    ax[1].set_xlabel(labeltime)
    ax[1].set_ylabel(labely)
    ax[2].plot(x, y, marker='o', linestyle='')
    ax[2].set_xlabel(labelx)
    ax[2].set_ylabel(labely)

    return x, y
예제 #3
0
def plot_2d_rabi_vs_powers(RABI_FOLDER):
    '''

    Args:
        RABI_FOLDER: folder with the rabi data to use

    Returns:
        rabi_data: rabi contrast APD output 2 / APD output 1 versus tau
        taus: tau values in the rabi sweep
        powers: power values used in the 2D sweep, in dBm

    '''

    rabi_data = []
    taus = []
    powers = []
    for f in sorted(glob.glob('{:s}/data_subscripts/*'.format(RABI_FOLDER))):
        data = Script.load_data(f)
        if 'tau' not in data or data is None: # not a Rabi folder (e.g., find_nv instead)
            continue
        cnts = np.transpose(data['counts'])
        cnts1 = cnts[1]
        cnts0 = cnts[0]
        single_rabi_data = cnts1/cnts0
        rabi_data.append(single_rabi_data)
        taus = data['tau']
        power = float(f.split('_')[-1])
        powers.append(power)
    rabi_data = np.array(rabi_data)[np.argsort(powers)]
    powers = np.sort(np.array(powers))
    plt.pcolormesh(taus, powers, rabi_data)
    plt.xlabel('tau values (ns)')
    plt.ylabel('input power (dBm)')

    return rabi_data, taus, powers
예제 #4
0
def plot_2d_rabi_vs_powers(RABI_FOLDER):
    '''

    Args:
        RABI_FOLDER: folder with the rabi data to use

    Returns:
        rabi_data: rabi contrast APD output 2 / APD output 1 versus tau
        taus: tau values in the rabi sweep
        powers: power values used in the 2D sweep, in dBm

    '''

    rabi_data = []
    taus = []
    powers = []
    for f in sorted(glob.glob('{:s}/data_subscripts/*'.format(RABI_FOLDER))):
        data = Script.load_data(f)
        if 'tau' not in data or data is None:  # not a Rabi folder (e.g., find_nv instead)
            continue
        cnts = np.transpose(data['counts'])
        cnts1 = cnts[1]
        cnts0 = cnts[0]
        single_rabi_data = cnts1 / cnts0
        rabi_data.append(single_rabi_data)
        taus = data['tau']
        power = float(f.split('_')[-1])
        powers.append(power)
    rabi_data = np.array(rabi_data)[np.argsort(powers)]
    powers = np.sort(np.array(powers))
    plt.pcolormesh(taus, powers, rabi_data)
    plt.xlabel('tau values (ns)')
    plt.ylabel('input power (dBm)')

    return rabi_data, taus, powers
예제 #5
0
def plot_esr_contrast_vs_power(ESR_FOLDER):  # ER 20190130
    '''

    Plots the fit contrast found for each ESR spectrum on the y axis, and the SRS power on the x axis.

    Args:
        ESR_FOLDER: the folder corresponding to the data you want to plot.
        in_expt_file: whether or not the ESR data to plot is within the subscript of a 'higher level' experiment folder / data
        exp_str: string to search for when finding the ESR data. For example, for hahn echo this could be 'hahn_echo' or 'he'
            depending on what the user put as the 'tag' for the hahn echo data. The script then finds all esr data WITHIN
            the data folders / data_subscripts with the tag 'hahn_echo' or 'he'.

    '''

    fit_contrast = []
    powers = []
    paths = []
    paths = glob.glob('{:s}/data_subscripts/*'.format(ESR_FOLDER))
    paths += glob.glob(
        '{:s}/data_subscripts/*/data_subscripts/*esr*'.format(ESR_FOLDER))
    for f in sorted(paths):
        data = Script.load_data(f)
        if data is None or 'esr_data' not in data:  # not an ESR folder (e.g., find_nv instead)
            continue
        fit_params = data['fit_params']
        if fit_params is not None and len(
                fit_params) and fit_params[0] != -1:  # check if fit valid
            if len(fit_params) == 4:
                # single peak
                fit_contrast.append(100 *
                                    np.abs(fit_params[1] / fit_params[0]))
                #   times.append(return_times(f, with_power_sweep=True))
                powers.append(float(f[-9:]))

            elif len(fit_params) == 6:
                # double peak, don't update the frequency - the fit may be bad
                continue

    print('powers: ', powers)
    powers = -np.array(powers)
    fit_contrast = np.array(fit_contrast)
    plt.figure()

    # ER 20190130 temporary
    #tmp_widths = fit_widths[1:]
    tmp_widths = [fit_contrast[i + 1] for i in [0, 1, 2, 5, 7, 8]]
    tmp_powers = [powers[i + 1] for i in [0, 1, 2, 5, 7, 8]]
    plt.plot(tmp_powers, tmp_widths, linestyle='', marker='o')

    #plt.plot(powers, fit_contrast, linestyle='', marker='o')
    plt.xlabel('SRS power (dBm)')
    plt.ylabel('ESR contrast (%)')
    plt.title('ESR contrast vs. SRS power')
예제 #6
0
def plot_esr_fit_vs_time(ESR_FOLDER):  # ER 20181211
    '''

    Plots the fit frequency found for each ESR spectrum on the y axis, and the time the ESR data was taken relative to the
    start of the experiment on the x axis.

    Args:
        ESR_FOLDER: the folder corresponding to the data you want to plot.
        in_expt_file: whether or not the ESR data to plot is within the subscript of a 'higher level' experiment folder / data
        exp_str: string to search for when finding the ESR data. For example, for hahn echo this could be 'hahn_echo' or 'he'
            depending on what the user put as the 'tag' for the hahn echo data. The script then finds all esr data WITHIN
            the data folders / data_subscripts with the tag 'hahn_echo' or 'he'.

    '''

    fit_freqs = []
    times = []
    paths = []
    paths = glob.glob('{:s}/data_subscripts/*'.format(ESR_FOLDER))
    paths += glob.glob(
        '{:s}/data_subscripts/*/data_subscripts/*esr*'.format(ESR_FOLDER))
    for f in sorted(paths):
        data = Script.load_data(f)
        if data is None or 'esr_data' not in data:  # not an ESR folder (e.g., find_nv instead)
            continue
        fit_params = data['fit_params']
        if fit_params is not None and len(
                fit_params) and fit_params[0] != -1:  # check if fit valid
            if len(fit_params) == 4:
                # single peak
                fit_freqs.append(fit_params[2])
                times.append(return_times(f, with_power_sweep=True))
            elif len(fit_params) == 6:
                # double peak, don't update the frequency - the fit may be bad
                continue

    times = np.array(times)
    times = times - times[0]
    times = times[1:]
    fit_freqs = np.array(fit_freqs) / 1.e6
    plt.figure()

    # ER 20190130 temporary
    tmp_freqs = fit_freqs[1:]
    tmp_freqs = [tmp_freqs[i] for i in [0, 1, 2, 5, 7, 8]]
    tmp_times = [times[i] for i in [0, 1, 2, 5, 7, 8]]
    plt.plot(tmp_times, tmp_freqs, linestyle='', marker='o')

    # plt.plot(times, fit_freqs[1:], linestyle='', marker='o')
    plt.xlabel('time (hours)')
    plt.ylabel('fit frequency (MHz)')
    plt.title('ESR center fit frequency vs. time')
예제 #7
0
def plot_2d_fft_rabi_vs_powers(RABI_FOLDER,
                               xlog=False,
                               ylog=False,
                               freq_range=None):
    '''

    Args:
        RABI_FOLDER: folder with the rabi data to use

    Returns:
        rabi_data: rabi contrast APD output 2 / APD output 1 versus tau
        taus: tau values in the rabi sweep
        powers: power values used in the 2D sweep, in dBm

    '''

    rabi_data = []
    taus = []
    powers = []
    freqs = []
    for f in sorted(glob.glob('{:s}/data_subscripts/*'.format(RABI_FOLDER))):
        data = Script.load_data(f)
        if 'tau' not in data or data is None:  # not a Rabi folder (e.g., find_nv instead)
            continue
        cnts = np.transpose(data['counts'])
        cnts1 = cnts[1]
        cnts0 = cnts[0]
        single_rabi_data = cnts1 / cnts0
        taus = data['tau']

        single_rabi_data -= np.mean(single_rabi_data)
        freqs, single_rabi_data = power_spectral_density(
            single_rabi_data, (taus[1] - taus[0]) * 1e-9,
            freq_range=freq_range)

        if ylog:
            single_rabi_data = np.log10(single_rabi_data)
        rabi_data.append(single_rabi_data)
        power = float(f.split('_')[-1])
        powers.append(power)

    if xlog:
        freqs += 1
        freqs = np.log10(freqs)
        print(freqs)

    rabi_data = np.array(rabi_data)[np.argsort(powers)]
    powers = np.sort(np.array(powers))
    plt.pcolormesh(freqs, powers, rabi_data)
    plt.xlabel('frequencies (Hz)')
    plt.ylabel('input power (dBm)')
예제 #8
0
def plot_2d_fft_rabi_vs_powers(RABI_FOLDER, xlog=False, ylog = False, freq_range = None):
    '''

    Args:
        RABI_FOLDER: folder with the rabi data to use

    Returns:
        rabi_data: rabi contrast APD output 2 / APD output 1 versus tau
        taus: tau values in the rabi sweep
        powers: power values used in the 2D sweep, in dBm

    '''

    rabi_data = []
    taus = []
    powers = []
    freqs = []
    for f in sorted(glob.glob('{:s}/data_subscripts/*'.format(RABI_FOLDER))):
        data = Script.load_data(f)
        if 'tau' not in data or data is None: # not a Rabi folder (e.g., find_nv instead)
            continue
        cnts = np.transpose(data['counts'])
        cnts1 = cnts[1]
        cnts0 = cnts[0]
        single_rabi_data = cnts1/cnts0
        taus = data['tau']

        single_rabi_data -= np.mean(single_rabi_data)
        freqs, single_rabi_data = power_spectral_density(single_rabi_data, (taus[1]-taus[0])*1e-9, freq_range=freq_range)

        if ylog:
            single_rabi_data = np.log10(single_rabi_data)
        rabi_data.append(single_rabi_data)
        power = float(f.split('_')[-1])
        powers.append(power)

    if xlog:
        freqs += 1
        freqs = np.log10(freqs)
        print(freqs)

    rabi_data = np.array(rabi_data)[np.argsort(powers)]
    powers = np.sort(np.array(powers))
    plt.pcolormesh(freqs, powers, rabi_data)
    plt.xlabel('frequencies (Hz)')
    plt.ylabel('input power (dBm)')
예제 #9
0
def get_pts(PTS_FOLDER, counter, flip = False):
    '''
    Get the points in real space of the scan. V_to_dist is the conversion factor from galvo voltage to a real distance

    flip: allows you to reverse the direction of the plot(e.g. towards or away from the iron/bead)

    '''
    data = Script.load_data(PTS_FOLDER)
    r = []
    for pt in data['nv_locations']:
        r.append( np.sqrt((pt[0]-data['nv_locations'][0][0])**2+(pt[1]-data['nv_locations'][0][1])**2))

    r = V_to_dist * np.array(r)
    r = r[0:counter] # truncate # of points to the actual number of data points taken
    if flip:
        r = np.flipud(r)
    return r
예제 #10
0
def get_pts(PTS_FOLDER, counter, flip=False):
    '''
    Get the points in real space of the scan. V_to_dist is the conversion factor from galvo voltage to a real distance

    flip: allows you to reverse the direction of the plot(e.g. towards or away from the iron/bead)

    '''
    data = Script.load_data(PTS_FOLDER)
    r = []
    for pt in data['nv_locations']:
        r.append(
            np.sqrt((pt[0] - data['nv_locations'][0][0])**2 +
                    (pt[1] - data['nv_locations'][0][1])**2))

    r = V_to_dist * np.array(r)
    r = r[
        0:
        counter]  # truncate # of points to the actual number of data points taken
    if flip:
        r = np.flipud(r)
    return r
예제 #11
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.pylabcontrol.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=4, 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=4, 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':
        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':
        if scatter_plot_axis == 'y':
            ax1.set_xlim([extent[3], extent[2]])
        else:
            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)
예제 #12
0
def get_freqs_and_data(ESR_FOLDER, plot_with_norm, esr_fixed=False, get_times=False, get_freqs=False):
    '''
    Get the frequencies of the ESR sweep as well as ESR contrast.

    ESR_FOLDER: folder with ESR data in it

    plot_with_norm: normalize to the photodiode signal (i.e. reflectted or incident laser power)

    esr_fixed: corresponds to data taken after we changed the name of the laser data in self.data, for when plot_with_norm is on.

    get_times: record and return the time duration of each ESR experiment.

    get_freqs: record and return the piezo frequency drive of each ESR experiment (see OneNotes from early Dec. 2018)

    '''
    data_esr = []
    times = []
    counter = 0  # use a counter to figure out the number of ESR points actually taken, to trunctate the real space coordinate to
    freqs = []
    paths = []
    paths = glob.glob('{:s}/data_subscripts/*esr*'.format(ESR_FOLDER))
    paths += glob.glob('{:s}/data_subscripts/*/data_subscripts/*esr*/'.format(ESR_FOLDER))

    # if plot_with_norm:
    #     for f in sorted(paths):
    #         data = Script.load_data(f)
    #         if 'esr_data' not in data or data is None: # not an ESR folder (e.g., find_nv instead)
    #             continue
    #         if not esr_fixed:
    #             full_data = np.divide(data['esr_data'], data['full_laser_data'])
    #         else:
    #             full_data = np.divide(data['esr_data'], data['laser_data'])
    #         data_esr.append(np.mean(full_data, axis=0))
    #         counter = counter + 1
    #
    #         if get_times:
    #             time = return_times(f, with_power_sweep=True)
    #             times.append(time)
    #
    #         if get_freqs:
    #             freqs.append(float(f[-9:]))

    for f in sorted(paths):
        data = Script.load_data(f)
        if data is None or 'esr_data' not in data: # not an ESR folder (e.g., find_nv instead)
            continue
        if plot_with_norm and not esr_fixed:
            full_data = np.divide(data['esr_data'], data['full_laser_data'])
            data_esr.append(np.mean(full_data, axis=0))

        elif plot_with_norm and esr_fixed:
            full_data = np.divide(data['esr_data'], data['laser_data'])
            data_esr.append(np.mean(full_data, axis=0))

        elif not plot_with_norm:
            data_esr.append(data['data'])

        counter = counter + 1

        if get_times:
            time = return_times(f, with_power_sweep=True)
            times.append(time)

        if get_freqs:
            freqs.append(float(f[-9:]))

    f = data['frequency']
    if not get_times and not get_freqs:
        return f, data_esr, counter
    elif get_times and not get_freqs:
        return f, data_esr, counter, times
    elif get_freqs and not get_times:
        return f, data_esr, counter, freqs
    elif get_freqs and get_times:
        return f, data_esr, counter, times, freqs
예제 #13
0
def get_freqs_and_data(ESR_FOLDER,
                       plot_with_norm,
                       esr_fixed=False,
                       get_times=False,
                       get_freqs=False):
    '''
    Get the frequencies of the ESR sweep as well as ESR contrast.

    ESR_FOLDER: folder with ESR data in it

    plot_with_norm: normalize to the photodiode signal (i.e. reflectted or incident laser power)

    esr_fixed: corresponds to data taken after we changed the name of the laser data in self.data, for when plot_with_norm is on.

    get_times: record and return the time duration of each ESR experiment.

    get_freqs: record and return the piezo frequency drive of each ESR experiment (see OneNotes from early Dec. 2018)

    '''
    data_esr = []
    times = []
    counter = 0  # use a counter to figure out the number of ESR points actually taken, to trunctate the real space coordinate to
    freqs = []
    paths = []
    paths = glob.glob('{:s}/data_subscripts/*esr*'.format(ESR_FOLDER))
    paths += glob.glob(
        '{:s}/data_subscripts/*/data_subscripts/*esr*/'.format(ESR_FOLDER))

    # if plot_with_norm:
    #     for f in sorted(paths):
    #         data = Script.load_data(f)
    #         if 'esr_data' not in data or data is None: # not an ESR folder (e.g., find_nv instead)
    #             continue
    #         if not esr_fixed:
    #             full_data = np.divide(data['esr_data'], data['full_laser_data'])
    #         else:
    #             full_data = np.divide(data['esr_data'], data['laser_data'])
    #         data_esr.append(np.mean(full_data, axis=0))
    #         counter = counter + 1
    #
    #         if get_times:
    #             time = return_times(f, with_power_sweep=True)
    #             times.append(time)
    #
    #         if get_freqs:
    #             freqs.append(float(f[-9:]))

    for f in sorted(paths):
        data = Script.load_data(f)
        if data is None or 'esr_data' not in data:  # not an ESR folder (e.g., find_nv instead)
            continue
        if plot_with_norm and not esr_fixed:
            full_data = np.divide(data['esr_data'], data['full_laser_data'])
            data_esr.append(np.mean(full_data, axis=0))

        elif plot_with_norm and esr_fixed:
            full_data = np.divide(data['esr_data'], data['laser_data'])
            data_esr.append(np.mean(full_data, axis=0))

        elif not plot_with_norm:
            data_esr.append(data['data'])

        counter = counter + 1

        if get_times:
            time = return_times(f, with_power_sweep=True)
            times.append(time)

        if get_freqs:
            freqs.append(float(f[-9:]))

    f = data['frequency']
    if not get_times and not get_freqs:
        return f, data_esr, counter
    elif get_times and not get_freqs:
        return f, data_esr, counter, times
    elif get_freqs and not get_times:
        return f, data_esr, counter, freqs
    elif get_freqs and get_times:
        return f, data_esr, counter, times, freqs