num_sweep_tones = int(f_sweep_span / df_baseband)
f_baseband = f_baseband_minimum + ri.state.adc_sample_rate / 2**tone_sample_exponent * np.arange(
    num_sweep_tones)
f_lo_center = f_lo_spacing * np.round(
    (f_center - f_baseband.mean()) / f_lo_spacing)
logger.info(
    "Fine sweep using {:d} tones spanning {:.1f} MHz with resolution {:.0f} Hz (2^{:d} samples)"
    .format(num_sweep_tones, 1e-6 * f_baseband.ptp(), df_baseband,
            tone_sample_exponent))
logger.info(
    "Coarse sweep using {:d} tones spanning {:.1f} MHz with resolution {:.0f} Hz (2^{:d} samples)"
    .format(num_sweep_tones // coarse_stride, 1e-6 * f_baseband.ptp(),
            coarse_stride * df_baseband, tone_sample_exponent))

# Run
npd = acquire.new_npy_directory(suffix=suffix)
tic = time.time()
try:
    for lo_index, f_lo in enumerate(f_lo_center):
        assert np.all(ri.adc_valon.get_phase_locks())
        tools.set_and_attempt_external_phase_lock(ri=ri,
                                                  f_lo=1e-6 * f_lo,
                                                  f_lo_spacing=1e-6 *
                                                  f_lo_spacing)
        for attenuation_index, attenuation in enumerate(attenuations):
            ri.set_dac_attenuator(attenuation)
            ri.set_tone_baseband_freqs(freqs=1e-6 * np.array([f_baseband[0]]),
                                       nsamp=2**tone_sample_exponent)
            #time.sleep(1)
            #tools.optimize_fft_gain(ri, fraction_of_maximum=0.5)
            ri.set_fft_gain(4)
conditioner = analog.HeterodyneMarkII()
hw = hardware.Hardware(conditioner)
ri = hardware_tools.r2h14_with_mk2(initialize=True, use_config=False)
ri.adc_valon.set_ref_select(0)
ri.lo_valon.set_ref_select(1)

# Calculate tone bin integers
f_filterbank_MHz = ri.fs / ri.nfft
n_filterbank = int(np.round(baseband_MHz / f_filterbank_MHz))
tone_sample_exponent = int(np.log2(ri.nfft) + tones_per_bin_exponent)
center_integer = 2 ** tones_per_bin_exponent * n_filterbank
tone_integers = center_integer + np.arange(-half_width_in_bins * 2 ** tones_per_bin_exponent,
                                           half_width_in_bins * 2 ** tones_per_bin_exponent + 1)

# Acquire
npd = acquire.new_npy_directory(suffix=suffix)
tic = time.time()
try:
    tools.set_and_attempt_external_phase_lock(ri, f_lo=lo_MHz, f_lo_spacing=lo_round_to_MHz)
    ri.set_lo(lomhz=lo_MHz, chan_spacing=lo_round_to_MHz)
    assert np.all(ri.adc_valon.get_phase_locks())
    assert np.all(ri.lo_valon.get_phase_locks())
    ri.set_dac_attenuator(dac_attenuation)
    ri.set_tone_bins(bins=np.array([center_integer]), nsamp=2 ** tone_sample_exponent)
    ri.fft_bins = np.atleast_2d(np.array([n_filterbank]))
    ri.select_bank(0)
    ri.select_fft_bins(np.array([0]))
    time.sleep(wait)
    tools.optimize_fft_gain(ri, fraction_of_maximum=0.5)
    time.sleep(wait)
    ri.iq_delay, _ = tools.find_best_iq_delay_adc(ri=ri)