Skip to content
Snippets Groups Projects
Commit 598683ab authored by ferrari's avatar ferrari
Browse files

Add reset fun to change current file

parent 17885a38
Branches
No related tags found
No related merge requests found
......@@ -4,6 +4,7 @@ import matplotlib.pyplot as plt
import scipy.signal as sg
import soundfile as sf
import os
import sys
from matplotlib.widgets import Button, Cursor, MultiCursor, CheckButtons, RadioButtons, AxesWidget, TextBox
from matplotlib.patches import Circle
from fractions import Fraction
......@@ -15,6 +16,10 @@ FSSR = 48_000 # Sampling rate of full signal plot
FSPK = 0.1 # Max distance to detect a click in full sig in seconds
IPIPK= 0.15 # Max distance to detect a IPI in milliseconds
SPSC = 80 # Spectrogram scale
EMLN = {'p1_pos':np.nan, 'ipi_sig': np.nan,
'ipi_corr_man': np.nan, 'ipi_corr_auto': np.nan,
'ipi_ceps_man': np.nan, 'ipi_ceps_auto': np.nan,
'ind_number': np.nan} # Empty dataline
def read(file_path, always_2d=True):
......@@ -29,6 +34,18 @@ def load_anysound(file_path):
return np.array(tmp.get_array_of_samples()).reshape(-1, tmp.channels), tmp.frame_rate
def load_file(in_path, channel, low, high):
print(f'Loading and processing {in_path}')
song, sr = read(in_path, always_2d=True)
song = song[:, channel]
sos = sg.butter(3, [low, high], 'bandpass', fs=sr, output='sos')
song = sg.sosfiltfilt(sos, song)
frac = Fraction(FSSR, sr)
song_resample = sg.resample_poly(song, frac.numerator, frac.denominator)
print('Done processing')
return song, sr, song_resample
def norm(x):
return x/(np.abs(x).max()+1e-10)
......@@ -242,6 +259,7 @@ class Callback(object):
self.curr_vert = 3*[0] # Current vertical line of sig/spec for each plot
self.cursor = None
self.f_cursor = None
self.reset_b = None
def shift_left(self, event):
self.p = max(0, self.p - FSSR*13)
......@@ -269,10 +287,7 @@ class Callback(object):
if mpos/FSSR not in self.offset[:,0]:
self.offset = np.concatenate([self.offset, [[mpos/FSSR, self.song_resample[mpos]]]], axis=0)
self.scat.set_offsets(self.offset)
self.df[mpos/FSSR] = {'p1_pos':np.nan, 'ipi_sig': np.nan,
'ipi_corr_man': np.nan, 'ipi_corr_auto': np.nan,
'ipi_ceps_man': np.nan, 'ipi_ceps_auto': np.nan,
'ind_number': np.nan}
self.df[mpos/FSSR] = EMLN.copy()
c = [[0, 0, 0, 1]]
c[0][self.curr] = 1
if len(self.offset) == 1:
......@@ -340,6 +355,7 @@ class Callback(object):
self.view_data[self.curr][1][0].set_clim(spec.max()-SPSC, spec.max())
self.view_data[self.curr][2][0].set_ydata(norm(np.correlate(click, click, 'same')[-int(10e-3*self.sr):]))
self.view_data[self.curr][3][0].set_ydata(norm_std(np.abs(np.fft.irfft(np.log10(np.abs(np.fft.rfft(click))))[:int(10e-3*self.sr)])))
self._set_label()
plt.draw()
return
for i in range(3): # Look if a click plot was clicked and which one
......@@ -365,7 +381,7 @@ class Callback(object):
if self.view_data[i][0][1][1].get_visible():
ipi_man = self.view_data[i][0][1][1].get_xdata()[0] - self.view_data[i][0][1][0].get_xdata()[0]
self.df[self.offset[self.curr_ind[i], 0]]['ipi_sig'] = ipi_man
self.view_ax[i][0].set_xlabel(f'IPI man:{ipi_man:.5f}')
self.view_ax[i][0].set_xlabel(f'Sig man:{ipi_man:.5f}')
else:
self.view_data[i][j][1].set_xdata((event.xdata, event.xdata))
self.view_data[i][j][1].set_visible(True)
......@@ -375,12 +391,14 @@ class Callback(object):
col = 'ipi_' + ('corr' if j == 2 else 'ceps')
self.df[self.offset[self.curr_ind[i],0]][col + '_man'] = event.xdata
self.df[self.offset[self.curr_ind[i],0]][col + '_auto'] = ipi_auto*1e3/self.sr
self.view_ax[i][j].set_xlabel(f'IPI man:{event.xdata:.3f} auto:{ipi_auto*1e3/self.sr:.3f}')
self.view_ax[i][j].set_xlabel(f'{"Corr" if j == 2 else "Ceps"} man:{event.xdata:.3f} auto:{ipi_auto*1e3/self.sr:.3f}')
plt.draw()
def change_curr(self, label):
self.curr = int(label[-1])
self.f_cursor.linev.set_color('rgb'[self.curr])
self.reset_b.label.set_c('rgb'[self.curr])
plt.draw()
def play(self, event):
sound = (norm(self.song_resample[self.p:self.p+FSSR*20])*(2**15-1)).astype(np.int16)
......@@ -395,22 +413,40 @@ class Callback(object):
plt.pause(0.2)
self.fax.get_figure().set_constrained_layout(False)
def _set_label(self, ind=None, dic=None):
if ind is None:
ind = self.curr
if dic is None:
dic = self.df[self.offset[self.curr_ind[ind], 0]]
self.view_ax[ind][0].set_xlabel(f'Sig man:{dic["ipi_sig"]:.3f}')
self.view_ax[ind][2].set_xlabel(f'Corr man:{dic["ipi_corr_man"]:.3f} auto:{dic["ipi_corr_auto"]:.3f}')
self.view_ax[ind][3].set_xlabel(f'Ceps man:{dic["ipi_ceps_man"]:.3f} auto:{dic["ipi_ceps_auto"]:.3f}')
def reset_curr(self, event):
self.df[self.offset[self.curr_ind[self.curr], 0]] = EMLN.copy()
self._set_label()
plt.draw()
def load_file(in_path, channel, low, high):
print(f'Loading and processing {in_path}')
song, sr = read(in_path, always_2d=True)
song = song[:, channel]
sos = sg.butter(3, [low, high], 'bandpass', fs=sr, output='sos')
song = sg.sosfiltfilt(sos, song)
frac = Fraction(FSSR, sr)
song_resample = sg.resample_poly(song, frac.numerator, frac.denominator)
print('Done processing')
return song, sr, song_resample
def reset(self, song, sr, song_resample):
self.p = 0
self.df = dict()
self.line.set_ydata(song_resample[:FSSR * 20])
self.song = song
self.song_resample = song_resample
self.sr = sr
self.curr = 0 # current view selected
self.offset = np.zeros((0, 2))
self.scat.set_offsets(self.offset)
self.curr_ind = 3 * [None] # Ind of click for each plot
self.curr_vert = 3 * [0] # Current vertical line of sig/spec for each plot
for i in range(3):
self._set_label(i, EMLN)
plt.draw()
def init(in_path, channel, low=2e3, high=20e3):
song, sr, song_resample = load_file(in_path, channel, low, high)
fig = plt.figure('IPI', figsize=[16, 9], constrained_layout=True)
fig = plt.figure('IPI of ' + in_path.rsplit('/', 1)[-1], figsize=[16, 9], constrained_layout=True)
gs = fig.add_gridspec(12, 20)
full_sig = plt.subplot(gs[:2, 1:-1])
......@@ -466,7 +502,13 @@ def init(in_path, channel, low=2e3, high=20e3):
resize_b = Button(resize_b_ax, 'Resize plot')
resize_b.on_clicked(callback.resize)
# text_b_ax = plt.subplot(gs[-1,4:6])
reset_b_ax = plt.subplot(gs[-1,4:6])
reset_b = Button(reset_b_ax, 'Reset current')
reset_b.label.set_c('r')
reset_b.on_clicked(callback.reset_curr)
callback.reset_b = reset_b
# text_b_ax = plt.subplot(gs[-1,6:8])
# text_b = TextBox(text_b_ax, 'Individue #\nof current')
# # text_b.on_clicked(callback.resize)
......@@ -523,21 +565,22 @@ def init(in_path, channel, low=2e3, high=20e3):
fig.set_constrained_layout(False)
return {'callback': callback, 'fig': fig, 'buttons':
{'b_left': b_left, 'b_right': b_right, 'play_b': play_b, 'resize_b': resize_b, 'r_button': r_button,
'fs_click': cid}} # Needed to keep the callbacks alive
'fs_click': cid, 'reset_b': reset_b}} # Needed to keep the callbacks alive
def reset(in_path, channel, low=2e3, high=20e3):
def reset(callback, in_path, channel, low=2e3, high=20e3):
song, sr, song_resample = load_file(in_path, channel, low, high)
callback.reset(song, sr, song_resample)
def main(args):
if args.out == '':
outpath = args.out.rsplit('.', 1)[0] + '.pred.h5'
outpath = args.input.rsplit('.', 1)[0] + '.pred.h5'
else:
outpath = args.out
if os.path.isfile(outpath) and not args.erase:
print(f'Out file {outpath} already exist and erase option isn\'t set.')
return 1
ref_dict = init(args.input, args.channel)
plt.show()
......@@ -555,4 +598,4 @@ if __name__ == '__main__':
" the computation will be halted")
args = parser.parse_args()
main(args)
sys.exit(main(args))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment