errorlist = []
for dat in datafolders_id:
print('Loading in data from participant: ' + dat)
if dat not in rein:
print('Not rein')
continue
if dat in rein_bug:
print('There is a bug in this file')
continue
if '18_2' in dat:
trialdata = pd.read_csv(os.path.join(experiment_to_process, dat, dat+'_reinitiated_results.csv'), sep=",")
else:
trialdata = pd.read_csv(os.path.join(experiment_to_process, dat, dat+'_results.csv'), sep=",")
# Get the xdf file
files = glob.glob(os.path.join(experiment_to_process, dat, '*.xdf'))
files = [x for x in files if 'reinitiated' in x or 'onlytpose' in x]
file = files[0]
# Load the xdf file
streams, header = pyxdf.load_xdf(
file,
synchronize_clocks=True,
dejitter_timestamps=False)
# Get the streams
mic_stream = next(s for s in streams if s['info']['name'][0] == 'Mic')
webcam_stream = next(s for s in streams if s['info']['name'][0] == 'MyWebcamFrameStream')
marker_stream = next(s for s in streams if s['info']['name'][0] == 'MyMarkerStream')
bb_stream = next(s for s in streams if s['info']['name'][0] == 'BalanceBoard_stream')
# Marker stream
print("Processing MyMarkerStream...")
processREXDFtoCSV(marker_stream, dat, outputfolder, relative_time=False)
markers = pd.read_csv(os.path.join(outputfolder, dat+'_rein_MyMarkerStream_nominal_srate0.csv'))
# Handle buggy last marker
if markers.iloc[-1][1] != 'Next_word' and markers.iloc[-1][1] != 'Experiment_end':
if pd.isna(markers.iloc[-1][1]):
print('Last row is nan, remove...')
markers = markers.iloc[:-1]
elif 'Trial_start' in markers.iloc[-1][1] or 'Practice trial starts' in markers.iloc[-1][1]:
print('Last row is buggy marker, remove...')
markers = markers.iloc[:-1]
# Process webcam stream
print("Processing MyWebcamFrameStream...")
webcam_ts = processREXDFtoCSV(webcam_stream, dat, outputfolder, relative_time=True)
# Process audio stream
print("Processing Mic...")
mic_ts, reduced_noise = processREXDFtoCSV(mic_stream, dat, outputfolder, relative_time=True)
# Process BB stream
print("Processing BalanceBoard_stream...")
bb_ts = processREXDFtoCSV(bb_stream, dat, outputfolder, relative_time=True)
print('done with processing a complete time series and audio data; we will now start making trial snipped data')
beginlist = []
endlist = []
timestamps = []
timestamps_2 = []
tpose_starts = []
tpose_ends = []
# Iterate over markers and save times of trial starts and ends
for row in markers.iterrows():
if 'Trial_start' in row[1].iloc[1] or 'Practice trial starts' in row[1].iloc[1]:
beginlist.append(row[1].iloc[0])
if 'Trial_end' in row[1].iloc[1] or 'Practice trial ends' in row[1].iloc[1]:
endlist.append(row[1].iloc[0])
if 'Experiment_start' in row[1].iloc[1]:
timestamps.append(row[1].iloc[0])
if 'New block starts' in row[1].iloc[1]:
timestamps_2.append(row[1].iloc[0])
if 'Tpose starts' in row[1].iloc[1]:
tpose_starts.append(row[1].iloc[0])
if 'Tpose ends' in row[1].iloc[1]:
tpose_ends.append(row[1].iloc[0])
# Get to lsl_to_pp coefficient
if timestamps != []:
print('There is experiment start in timestamps')
lsl_to_pp = timestamps[0] - float(trialdata['exp_start'][0])
if timestamps_2 != []:
unique_values = trialdata['block_start'].unique()
# Get rid of nan values
unique_values = unique_values[~np.isnan(unique_values)]
block_start_pp = unique_values[-1]
lsl_to_pp = timestamps_2[-1] - block_start_pp
else:
print('Check: this should be 8_1')
# Get first concept in modality geluiden and practice none
first_concept = trialdata.loc[(trialdata['modality'] == 'geluiden') & (trialdata['practice'] == 'none')].iloc[0]['trial_start']
first_concept_lsl = beginlist[0]
lsl_to_pp = first_concept_lsl - first_concept
# Now we can proceed to cutting
for i in range(len(beginlist)):
begin = beginlist[i]
end = endlist[i]
##########################################
# Convert the beginst to psychopy time
beginst_pp = begin - lsl_to_pp
# Now find in trialdata the closest time to the beginst_pp to gather info
# Whether it is practice or trial
practice = find_closest_value_and_retrieve(trialdata, beginst_pp, 'trial_start', 'practice')
if practice == 'practice':
trialtype = 'pr'
else:
trialtype = 'trial'
# Which participant it is
cycle = find_closest_value_and_retrieve(trialdata, beginst_pp, 'trial_start', 'cycle')
if cycle == 0:
participant = 'p0'
else:
participant = 'p1'
# What concept it is
word = find_closest_value_and_retrieve(trialdata, beginst_pp, 'trial_start', 'word')
# Modality
modality = find_closest_value_and_retrieve(trialdata, beginst_pp, 'trial_start', 'modality')
# Correction, if applicable
correction_info = find_closest_value_and_retrieve(trialdata, beginst_pp, 'trial_start', 'correction')
if correction_info == 0:
correction = '_c0'
elif correction_info == 1:
correction = '_c1'
elif correction_info == 2:
correction = '_c2'
else:
correction = ''
##########################################
# Get frame number of this timestamp from webcam stream
start_frame_idx = np.searchsorted(webcam_ts.iloc[:,0], begin)
end_frame_idx = np.searchsorted(webcam_ts.iloc[:,0], end)
start_frame_number = webcam_ts.iloc[:,1][start_frame_idx]
end_frame_number = webcam_ts.iloc[:,1][end_frame_idx]
# print('start frame number: ' + str(start_frame_number))
# print('end frame number: ' + str(end_frame_number))
# Get corresponding timestamps (relative)
start_time = webcam_ts.iloc[:,2][start_frame_idx]
end_time = webcam_ts.iloc[:,2][end_frame_idx]
# Cut the video stream csv in this subset
webcam_subset = webcam_ts.iloc[start_frame_idx:end_frame_idx+1, :]
if len(webcam_subset.axes[0]) < 2:
print('No data within range...')
errorlist.append(dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'MyWebcamFrameStream'+'_nominal_srate'+str(500)+'_'+participant+'_'+word+'_'+modality+correction+'.csv')
continue
else:
# Save subset to csv
webcam_subset.to_csv(os.path.join(trialfolder, dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'MyWebcamFrameStream'+'_nominal_srate'+str(500)+'_'+participant+'_'+word+'_'+modality+correction+'.csv'), index=False)
# Cut the audio stream csv from start_time to end_time according to relative time
mic_start_idx = np.searchsorted(mic_ts.iloc[:,2], start_time)
mic_end_idx = np.searchsorted(mic_ts.iloc[:,2], end_time)
mic_subset = mic_ts.iloc[mic_start_idx:mic_end_idx+1, :]
if len(mic_subset.axes[0]) < 2:
print('No data within range...')
errorlist.append(dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'Mic'+'_nominal_srate'+str(16000)+'_'+participant+'_'+word+'_'+modality+correction+'.csv')
continue
else:
# Save subset to csv
mic_subset.to_csv(os.path.join(trialfolder, dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'Mic'+'_nominal_srate'+str(16000)+'_'+participant+'_'+word+'_'+modality+correction+'.csv'), index=False)
# Also create audio
wavloc = os.path.join(trialfolder, 'Audio', dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'Mic'+'_nominal_srate'+str(16000)+'_'+participant+'_'+word+'_'+modality+correction+'.wav')
to_audio(wavloc, mic_subset.iloc[:, 1])
# Also apply denoising
reduced_noiseclip = reduced_noise[mic_start_idx:mic_end_idx+1]
wavloc2 = os.path.join(trialfolder, 'Audio', dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'Mic'+'_nominal_srate'+str(16000)+'_'+participant+'_'+word+'_'+modality+correction+'_denoised.wav')
wavfile.write(wavloc2, 16000, reduced_noiseclip)
# Cut the balance board stream csv from start_time to end_time according to relative time
bb_start_idx = np.searchsorted(bb_ts.iloc[:,5], start_time)
bb_end_idx = np.searchsorted(bb_ts.iloc[:,5], end_time)
bb_subset = bb_ts.iloc[bb_start_idx:bb_end_idx+1, :]
if len(bb_subset.axes[0]) < 2:
print('No data within range...')
errorlist.append(dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'BalanceBoard_stream'+'_nominal_srate'+str(100)+'_'+participant+'_'+word+'_'+modality+correction+'.csv')
continue
else:
# Save subset to csv
bb_subset.to_csv(os.path.join(trialfolder, dat+'_rein_'+trialtype+'_'+ str(i) +'_'+'BalanceBoard_stream'+'_nominal_srate'+str(100)+'_'+participant+'_'+word+'_'+modality+correction+'.csv'), index=False)
if len(tpose_starts) < 2:
index = 1
elif len(tpose_starts) == 2:
index = 0
else:
break
# Get information about the tpose for camera
for i in range(len(tpose_starts)):
begin = tpose_starts[i]
end = tpose_ends[i]
# get frame number of this timestamp from webcam stream
start_frame_idx = np.searchsorted(webcam_ts.iloc[:,0], begin)
end_frame_idx = np.searchsorted(webcam_ts.iloc[:,0], end)
start_frame_number = webcam_ts.iloc[:,1][start_frame_idx]
end_frame_number = webcam_ts.iloc[:,1][end_frame_idx]
# print('start frame number: ' + str(start_frame_number))
# print('end frame number: ' + str(end_frame_number))
# Find indices of the specified frames
try:
start_frame_idx = webcam_ts.index[webcam_ts.iloc[:,1] == start_frame_number][0]
end_frame_idx = webcam_ts.index[webcam_ts.iloc[:,1] == end_frame_number][0]
except IndexError:
print("Frame number not found in DataFrame.")
errorlist.append(dat+'_rein_'+'tpose_'+ str(index) +'_'+'MyWebcamFrameStream'+'_nominal_srate'+str(500)+'.csv')
continue
# Cut the vide stream csv in this subset
webcam_ts_subset = webcam_ts.iloc[start_frame_idx:end_frame_idx+1, :]
if len(webcam_ts_subset.axes[0]) < 2:
print('No data within range...')
errorlist.append(dat+'_rein_'+'tpose_'+ str(index) +'_'+'MyWebcamFrameStream'+'_nominal_srate'+str(500)+'.csv')
continue
else:
# Save subset to csv
webcam_ts_subset.to_csv(os.path.join(trialfolder, dat+'_rein_'+'tpose_'+ str(index) +'_'+'MyWebcamFrameStream'+'_nominal_srate'+str(500)+'.csv'), index=False)
# Save the error log
errors = pd.DataFrame(errorlist, columns=['file_error'])
# Get todays date
today = pd.Timestamp("today").strftime("%Y_%m")
file_path = os.path.join(errorlogs,'error_log_cuttingtrails' + today + '.csv')
errors.to_csv(file_path, index=False)
print('We are done: proceed to snipping videos to triallevel')