Skip to content

Commit

Permalink
Merge branch 'ml' into ml-multicolor-simulation
Browse files Browse the repository at this point in the history
  • Loading branch information
ange1a-j14 authored Dec 11, 2024
2 parents 932b727 + a97eef4 commit 698a925
Show file tree
Hide file tree
Showing 10 changed files with 506 additions and 199 deletions.
164 changes: 100 additions & 64 deletions acquire_automatic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,22 @@
import matplotlib.pyplot as plt
import redpitaya_scpi as scpi
import numpy as np
from scipy.fftpack import fft
from numpy.fft import fft, fftfreq
# from scipy.fft import fft # use numpy
import math
import util
from timeit import timeit
from datetime import datetime
from scipy.signal import butter, filtfilt

IP = 'rp-f0c04a.local'
rp_s = scpi.scpi(IP)
print('Connected to ' + IP)
# plt.rcParams.update({
# "text.usetex": True
# })

def run_one_shot(use_freq, max_freq, start_freq=1, end_freq=1000, ampl=0.1, decimation=8192,
def run_one_shot(start_freq=1, end_freq=1000, ampl=0.1, gen_dec=8192, acq_dec=256, num_acq=1,
store_data=False, plot_data=False, filename='data.h5py'):
"""Runs one shot of driving the speaker with a waveform and collecting the relevant data.
Expand All @@ -30,15 +37,16 @@ def run_one_shot(use_freq, max_freq, start_freq=1, end_freq=1000, ampl=0.1, deci

N = 16384 # Number of samples in buffer
SMPL_RATE_DEC1 = 125e6 # sample rate for decimation=1 in Samples/s (Hz)
smpl_rate = SMPL_RATE_DEC1//decimation
burst_time = N / smpl_rate
gen_smpl_rate = SMPL_RATE_DEC1//gen_dec
acq_smpl_rate = SMPL_RATE_DEC1//acq_dec
burst_time = N / gen_smpl_rate

wave_form = 'ARBITRARY'
freq = 1 / burst_time

t, y = util.bounded_frequency_waveform(start_freq, end_freq, length=N, sample_rate=smpl_rate,
use_freq=use_freq, max_freq=max_freq)
t, y = util.bounded_frequency_waveform(start_freq, end_freq, length=N, sample_rate=gen_smpl_rate, invert=True)
y = util.linear_convert(y) # convert range of waveform to [-1, 1] to properly set ampl

if plot_data:
plt.plot(t, y)
plt.show()
Expand All @@ -49,94 +57,122 @@ def run_one_shot(use_freq, max_freq, start_freq=1, end_freq=1000, ampl=0.1, deci

##### Generation #####
# Function for configuring Source
rp_s.sour_set(1, wave_form, ampl, freq, data=y)
rp_s.sour_set(1, wave_form, 1, freq, data=ampl*y)

# Enable output
rp_s.tx_txt('OUTPUT1:STATE ON')
rp_s.tx_txt('SOUR1:TRig:INT')
# print("output enabled", datetime.now().time())

##### Acqusition #####
pd_data = []
speaker_data = []
vel_data = []
# Function for configuring Acquisition
rp_s.acq_set(dec=decimation, trig_delay=0)
rp_s.tx_txt('ACQ:START')
time.sleep(1)
rp_s.tx_txt('ACQ:TRig CH2_PE')
rp_s.tx_txt('ACQ:RST')
rp_s.acq_set(dec=acq_dec, trig_delay=8192)

rp_s.tx_txt('ACQ:START')
# ! OS 2.00 or higher only ! ##
time.sleep(0.4)
rp_s.tx_txt('ACQ:TRig NOW') # CH2_PE
time.sleep(0.4)
# Wait for trigger
while 1:
rp_s.tx_txt('ACQ:TRig:STAT?') # Get Trigger Status
if rp_s.rx_txt() == 'TD': # Triggered?
# print("td", datetime.now().time())
break
## ! OS 2.00 or higher only ! ##
while 1:
rp_s.tx_txt('ACQ:TRig:FILL?')
if rp_s.rx_txt() == '1':
# print("filled", datetime.now().time())
break

##### Analaysis #####
##### Analysis #####
# Read data and plot function for Data Acquisition
pd_data = np.array(rp_s.acq_data(chan=1, convert=True)) # Volts
speaker_data = np.array(rp_s.acq_data(chan=2, convert=True)) # Volts
velocity_data, converted_signal, freq = util.velocity_waveform(speaker_data, smpl_rate, use_freq, max_freq)
displ_data, _, _ = util.displacement_waveform(speaker_data, smpl_rate, use_freq, max_freq)
y_vel, y_converted, _ = util.velocity_waveform(ampl*y, smpl_rate, use_freq, max_freq)
time_data = np.linspace(0, N-1, num=N) / smpl_rate

pds = np.array(rp_s.acq_data(chan=1, convert=True))
speaker = np.array(rp_s.acq_data(chan=2, convert=True))
acq_time_data = np.linspace(0, N-1, num=N) / acq_smpl_rate

if plot_data:
fig, ax = plt.subplots(nrows=3)

ax[0].plot(time_data, pd_data, color='blue', label='Observed PD')
ax[0].plot(time_data, speaker_data, color='black', label='Observed Drive')
ax[0].plot(time_data, ampl*y, label='Drive Output', alpha=0.5)
ax[0].legend()
ax[0].set_ylabel('Amplitude (V)')
ax[0].set_xlabel('Time (s)')

ax[1].plot(freq, np.abs(fft(speaker_data)), color='black', label='Observed Drive', marker='.')
ax[1].plot(freq, np.abs(converted_signal), color='green', label='Expected Observed Vel', marker='.')
ax[1].plot(freq, np.abs(fft(ampl*y)), color='blue', label='Expected Drive', marker='.')
ax[1].plot(freq, np.abs(y_converted), color='orange', label='Expected Ideal Vel', marker='.')
ax[1].loglog()
ax[1].set_xlabel('Frequency (Hz)')
ax[1].set_ylabel('$|\^{V}|$')
ax[1].legend()

ax[2].plot(time_data, velocity_data, color='black', label='Observed Drive')
ax[2].plot(time_data, y_vel, label='Drive Output')
ax[2].set_ylabel('Expected Vel (Microns/s)')
ax[2].set_xlabel('Time (s)')
ax[2].legend()
plt.tight_layout()
plt.show()

pd_data = pds
speaker_data = speaker
# pd_data.append(pds) # Volts
# speaker_data.append(speaker) # Volts
# vel_data.append(vels)

if store_data:
# Store data in h5py file
path = "/Users/angelajia/Code/College/SMI/data/"
# filename = "training_data.h5py"
file_path = os.path.join(path, filename)

entries = {
'Time (s)': time_data,
'Speaker (V)': speaker_data,
'Speaker (Microns/s)': velocity_data,
'PD (V)': pd_data,
'Speaker (Microns)': displ_data
'Speaker (V)': speaker,
'Speaker (Microns/s)': vels,
'PD (V)': pds
}

util.write_data(file_path, entries)

if plot_data:
gen_time_data = np.linspace(0, N-1, num=N) / gen_smpl_rate
# pd_data = np.concatenate(pd_data)
# speaker_data = np.concatenate(speaker_data)
# vel_data = np.concatenate(vel_data)
y_vel, y_converted, _ = util.velocity_waveform(ampl*y, gen_smpl_rate)
avg_speaker = np.mean(np.reshape(speaker, (-1, 32)), axis=1)
print(avg_speaker.shape)
vel_data, vel_converted, freqs= util.velocity_waveform(avg_speaker, acq_smpl_rate)

fig, ax = plt.subplots(nrows=4)

ax[0].plot(pd_data, color='blue', label='Observed PD')# , marker='.')
ax[0].plot(speaker_data, color='black', label='Observed Drive') #, marker='.')
# ax[0].plot(time_data, ampl*y, label='Drive Output', alpha=0.5)
ax[0].legend()
ax[0].set_ylabel('Amplitude (V)')
ax[0].set_xlabel('Samples')

#ax[1].set_title(r'$\tilde{F}^{-1}(VelTransferFunc(f) * \tilde{F}(Voltage Time Series)(f) )$')
ax[1].set_title("Vel for acq_dec=256")
ax[1].plot(vel_data)
ax[1].set_xlabel('Samples')
ax[1].set_ylabel('Expected Vel (Microns/s)')

# ax[3].set_title("Vel for gen_dec=8192")
# ax[3].plot(gen_time_data, y_vel, label='Drive Output', alpha=0.7)
# ax[3].set_ylabel('Expected Vel (Microns/s)')
# ax[3].set_xlabel('Time (s)')
# ax[1].legend()

# ax[2].set_title("Generated Speaker Voltage (gen_dec=8192)")
# ax[2].plot(gen_time_data, ampl*y)
# ax[2].set_xlabel('Time (s)')
# ax[2].set_ylabel('Amplitude (V)')

ax[2].plot(fftfreq(speaker.shape[0], d=1/acq_smpl_rate), np.abs(fft(speaker, norm='ortho')), marker='.')
ax[3].plot(freqs, np.abs(vel_converted), marker='.')
plt.tight_layout()
plt.show()

##### Reset when closing program #####
rp_s.tx_txt('GEN:RST')
rp_s.tx_txt('ACQ:RST')

num_shots = 2000

filenames = ['test_1to1kHz_misaligned_invertspectra_trigdelay8192_sleep100ms_2kx1shots_randampl.h5py',
'val_1to1kHz_misaligned_invertspectra_trigdelay8192_sleep100ms_2kx1shots_randampl.h5py']
shots = [1, 0]
amplitude = 0
end_freq = 1000
max_freq = 10*end_freq
for i in range(num_shots):
amplitude = np.random.uniform(0.1, 0.6)
if i % 400 == 0:
print(f"{i}: ampl = {amplitude}")
run_one_shot(True, max_freq, 30, end_freq, ampl=amplitude, decimation=256, store_data=True, plot_data=False,
filename='test_max10kHz_30to1kHz_2kshots_dec=256_randampl.h5py')
# print(i)
acq_num = 1
print("start", datetime.now().time())
for (file, num_shots) in zip(filenames, shots):
print(file)
print(num_shots)
for i in range(num_shots):
amplitude = 0.1 # np.random.uniform(0.1, 0.6)
if i % 500 == 0:
print("\t", datetime.now().time())
print(f"\t{i*acq_num}: ampl = {amplitude}")
run_one_shot(100, 101, ampl=amplitude, gen_dec=8192, acq_dec=256, num_acq=acq_num, store_data=False, plot_data=True,
filename=file)
print("end", datetime.now().time())
4 changes: 2 additions & 2 deletions acquire_continuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
print('Connected to ' + IP)

wave_form = "SINE"
freq = 1000
freq = 120
ampl = 0.1

N = 16384 # Number of samples in buffer
SMPL_RATE_DEC1 = 125e6 # sample rate for decimation=1 in Samples/s (Hz)
decimation = 32
decimation = 256# 32
smpl_rate = SMPL_RATE_DEC1//decimation

# Reset Generation and Acquisition
Expand Down
4 changes: 2 additions & 2 deletions decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def configure_optimizers(self):
# We will reduce the learning rate by factor of gamma after 100 and 150
# epochs
scheduler = optim.lr_scheduler.MultiStepLR(optimizer,
milestones=[100, 150, 200],
gamma=1)
milestones=[50, 100, 150], #changed from [100, 150, 200]
gamma=1)
return [optimizer], [scheduler]

def get_loss_function(self, loss_hparams):
Expand Down
99 changes: 0 additions & 99 deletions model_analysis.py

This file was deleted.

2 changes: 1 addition & 1 deletion models.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __init__(self, input_size, output_size, in_channels=1, activation='LeakyReLU
self.fc_layers = nn.Sequential(
# length of input = 64 filters * length of 10 left
nn.Linear(640, 16),
nn.ReLU(),
act_fn_by_name[activation],
nn.Linear(16, output_size)
)

Expand Down
Loading

0 comments on commit 698a925

Please sign in to comment.