-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlidingWindowAnalysisFunc.py
384 lines (313 loc) · 18.1 KB
/
SlidingWindowAnalysisFunc.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 09:33:08 2019
@author: thugwithyoyo
"""
import numpy as np
import pandas as pd
from PeriEventTraceFuncLib import *
from collections import defaultdict
import os
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
# Paths to data in JSON formatted files.
# NOTE: These have been commented out so that the SlidingWindowAnalysisFunc
# function can be called without these global level variables being
# intitialized.
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-31-41_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-31-41_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2019-01-07-10-31-41/2019-01-07-10-31-41_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-45-52_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-45-52_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2019-01-07-10-45-52/2019-01-07-10-45-52_new_unique_400ms_SamFiltered'
################### Analyses run ###############
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-11-21/2018-11-21-10-49-56_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-11-21/2018-11-21-10-49-56_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-11-21-10-49-56/2018-11-21-10-49-56_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-11-26/2018-11-26-11-45-46_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-11-26/2018-11-26-11-45-46_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-11-26-11-45-46/2018-11-26-11-45-46_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-04/2018-12-04-10-31-21_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-04/2018-12-04-10-31-21_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-12-04-10-31-21/2018-12-04-10-31-21_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-10/2018-12-10-11-37-56_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-10/2018-12-10-11-37-56_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-12-10-11-37-56/2018-12-10-11-37-56_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-11/2018-12-11-10-53-04_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-11/2018-12-11-10-53-04_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-12-11-10-53-04/2018-12-11-10-53-04_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-14/2018-12-14-11-01-41_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-14/2018-12-14-11-01-41_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-12-14-11-01-41/2018-12-14-11-01-41_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-17/2018-12-17-11-38-42_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-17/2018-12-17-11-38-42_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-12-17-11-38-42/2018-12-17-11-38-42_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-18/2018-12-18-11-20-21_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-18/2018-12-18-11-20-21_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-12-18-11-20-21/2018-12-18-11-20-21_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-19/2018-12-19-11-24-58_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2018-12-19/2018-12-19-11-24-58_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2018-12-19-11-24-58/2018-12-19-11-24-58_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-31-41_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-31-41_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2019-01-07-10-31-41/2019-01-07-10-31-41_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-45-52_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-07/2019-01-07-10-45-52_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2019-01-07-10-45-52/2019-01-07-10-45-52_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-24/2019-01-24-11-36-02_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-24/2019-01-24-11-36-02_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2019-01-24-11-36-02/2019-01-24-11-36-02_new_unique_400ms_SamFiltered'
#PathToBehavFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-24/2019-01-24-11-50-23_new_unique_B.json'
#PathToFluorFile = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData/2019-01-24/2019-01-24-11-50-23_new_unique_C.json'
#SavePath = '/home/thugwithyoyo/CaTransDecoding/Output/2019-01-24-11-50-23/2019-01-24-11-50-23_new_unique_400ms_SamFiltered'
# Define ParamsDict, the dictionary that contains the parameters for
# PLS decoding, Bootstrapping, Shuffle control processes.
# Peripheral target entry events
ParamsDict = defaultdict(dict)
#ParamsDict['RefEventsList'] = ['M6T0_Entry_ts', 'M7T1_Entry_ts']
#ParamsDict['RefEventsList'] = ['M6T0_Entry_ts', 'M6T1_Entry_ts']
ParamsDict['RefEventsList'] = ['M7T0_Entry_ts', 'M7T1_Entry_ts']
# Scalar values assigned to event types listed above.
ParamsDict['AssignedEventVals'] = [-1, 1]
# Set parameters for peri-event extraction
ParamsDict['BoundaryWindow'] = [-2., 2.]
ParamsDict['StepWidth'] = 0.1
ParamsDict['WindowWidth'] = 0.4
ParamsDict['NumLatents'] = 5
ParamsDict['NumRepetitions'] = 30
ParamsDict['ConfLevel'] = 0.95
ParamsDict['RelativeTolWindow'] = (0.0001, 2.5)
def SlidingWindowAnalysisFunc(BehavDict, CellFluorTraces_Frame, SavePath, ParamsDict):
# Peripheral target entry events
#Params.RefEventsList = ['M6T0_Entry_ts', 'M6T1_Entry_ts']
# Scalar values assigned to event types listed above.
#ParamsDict.AssignedEventVals = [-1, 1]
# Pack into a dict the two lists above that specify info for reference
# events
RefEventsDict = {'RefEventsList' : ParamsDict['RefEventsList'],
'AssignedEventVals' : ParamsDict['AssignedEventVals']}
# Set parameters for peri-event extraction
#ParamsDict.BoundaryWindow = [-1., 2.]
#ParamsDict.StepWidth = 0.1
#ParamsDict.WindowWidth = 0.4
ArrayOfSlidWindows = SlidingWindowGen(ParamsDict['BoundaryWindow'],
ParamsDict['StepWidth'],
ParamsDict['WindowWidth'])
# Set parameters for PLS
#ParamsDict.NumLatents = 5
# Set parameters for Monte Carlo estimation of confidence intervals
#ParamsDict.NumRepetitions = 30
#ParamsDict.ConfLevel = 0.95
# Specified anti-tolerance window, relative to target entry, for detecting and
# removing repeat entries that followed shortly after the initial entry.
#ParamsDict.RelativeTolWindow = (0.0001, 2.5)
# Generate the unfiltered behavior dictionary.
if (type(BehavDict) == str):
PathToBehavFile = BehavDict
BehavDict = BehavDictGen(PathToBehavFile)
elif (type(BehavDict) == dict):
pass
# # Detect rapid repeats within each event list.
# EventFilters = RemoveRepeatTargetEntries(BehavDict,
# RefEventsDict['RefEventsList'],
# ParamsDict['RelativeTolWindow'])
#
# # Remove repeat events
# for ef in EventFilters:
#
# BehavDict[ef] = BehavDict[ef][EventFilters[ef]]
#
# # Determine lowest number of occurances among event types.
# MinNumOccurences = BehavDict[ParamsDict['RefEventsList'][0]].shape[0]
# MinEventType = ParamsDict['RefEventsList'][0]
#
# for e in ParamsDict['RefEventsList']:
#
# NumOccurences = BehavDict[e].shape[0]
#
# if NumOccurences < MinNumOccurences:
#
# MinNumOccurences = NumOccurences
# MinEventType = e
#
# # Randomly draw, without replacement, the equivalent number of event occurances
# # from longer lists belonging to other event types.
# Filt = (np.array(ParamsDict['RefEventsList']) != MinEventType)
# EventListsToSample = np.array(ParamsDict['RefEventsList'])[Filt]
#
# for e in EventListsToSample:
#
# BehavDict[e] = pd.Series(np.random.choice(BehavDict[e],
# MinNumOccurences, replace=False))
# If a path is given in in place of a datafrom for the second arg, then
# import the dataframe from filepath string.
if type(CellFluorTraces_Frame) == str:
# Generate the data frame of calcium transients.
PathToFluorFile = CellFluorTraces_Frame
CellFluorTraces_Frame = CellFluorTraces_FrameGen(PathToFluorFile)
# Assemble dataframe of centroids.
CentroidFrame = CIFP.CellCentroidsFromJSON(PathToFluorFile)
elif type(CellFluorTraces_Frame) == pd.DataFrame:
pass
# Grow window forwards from floor
(NumDomains, _) = ArrayOfSlidWindows.shape
# Initialize an empty array to contain output dictionaries from the
# decoder cross-validation perfomance and monte carlo bootstrap routines
Performance = np.empty((NumDomains,), dtype=dict)
ConfInts = np.empty((NumDomains,), dtype=dict)
EventsShuffled = np.empty((NumDomains,), dtype=dict)
for i in np.arange(0, NumDomains):
PeriEventExtractorDict = PeriEventExtractor_Trace(BehavDict,
CellFluorTraces_Frame, RefEventsDict,
ArrayOfSlidWindows[i])
# Generate a set of indices to test the inclusion portion of the performance code.
PEA_Array = PeriEventExtractorDict['PEA_Array']
(NumTotalTrials, NumTotalFeatures) = PEA_Array.shape
#InclusionSet = np.random.randint(0, high=NumTotalTrials, size=(NumTotalTrials,))
Performance[i] = PLS_DecoderPerformance(PeriEventExtractorDict,
ParamsDict['NumLatents'])
Performance[i].update({'PeriEventDomain': ArrayOfSlidWindows[i]})
ConfInts[i] = PLS_MonteCarlo(PeriEventExtractorDict,
ParamsDict['NumLatents'],
ParamsDict['NumRepetitions'],
ParamsDict['ConfLevel'],
Performance[i])
ConfInts[i].update({'PeriEventDomain': ArrayOfSlidWindows[i]})
EventsShuffled[i] = PLS_Shuffle(PeriEventExtractorDict,
ParamsDict['NumLatents'],
ParamsDict['NumRepetitions'],
ParamsDict['ConfLevel'])
# EventsShuffled[i] = PLS_Shuffle2(PeriEventExtractorDict,
# ParamsDict['NumLatents'],
# ParamsDict['NumRepetitions'],
# ParamsDict['ConfLevel'])
EventsShuffled[i].update({'PeriEventDomain': ArrayOfSlidWindows[i]})
#####################################
######## Start shelving #########
#####################################
# Assemble save path
# get root directory of save path from path to calcium data
# SavePath is an arguement above. The following script requires it
exec(open('./ShelveWorkspaceScript.py').read())
###############################################################################
######### START EXECUTION SCRIPT #########
###############################################################################
# Acquire path of workspace to load.
# Set defualt parent directories
DataRootDir = '/home/thugwithyoyo/CaTransDecoding/CalciumImagingData'
SaveRootDir = '/home/thugwithyoyo/CaTransDecoding/Output'
# Start file dialogs
root = tk.Tk()
# Prompt user to navigate to, and select, the session behavior file
PathToBehavFile = askopenfilename(title='Select session behavior file',
filetypes=[("json files","*.json"),
("csv files", "*.csv")],
initialdir=DataRootDir)
# Prompt user to navigate to, and select, the session imaging file
PathToFluorFile = askopenfilename(title='Select session fluorescence record file',
filetypes=[("json files","*.json"),
("csv files", "*.csv")],
initialdir=DataRootDir)
# Determine parent directory and filename from complete path.
Drive, Path_and_file = os.path.splitdrive(PathToBehavFile)
Path, File = os.path.split(Path_and_file)
# Extract session id from filename
SessionID = File[0:19]
# Construct a workspace filename to use as save default
SaveFilename = SessionID + '_new_unique_400ms_SamFiltered'
DefaultSavePath = SaveRootDir + os.path.sep + SessionID
# Prompt user to select default
SavePath = asksaveasfilename(title='Set workspace save path',
initialdir=DefaultSavePath,
initialfile=SaveFilename)
# End file dialogs
root.withdraw()
# Run sliding window analysis using above-defined subroutine.
SlidingWindowAnalysisFunc(PathToBehavFile, PathToFluorFile, SavePath, ParamsDict)
#SlidingWindowAnalysisFunc(PathToBehavFile, FluorDataframe_Combined, SavePath, ParamsDict)
#SlidingWindowAnalysisFunc(BehavDict_Combined, CaImag_df_Combined, SavePath, ParamsDict)
# Figure generation code below moved to GenerateDecodePlotsScript.py. Use the
# script to generate plots from shelved workspaces generated from above-called function.
#
#RestoreFilePath = SavePath +'.dat'
#exec(open('./RestoreShelvedWorkspaceScript.py').read())
#
##### Plot outcome measures #####
#
## Specify outcome measures to be plotted
##PerformancePlotSpecDict = {'measure': 'performance',
## 'measure_median': 'performance_median',
## 'measure_CLs': 'performance_CLs'}
##
##ShuffledPerformancePlotSpecDict = {'measure': 'performance_median',
## 'measure_median': 'performance_median',
## 'measure_CLs': 'performance_CLs'}
##
##MutInfoPlotSpecDict = {'measure': 'mutual_info',
## 'measure_median': 'mutual_info_median',
## 'measure_CLs': 'mutual_info_CLs'}
##
##ShuffledMutInfoPlotSpecDict = {'measure': 'mutual_info_median',
## 'measure_median': 'mutual_info_median',
## 'measure_CLs': 'mutual_info_CLs'}
#
## Plot performance dependence on increasing peri-event window span
## Define figure name
#drive, path_and_file = os.path.splitdrive(PathToBehavFile)
#path, file = os.path.split(path_and_file)
#FigureTitle = file[:-7]
#
## Initialize figure
#fig1, axs1 = plt.subplots()
#fig1.suptitle(FigureTitle)
#
## Plot performance and performance control plots
#PlotSpecDict = {'measure': 'performance',
# 'measure_median': 'performance_median',
# 'measure_CLs': 'performance_CLs',
# 'measure_SE': 'performance_SE',
# 'color':'blue'}
#
#GenerateConfIntsPlot(ConfInts, Performance, PlotSpecDict,
# axs1, 'fw_sliding')
#
#PlotSpecDict = {'measure': 'performance_median',
# 'measure_median': 'performance_median',
# 'measure_CLs': 'performance_CLs',
# 'measure_SE': 'performance_SE',
# 'color':'lightblue'}
#
#GenerateConfIntsPlot(EventsShuffled, EventsShuffled, PlotSpecDict,
# axs1, 'fw_sliding')
#
#axs1.set_xbound(lower=ParamsDict['BoundaryWindow'][0],
# upper=ParamsDict['BoundaryWindow'][1])
#axs1.set_ybound(lower=0.4, upper=1.)
#
## Plot mutual information and mutual information control plots
#fig2, axs2 = plt.subplots()
#fig2.suptitle(FigureTitle)
#
#PlotSpecDict = {'measure': 'mutual_info',
# 'measure_median': 'mutual_info_median',
# 'measure_CLs': 'mutual_info_CLs',
# 'measure_SE': 'mutual_info_SE',
# 'color':'blue'}
#
#GenerateConfIntsPlot(ConfInts, Performance, PlotSpecDict,
# axs2, 'fw_sliding')
#
#PlotSpecDict = {'measure': 'mutual_info_median',
# 'measure_median': 'mutual_info_median',
# 'measure_CLs': 'mutual_info_CLs',
# 'measure_SE': 'mutual_info_SE',
# 'color':'lightblue'}
#
#GenerateConfIntsPlot(EventsShuffled, EventsShuffled, PlotSpecDict,
# axs2, 'fw_sliding')
#
#axs2.set_xbound(lower=ParamsDict['BoundaryWindow'][0],
# upper=ParamsDict['BoundaryWindow'][1])
#axs2.set_ybound(lower=0., upper=1.)