-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextractSaveData.py
489 lines (462 loc) · 26 KB
/
extractSaveData.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import pdb
import h5py
import time
import glob
import pickle
from tools.h5pyTools import h5pyTools
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import platform
import tools.googleDocsAccess as googleDocsAccess
from tools.pyqtgraph import OrderedDict
import os
import sys
from tools.pyqtgraph.configfile import readConfigFile, writeConfigFile
# analysisParams= OrderedDict([
# ('swingStanceExtraction',{
# 'stanceDistances': None,
# }),
# ('pawTrajectories' ,{
# 'DLCinstance': None,
# }),
# ('projectionInTimeParameters', {
# 'horizontalCuts' : None ,
# }),
# ('caEphysParameters', {
# 'leaveOut' : None,
# }),
# ])
class extractSaveData:
def __init__(self, mouse , recStruc=None):
self.mouse = mouse[:10]
self.h5pyTools = h5pyTools()
if platform.node() == 'CD-8QLSTY3' or platform.node() == 'thinkpadX1B':
laptop = False
self.analysisBase = 'S:/BelloneLab/#SHARE/AndryA'
if int(self.mouse[:6]) < 200300:
self.recStructure = 'DCN'
self.listOfAllExpts = googleDocsAccess.getExperimentSpreadsheet(self.recStructure)
# if self.recStructure == 'lol':
# self.config = readConfigFile('animals.config')
dates = []
for d in self.listOfAllExpts[self.mouse]['dates']:
dates.append(d)
if dates[0] >= '181018':
self.dataBase = 'S:/BelloneLab/#SHARE/AndryA/rawData'
self.dataPCLocation = OrderedDict(
[('andryPC', '/')])
#
self.computerDict = OrderedDict(
[('andryPC', 'andryPC')])
self.analysisLocation = self.analysisBase + '/procData/%s/' % mouse
self.figureLocation = self.analysisBase + '/figures/%s/' % self.mouse
if not os.path.isdir(self.analysisLocation):
os.makedirs(self.analysisLocation)
if not os.path.isdir(self.figureLocation):
os.makedirs(self.figureLocation)
fName = self.analysisLocation + 'analysis.hdf5'
try:
self.f = h5py.File(fName, 'a')
except FileExistsError:
print('hdf5 file is used by another process and cannot be accessed.')
sys.exit(1)
else:
pass
# read animal specific config file with analysis parameters
# self.analysisConfigFile = self.analysisLocation + '%s.config' % self.mouse
# if os.path.isfile(self.analysisConfigFile):
# print('analysis parameter exist already')
# self.analysisConfig = readConfigFile(self.analysisConfigFile)
# else:
# self.analysisConfig = analysisParams
# writeConfigFile(self.analysisConfig, self.analysisConfigFile)
# print(self.analysisConfig)
# experiments stored under this name were recorded as sequence with a certain number of repetitions
self.listOfSequenceExperiments = ['locomotionTriggerSIAndMotor', 'locomotionTriggerSIAndMotorJin',
'locomotionTriggerSIAndMotor60sec', 'locomotion_recording_setup2',
'E2_VC_LEDtrigger', 'E2_VC_LEDtrigger_train',
'locomotionTriggerSIAndMotorEMG60sec', 'locomotion_recording_setupBonsai',
'locomotionTriggerSIAndMotor60sec_Bonsai',
'locomotionEMGAndMotor60sec_Bonsai']
############################################################
def __del__(self):
try:
self.f.flush()
except:
pass
else:
print('hdf5 file flushed!')
# self.f.close()
print('on exit')
# read animal specific config file with analysis parameters
# self.analysisConfigFile = self.analysisLocation + '%s.config' % self.mouse
# if os.path.isfile(self.analysisConfigFile):
# print('analysis parameter exist already')
# self.analysisConfig = readConfigFile(self.analysisConfigFile)
# else:
# self.analysisConfig = analysisParams
# writeConfigFile(self.analysisConfig, self.analysisConfigFile)
# print(self.analysisConfig)
############################################################
def __del__(self):
try:
self.f.flush()
except:
pass
else:
print('hdf5 file flushed!')
# self.f.close()
print('on exit')
############################################################
def writeConfigFile(self):
print('analysis parameters : ', self.analysisConfig)
print('analysis parameters writting to file : ', self.analysisConfigFile)
writeConfigFile(self.analysisConfig, self.analysisConfigFile)
############################################################
def getEphysRecordingsList(self, expDate='all', recordings='all'):
if recordings == 'allMLI':
self.recID = 'recsMLI'
elif recordings == 'allPC':
self.recID = 'recsPC'
elif recordings == 'allBehavior':
self.recID = 'recsBehavior'
elif recordings == 'all':
self.recID = ['recsMLI','recsPC','recsBehavior']
#pdb.set_trace()
# for i in range(len(self.config)):
# if self.config['%s' % i]['mouse'] == self.mouse:
# print('experiment dictionary of mouse exists')
# self.expDict = self.config['%s' % i]['days']
# dictExists = True
#pdb.set_trace()
folderRec = []
if self.mouse in self.listOfAllExpts:
# print mouse
# print expDate, self.listOfAllExpts[mouse]['dates']
expDateList = []
# pdb.set_trace()
# provide choice of which days to include in analysis
if expDate == 'some':
print('Dates when experiments where performed with animal %s :' % self.mouse)
didx = 0
for d in self.listOfAllExpts[self.mouse]['dates']:
print(' %s %d' % (d, didx))
didx += 1
print('Choose the dates for analysis by typing the index, e.g, \'1\', or \'0,1,3,5\', or \'0-5\' : ', end='')
daysInput = input()
if '-' in daysInput:
startEnd = [int(i) for i in daysInput.split('-')]
daysInputIdx = [i for i in range(startEnd[0],startEnd[1]+1)]
else:
daysInputIdx = [int(i) for i in daysInput.split(',')] # print(daysInputIdx,daysInputIdx[0],type(daysInputIdx))
elif expDate == 'allPC' or expDate == 'allMLI':
didx = 0
daysInputIdx = []
for d in self.listOfAllExpts[self.mouse]['dates']:
if d in self.expDict.keys() :
#print(self.expDict[d])
if self.recID in self.expDict[d]:
daysInputIdx.append(didx)
didx+=1
elif expDate == 'all':
didx = 0
daysInputIdx = []
for d in self.listOfAllExpts[self.mouse]['dates']:
if d in self.expDict.keys() :
if any(key in self.expDict[d] for key in self.recID):
daysInputIdx.append(didx)
didx+=1
########################################################
# generate list of days to analyze
if expDate == 'some' or expDate=='allMLI' or expDate=='allPC' or expDate == 'all':
didx = 0
for d in self.listOfAllExpts[self.mouse]['dates']:
if didx in daysInputIdx:
# print(d)
expDateList.append(d)
didx += 1
else:
expDateList.append(expDate)
print('Selected dates :', expDateList)
# pdb.set_trace()
#####################################################
# chose recordings
if recordings == 'allMLI':
print('All MLI recordings will be analyzed')
recIdx = 0
recInputIdx = []
for eD in expDateList:
dataFolders = self.listOfAllExpts[self.mouse]['dates'][eD]['folders']
if 'recsMLI' in self.expDict[eD]:
idx910recs = list(self.expDict[eD]['recsMLI'].keys())
else:
idx910recs = None
for fold in dataFolders:
self.dataLocation = self.dataBase + self.dataPCLocation[dataFolders[fold]['recComputer']] + fold + '/'
recList = self.getDirectories(self.dataLocation)
if idx910recs is not None:
idx910recs = [int(i) for i in idx910recs]
for n in range(len(idx910recs)):
#print(idx910recs,n)
trials = self.expDict[eD]['recsMLI'][str(idx910recs[n])]['trials']
if 'visuallyGuided' in self.expDict[eD]['recsMLI'][str(idx910recs[n])].keys():
visGuided = ['MLI',True]
else:
visGuided = ['MLI',False]
#if trials == 'all':
# trials = [i for i in range(5)] # assume to include all five trials if 'trials' subfield does not exist in the config file
#elif type(trials)==int:
#print(idx910recs, n,trials,recIdx)
trials=[trials]
#recInputIdx.append([recIdx+idx910recs[n],idx910recs[n],trials])
recInputIdx.append([recIdx,eD, idx910recs[n], trials,visGuided])
#nRecs = len(trials[0])
recIdx+=len(recList)
#pdb.set_trace()
elif recordings == 'allPC':
print('All PC recordings will be analyzed')
recIdx = 0
recInputIdx = []
for eD in expDateList:
dataFolders = self.listOfAllExpts[self.mouse]['dates'][eD]['folders']
if 'recsPC' in self.expDict[eD]:
idx820recs = list(self.expDict[eD]['recsPC'].keys())
else:
idx820recs = None
for fold in dataFolders:
#print(' ', fold)
self.dataLocation = self.dataBase + self.dataPCLocation[dataFolders[fold]['recComputer']] + fold + '/'
recList = self.getDirectories(self.dataLocation)
#print(recList)
if idx820recs is not None:
idx820recs = [int(i) for i in idx820recs]
for n in range(len(idx820recs)):
trials = self.expDict[eD]['recsPC'][str(idx820recs[n])]['trials']
if 'visuallyGuided' in self.expDict[eD]['recsPC'][str(idx820recs[n])].keys():
visGuided = ['PC',True]
else:
visGuided = ['PC',False]
#if trials == 'all':
# trials = [i for i in range(1)] # assume to include all five trials if 'trials' subfield does not exist in the config file
trials = [trials]
#recInputIdx.append([recIdx+idx820recs[n],idx820recs[n],trials])
recInputIdx.append([recIdx,eD,idx820recs[n],trials,visGuided])
recIdx+=len(recList)
#pdb.set_trace()
elif recordings == 'some':
# first show all recordings for a given date
print('Choose recording to analyze')
recIdx = 0
recInputIdx = []
for eD in expDateList:
dataFolders = self.listOfAllExpts[self.mouse]['dates'][eD]['folders']
for fold in dataFolders:
print(' ', fold)
# pdb.set_trace()
# self.dataLocation = (self.dataBase2 + fold + '/') if eD >= '181018' else (self.dataBase + fold + '/')
self.dataLocation = self.dataBase + self.dataPCLocation[dataFolders[fold]['recComputer']] + fold + '/'
#self.recordingMachine = self.computerDict[dataFolders[fold]['recComputer']]
#print(self.dataLocation)
if not os.path.exists(self.dataLocation):
# print('experiment %s exists' % fold)
# else:
print('Problem, experiment does not exist')
# recList = OrderedDict()
recList = self.getDirectories(self.dataLocation)
for r in recList:
print(' %s %s' % (r, recIdx))
recIdx += 1
print('Choose the recordings for analysis by typing the index, e.g, \'1\', or \'0,1,3,5\', or \'0-5\' : ', end='')
recInput = input()
if '-' in recInput:
startEnd = [int(i) for i in recInput.split('-')]
recInputIdxRaw = [i for i in range(startEnd[0],startEnd[1]+1)]
else:
recInputIdxRaw = [int(i) for i in recInput.split(',')]
#TODO : allow for 'some' recordings of a given day to be picked
recIdx = 0
recIdx2 = 0
#rec820Idx = 0
for eD in expDateList:
for fold in dataFolders:
self.dataLocation = self.dataBase + self.dataPCLocation[dataFolders[fold]['recComputer']] + fold + '/'
recList = self.getDirectories(self.dataLocation)
for r in range(len(recList)):
if recIdx in recInputIdxRaw:
dirs = self.getDirectories(self.dataLocation + '/' + recList[r])
if (len(dirs) == 1) and (dirs[0]=='CameraGigEBehavior') : # 820 recording
recInputIdx.append([recIdx2 + r, eD, r, [i for i in range(1)]])
else:
recInputIdx.append([recIdx2 + r,eD, r, [i for i in range(len(dirs))]])
#pdb.set_trace()
recIdx+=1
recIdx2 += len(recList)
#print(recInputIdx)
#pdb.set_trace()
elif recordings == 'all':
print('All MLI and PC recordings will be analyzed')
recIdx = 0
recInputIdx = []
for eD in expDateList:
dataFolders = self.listOfAllExpts[self.mouse]['dates'][eD]['folders']
if 'recsMLI' in self.expDict[eD]:
#idx910 = self.expDict[eD]['recs910']['recordings']
idx910recs = list(self.expDict[eD]['recsMLI'].keys())
else:
idx910recs = None
if 'recsPC' in self.expDict[eD]:
#idx820 = self.expDict[eD]['recs820']['recordings']
idx820recs = list(self.expDict[eD]['recsPC'].keys())
else:
idx820recs = None
if 'recsBehavior' in self.expDict[eD]:
#idx820 = self.expDict[eD]['recs820']['recordings']
idxBehrecs = list(self.expDict[eD]['recsBehavior'].keys())
else:
idxBehrecs = None
for fold in dataFolders:
#print(' ', fold)
self.dataLocation = self.dataBase + self.dataPCLocation[dataFolders[fold]['recComputer']] + fold + '/'
recList = self.getDirectories(self.dataLocation)
#print(recList)
if idx910recs is not None:
idx910recs = [int(i) for i in idx910recs]
for n in range(len(idx910recs)):
trials = self.expDict[eD]['recsMLI'][str(idx910recs[n])]['trials']
if 'visuallyGuided' in self.expDict[eD]['recsMLI'][str(idx910recs[n])].keys():
visGuided = ['MLI',True]
else:
visGuided = ['MLI',False]
#if trials=='all':
# trials = [i for i in range(5)] # assume to include all five trials if 'trials' subfield does not exist in the config file
trials = [trials]
#recInputIdx.append([recIdx+idx910recs[n],idx910recs[n],trials])
recInputIdx.append([recIdx,eD, idx910recs[n], trials, visGuided])
if idx820recs is not None:
idx820recs = [int(i) for i in idx820recs]
for n in range(len(idx820recs)):
trials = self.expDict[eD]['recsPC'][str(idx820recs[n])]['trials']
if 'visuallyGuided' in self.expDict[eD]['recsPC'][str(idx820recs[n])].keys():
visGuided = ['PC',True]
else:
visGuided = ['PC',False]
#if trials=='all':
# trials = [i for i in range(1)] # assume to include all five trials if 'trials' subfield does not exist in the config file
trials = [trials]
#recInputIdx.append([recIdx+idx820recs[n],idx820recs[n],trials])
recInputIdx.append([recIdx,eD, idx820recs[n], trials, visGuided])
if idxBehrecs is not None:
idxBehrecs = [int(i) for i in idxBehrecs]
for n in range(len(idxBehrecs)):
trials = self.expDict[eD]['recsBehavior'][str(idxBehrecs[n])]['trials']
if 'visuallyGuided' in self.expDict[eD]['recsBehavior'][str(idxBehrecs[n])].keys():
visGuided = ['Beh',True]
else:
visGuided = ['Beh',False]
#if trials=='all':
# trials = [i for i in range(1)] # assume to include all five trials if 'trials' subfield does not exist in the config file
trials = [trials]
#recInputIdx.append([recIdx+idx820recs[n],idx820recs[n],trials])
recInputIdx.append([recIdx,eD, idxBehrecs[n], trials, visGuided])
recIdx+=len(recList)
else:
recInputIdx = [int(i) for i in recordings.split(',')]
print('list of recordings : ', recInputIdx)
# print(recordings)
#
# then compile a list the selected recordings
recIdx = 0
for eD in expDateList:
# print(expDateList, self.listOfAllExpts[mouse]['dates'], len(self.listOfAllExpts[mouse]['dates']))
dataFolders = self.listOfAllExpts[self.mouse]['dates'][eD]['folders']
# print(eD, self.listOfAllExpts[mouse]['dates'],dataFolders)
for fold in dataFolders:
# self.dataLocation = (self.dataBase2 + fold + '/') if eD >= '181018' else (self.dataBase + fold + '/')
# pdb.set_trace()
self.dataLocation = self.dataBase + self.dataPCLocation[dataFolders[fold]['recComputer']] + fold + '/'
self.recordingMachine = self.computerDict[dataFolders[fold]['recComputer']]
#print(self.dataLocation)
if not os.path.exists(self.dataLocation):
# print('experiment %s exists' % fold)
# else:
print('Problem, experiment does not exist')
recList = self.getDirectories(self.dataLocation)
#pdb.set_trace()
for j in range(len(recInputIdx)):
if recInputIdx[j][1] == eD:
#print(recInputIdx[j])
if j>0:
if recInputIdx[j][1] == recInputIdx[j-1][1]: # restart to count the recording index if two cells where recorded at the same day
recIdx -= len(recList)
tempRecList = []
for r in recList: # loop over list of actually saved recordings on the backup machine
#print(fold, eD, r, j, recIdx,(recInputIdx[j][0] + np.array(recInputIdx[j][3])))
# only add recordings which were previously selected
#print([recIdx == (f[0] + np.arange(2)) for f in recInputIdx])
#if np.any(np.hstack([recIdx == (f[0]+np.array(f[3])) for f in recInputIdx[j]])): # check whether recIdx matches any of the first indicies of the recInputIdx list
if np.any((recIdx == (recInputIdx[j][0] + np.array(recInputIdx[j][3])))): # for f in recInputIdx[j]])):
# if r[:-4] == 'locomotionTriggerSIAndMotor' or r[:-4] == 'locomotionTriggerSIAndMotorJin' or r[:-4] == 'locomotionTriggerSIAndMotor60sec':
# for i in range(len(recInputIdx)):
# if recIdx == recInputIdx[i][0] :
# recInfo = recInputIdx[i]
# consistency check
#print('r and recinfo : ',r, recInfo, recInfo[3], int(r[-3:]))
#if np.all(np.array(recInfo[3]) != int(r[-3:])):
if recordings == 'some':
tempRecList.append(r)
else:
if np.all(np.array(recInputIdx[j][3]) != int(r[-3:])):
print('Something wrong with the recording number!')
print(recInputIdx[j][3], r)
#pdb.set_trace()
else:
tempRecList.append(r)
recIdx += 1
folderRec.append([fold, eD, tempRecList])
#pdb.set_trace()
print('Data was recorded on %s' % self.recordingMachine)
return (folderRec, dataFolders,recInputIdx)
############################################################
def getDirectories(self, location):
# seqFolder = self.dataLocation + '/' + r
subFolders = [os.path.join(o) for o in os.listdir(location) if os.path.isdir(os.path.join(location, o))]
# Create a list of subfolders to remove ('2023' or '2022')
subfolders_to_remove = ['2023', '2022']
# Remove the subfolders to_remove from the subFolders list
subFolders = [subfolder for subfolder in subFolders if
not any(item in subfolder for item in subfolders_to_remove)]
subFolders.sort()
return subFolders
def getCaImagingRoiData(self, caAnalysisLocation):
# frameNumbers = []
# timeStamps = []
# for i in range(len(tiffList)):
# data = ScanImageTiffReader(tiffList[i]).data()
# fN = np.shape(data)[0]
# frameNumbers.append(fN)
# for n in range(fN):
# timeStamps.append(self.readTimeStampOfRecording(tiffList[i],n))
# pdb.set_trace()
if os.path.isdir(caAnalysisLocation):
# timeStamps = np.load(caAnalysisLocation + '/suite2p/plane0/timeStamps.npy')
F = np.load(caAnalysisLocation + '/suite2p/plane0/F.npy')
# if len(timeStamps) == 2*np.shape(F)[1]:
# timeStamps = timeStamps[::2]
Fneu = np.load(caAnalysisLocation + '/suite2p/plane0/Fneu.npy')
ops = np.load(caAnalysisLocation + '/suite2p/plane0/ops.npy',allow_pickle=True)
ops = ops.item()
iscell = np.load(caAnalysisLocation + '/suite2p/plane0/iscell.npy')
stat = np.load(caAnalysisLocation + '/suite2p/plane0/stat.npy',allow_pickle=True)
spks = np.load(caAnalysisLocation + '/suite2p/plane0/spks.npy',allow_pickle=True)
# pdb.set_trace()
nRois = np.arange(len(F))
realCells = (iscell[:, 0] == 1)
nRois = nRois[realCells]
Fluo = F[realCells] - 0.7 * Fneu[realCells] # substract neuropil data
stat = stat[realCells]
# pdb.set_trace()
# if gcampVersion=='jrgeco':
# return (Fluo, nRois, ops, stat, spks, Fneu,iscell,F)
# else:
return (Fluo, nRois, ops, stat)