-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSweep_analysis.py
2428 lines (1669 loc) · 113 KB
/
Sweep_analysis.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 4 14:22:09 2023
@author: julienballbe
"""
import pandas as pd
import numpy as np
import plotnine as p9
import scipy
from lmfit.models import Model, QuadraticModel, ExponentialModel, ConstantModel
from lmfit import Parameters
from sklearn.metrics import mean_squared_error, root_mean_squared_error
import importlib
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import traceback
import Ordinary_functions as ordifunc
import Spike_analysis as sp_an
import Firing_analysis as fir_an
import matplotlib.pyplot as plt
def sweep_analysis_processing(cell_Full_TVC_table, cell_stim_time_table, nb_workers):
'''
Create cell_sweep_info_table using parallel processing.
For each sweep contained in cell_Full_TVC_table, extract different recording information (Bridge Error, sampling frequency),
stimulus and voltage trace information (holding current, resting voltage...),
and trace-computed linear properties if possible (membrane time constant, input resistance)
Parameters
----------
cell_Full_TVC_table : pd.DataFrame
2 columns DataFrame, cotaining in column 'Sweep' the sweep_id and in the column 'TVC' the corresponding 3 columns DataFrame containing Time, Current and Potential Traces
cell_stim_time_table : pd.DataFrame
DataFrame, containing foir each Sweep the corresponding stimulus start and end times.
nb_workers : int
Number of CPU cores to use for parallel processing.
Returns
-------
cell_sweep_info_table : pd.DataFrame
DataFrame containing the information about the different traces for each sweep (one row per sweep).
'''
cell_sweep_info_table = pd.DataFrame(columns=['Sweep', 'Protocol_id', 'Trace_id', 'Stim_SS_pA', 'Holding_current_pA','Stim_amp_pA', 'Stim_start_s', 'Stim_end_s', 'Bridge_Error_GOhms', 'Bridge_Error_extrapolated', 'Sampling_Rate_Hz'])
cell_Full_TVC_table.index.name = 'Index'
cell_Full_TVC_table = cell_Full_TVC_table.sort_values(by=['Sweep'])
cell_stim_time_table.index.name = 'Index'
cell_stim_time_table = cell_stim_time_table.sort_values(by=['Sweep'])
sweep_list = np.array(cell_Full_TVC_table['Sweep'], dtype=str)
cell_sweep_info_table = get_sweep_info_loop(cell_Full_TVC_table, cell_stim_time_table)
### create table of trace data
extrapolated_BE = pd.DataFrame(columns=['Sweep', 'Bridge_Error_GOhms'])
cell_sweep_info_table['Bridge_Error_GOhms']=removeOutliers(
np.array(cell_sweep_info_table['Bridge_Error_GOhms']), 3)
cell_sweep_info_table.index = cell_sweep_info_table.loc[:, 'Sweep']
cell_sweep_info_table.index = cell_sweep_info_table.index.astype(str)
cell_sweep_info_table.index.name = 'Index'
### Create Linear properties table
TVC_list = []
for x in sweep_list:
current_TVC = ordifunc.get_filtered_TVC_table(cell_Full_TVC_table, x, do_filter=True, filter=5., do_plot=False)
TVC_list.append(current_TVC)
stim_start_time_list = list(cell_stim_time_table.loc[:,'Stim_start_s'])
stim_end_time_list = list(cell_stim_time_table.loc[:,'Stim_end_s'])
sweep_info_zip = zip(TVC_list,sweep_list,stim_start_time_list,stim_end_time_list)
sweep_info_list= list(sweep_info_zip)
Linear_table=pd.DataFrame(columns=['Sweep',"Time_constant_ms", 'Input_Resistance_GOhms', 'Holding_potential_mV','SS_potential_mV','Resting_potential_mV'])
cell_sweep_info_table = cell_sweep_info_table.sort_values(by=['Sweep'])
stim_start_time_list = list(cell_sweep_info_table.loc[:,'Stim_start_s'])
stim_end_time_list = list(cell_sweep_info_table.loc[:,'Stim_end_s'])
BE_extrapolated_list = list(cell_sweep_info_table.loc[:,'Bridge_Error_extrapolated'])
BE_list = list(cell_sweep_info_table.loc[:,'Bridge_Error_GOhms'])
stim_amp_list = list(cell_sweep_info_table.loc[:,'Stim_amp_pA'])
sweep_info_zip = zip(TVC_list,sweep_list,stim_start_time_list,stim_end_time_list, BE_extrapolated_list, BE_list, stim_amp_list)
sweep_info_list= list(sweep_info_zip)
for x in sweep_info_list:
result = get_sweep_linear_properties(x)
Linear_table = pd.concat([
Linear_table,result], ignore_index=True)
cell_sweep_info_table = cell_sweep_info_table.merge(
Linear_table, how='inner', on='Sweep')
### For sweeps whose Brige Error couldn't be estimated, extrapolate from neighboring traces (protocol_wise)
for current_Protocol in cell_sweep_info_table['Protocol_id'].unique():
reduced_cell_sweep_info_table = cell_sweep_info_table[
cell_sweep_info_table['Protocol_id'] == current_Protocol]
reduced_cell_sweep_info_table=reduced_cell_sweep_info_table.astype({"Trace_id":"int"})
reduced_cell_sweep_info_table=reduced_cell_sweep_info_table.sort_values(by=['Trace_id'])
BE_array = np.array(
reduced_cell_sweep_info_table['Bridge_Error_GOhms'])
sweep_array = np.array(reduced_cell_sweep_info_table['Sweep'])
nan_ind_BE = np.isnan(BE_array)
x = np.arange(len(BE_array))
if False in nan_ind_BE:
BE_array[nan_ind_BE] = np.interp(
x[nan_ind_BE], x[~nan_ind_BE], BE_array[~nan_ind_BE])
extrapolated_BE_Series = pd.Series(BE_array)
sweep_array = pd.Series(sweep_array)
extrapolated_BE_Series = pd.DataFrame(
pd.concat([sweep_array, extrapolated_BE_Series], axis=1))
extrapolated_BE_Series.columns = ['Sweep', 'Bridge_Error_GOhms']
extrapolated_BE = pd.concat(
[extrapolated_BE,extrapolated_BE_Series], ignore_index=True)
cell_sweep_info_table.pop('Bridge_Error_GOhms')
cell_sweep_info_table = cell_sweep_info_table.merge(
extrapolated_BE, how='inner', on='Sweep')
cell_sweep_info_table = cell_sweep_info_table.loc[:, ['Sweep',
"Protocol_id",
'Trace_id',
'Stim_amp_pA',
'Stim_SS_pA',
'Holding_current_pA',
'Stim_start_s',
'Stim_end_s',
'Bridge_Error_GOhms',
'Bridge_Error_extrapolated',
'Time_constant_ms',
'Input_Resistance_GOhms',
'Holding_potential_mV',
"SS_potential_mV",
"Resting_potential_mV",
'Sampling_Rate_Hz']]
cell_sweep_info_table.index = cell_sweep_info_table.loc[:, 'Sweep']
cell_sweep_info_table.index = cell_sweep_info_table.index.astype(str)
cell_sweep_info_table.index.name = 'Index'
convert_dict = {'Sweep': str,
'Protocol_id': str,
'Trace_id': int,
'Stim_amp_pA': float,
'Holding_current_pA':float,
'Stim_SS_pA':float,
'Stim_start_s': float,
'Stim_end_s': float,
'Bridge_Error_GOhms': float,
'Bridge_Error_extrapolated': bool,
'Time_constant_ms': float,
'Input_Resistance_GOhms': float,
'Holding_potential_mV':float,
"SS_potential_mV": float,
"Resting_potential_mV":float,
'Sampling_Rate_Hz': float
}
cell_sweep_info_table = cell_sweep_info_table.astype(convert_dict)
### Remove extremes outliers of Time_constant and Input_Resistance (Q1/Q3 ± 3IQR)
remove_outier_columns = ['Time_constant_ms', 'Input_Resistance_GOhms']
for current_column in remove_outier_columns:
cell_sweep_info_table.loc[:, current_column] = removeOutliers(
np.array(cell_sweep_info_table.loc[:, current_column]), 3)
cell_sweep_info_table.index = cell_sweep_info_table.loc[:, 'Sweep']
cell_sweep_info_table.index = cell_sweep_info_table.index.astype(str)
cell_sweep_info_table.index.name = 'Index'
return cell_sweep_info_table
def get_sweep_info_loop(cell_Full_TVC_table, cell_stim_time_table):
'''
Function to be used in parallel to extract or compute different sweep related information
Parameters
----------
sweep_info_list : List
List of parameters required by the function.
Returns
-------
output_line : pd.DataFrame
One Row DataFrame containing different sweep related information.
'''
cell_sweep_info_table = pd.DataFrame(columns=['Sweep', 'Protocol_id', 'Trace_id', 'Stim_SS_pA', 'Holding_current_pA','Stim_amp_pA', 'Stim_start_s', 'Stim_end_s', 'Bridge_Error_GOhms', 'Bridge_Error_extrapolated', 'Sampling_Rate_Hz'])
sweep_list = cell_Full_TVC_table.loc[:,'Sweep']
for current_sweep in sweep_list:
stim_start_time = cell_stim_time_table.loc[current_sweep,'Stim_start_s']
stim_end_time = cell_stim_time_table.loc[current_sweep,'Stim_end_s']
filtered_TVC_table = ordifunc.get_filtered_TVC_table(cell_Full_TVC_table, current_sweep, do_filter=True, filter=5., do_plot=False)
unfiltered_TVC_table = ordifunc.get_filtered_TVC_table(cell_Full_TVC_table, current_sweep, do_filter=False, filter=5., do_plot=False)
if len(str(current_sweep).split("_")) == 1:
Protocol_id = str(1)
Trace_id = current_sweep
elif len(str(current_sweep).split("_")) == 2 :
Protocol_id, Trace_id = str(current_sweep).split("_")
else :
Protocol_id, Trace_id = str(current_sweep).split("_")[-2:]
Protocol_id=str(Protocol_id)
Holding_current,SS_current = fit_stimulus_trace(
filtered_TVC_table, stim_start_time, stim_end_time,do_plot=False)[:2]
if np.abs((Holding_current-SS_current))>=20.:
# Bridge_Error= estimate_bridge_error(
# TVC_table, SS_current, stim_start_time, stim_end_time, do_plot=False)
Bridge_Error = estimate_bridge_error_test(unfiltered_TVC_table, SS_current, stim_start_time, stim_end_time, do_plot=False)[0]
else:
Bridge_Error=np.nan
if np.isnan(Bridge_Error):
BE_extrapolated = True
else:
BE_extrapolated = False
time_array = np.array(unfiltered_TVC_table.loc[:,"Time_s"])
sampling_rate = 1/(time_array[1]-time_array[0])
stim_amp = SS_current - Holding_current
output_line = pd.DataFrame([str(current_sweep),
str(Protocol_id),
Trace_id,
SS_current,
Holding_current,
stim_amp,
stim_start_time,
stim_end_time,
Bridge_Error,
BE_extrapolated,
sampling_rate]).T
output_line.columns=['Sweep', 'Protocol_id', 'Trace_id', 'Stim_SS_pA', 'Holding_current_pA','Stim_amp_pA', 'Stim_start_s', 'Stim_end_s', 'Bridge_Error_GOhms', 'Bridge_Error_extrapolated', 'Sampling_Rate_Hz']
cell_sweep_info_table = pd.concat([cell_sweep_info_table, output_line], ignore_index = True)
return cell_sweep_info_table
def get_sweep_linear_properties(sweep_info_list):
'''
Function to be used in parallel to compute different sweep based linear properties
Parameters
----------
sweep_info_list : List
List of parameters required by the function.
Returns
-------
sweep_line : pd.DataFrame
One Row DataFrame containing different sweep based linear properties
'''
TVC_table, sweep, stim_start, stim_end, BE_extrapolated, BE, stim_amp = sweep_info_list
sub_test_TVC=TVC_table[TVC_table['Time_s']<=stim_start-.005].copy()
sub_test_TVC=sub_test_TVC=sub_test_TVC[sub_test_TVC['Time_s']>=(stim_start-.200)]
CV_pre_stim=np.std(np.array(sub_test_TVC['Membrane_potential_mV']))/np.mean(np.array(sub_test_TVC['Membrane_potential_mV']))
voltage_spike_table = sp_an.identify_spike(np.array(TVC_table.Membrane_potential_mV),
np.array(TVC_table.Time_s),
np.array(TVC_table.Input_current_pA),
stim_start,
(stim_start+stim_end)/2,do_plot=False)
if len(voltage_spike_table['Peak']) != 0:
is_spike = True
else:
is_spike = False
sub_test_TVC=TVC_table[TVC_table['Time_s']<=(stim_end)].copy()
sub_test_TVC=sub_test_TVC[sub_test_TVC['Time_s']>=((stim_start+stim_end)/2)]
CV_second_half=np.std(np.array(sub_test_TVC['Membrane_potential_mV']))/np.mean(np.array(sub_test_TVC['Membrane_potential_mV']))
if (is_spike == True or
np.abs(stim_amp)<2.0 or
np.abs(CV_pre_stim) > 0.01 or
np.abs(CV_second_half) > 0.01):
SS_potential = np.nan
resting_potential = np.nan
holding_potential = np.nan
R_in = np.nan
time_cst = np.nan
else:
best_A,best_tau,SS_potential,holding_potential,NRMSE = fit_membrane_time_cst(TVC_table,
stim_start,
(stim_start+.300),do_plot=False)
if NRMSE > 0.3 or np.isnan(NRMSE) == True:
SS_potential = np.nan
resting_potential = np.nan
R_in = np.nan
time_cst = np.nan
else:
Holding_current,SS_current = fit_stimulus_trace(
TVC_table, stim_start, stim_end, do_plot=False)[:2]
R_in=((SS_potential-holding_potential)/stim_amp)-BE
time_cst=best_tau*1e3 #convert s to ms
resting_potential = holding_potential - (R_in+BE)*Holding_current
sweep_line=pd.DataFrame([str(sweep),time_cst,R_in,holding_potential,SS_potential,resting_potential]).T
sweep_line.columns=['Sweep',"Time_constant_ms", 'Input_Resistance_GOhms', 'Holding_potential_mV','SS_potential_mV','Resting_potential_mV']
return sweep_line
def removeOutliers(x, outlierConstant=3):
'''
Remove from an array outliers defined by values x<Q1-nIQR or x>Q3+nIQR
with x a value in array and n the outlierConstant
Parameters
----------
x : np.array or list
Values from whihc remove outliers.
outlierConstant : int, optional
The number of InterQuartile Range to define outleirs. The default is 3.
Returns
-------
np.array
x array without outliers.
'''
a = np.array(x)
upper_quartile = np.nanpercentile(a, 75)
lower_quartile = np.nanpercentile(a, 25)
IQR = (upper_quartile - lower_quartile) * outlierConstant
quartileSet = (lower_quartile - IQR, upper_quartile + IQR)
resultList = []
for y in a.tolist():
if y >= quartileSet[0] and y <= quartileSet[1]:
resultList.append(y)
else:
resultList.append(np.nan)
return np.array(resultList)
def fit_stimulus_trace(TVC_table_original,stim_start,stim_end,do_plot=False):
'''
Fit double Heaviside function to the time-varying trace representing the input current.
The Trace is low-pass filtered at 1kHz, and the fit is weighted to the inverse of the time derivative of the trace
Parameters
----------
TVC_table_original : Tpd.DataFrame
Contains the Time, voltage, Current and voltage 1st and 2nd derivatives arranged in columns.
stim_start : Float
Stimulus start time.
stim_end : Float
Stimulus end time.
do_plot : Boolean, optional
Do plot. The default is False.
Returns
-------
best_baseline ,best_stim_amp, best_stim_start, best_stim_end : Float
Fitting results.
NRMSE_double_Heaviside : Float
Godness of fit.
'''
TVC_table=TVC_table_original.copy()
stim_table=TVC_table.loc[:,['Time_s','Input_current_pA']].copy()
stim_table = stim_table.reset_index(drop=True)
x_data=stim_table.loc[:,"Time_s"]
index_stim_start=next(x for x, val in enumerate(x_data[0:]) if val >= stim_start )
index_stim_end=next(x for x, val in enumerate(x_data[0:]) if val >= (stim_end) )
stim_table['Input_current_pA']=np.array(ordifunc.filter_trace(stim_table['Input_current_pA'],
stim_table['Time_s'],
filter=1.,
do_plot=False))
first_current_derivative=ordifunc.get_derivative(np.array(stim_table["Input_current_pA"]),np.array(stim_table["Time_s"]))
#first_current_derivative=np.insert(first_current_derivative,0,first_current_derivative[0])
stim_table['Filtered_Stimulus_trace_derivative_pA/ms']=np.array(first_current_derivative)
before_stim_start_table=stim_table[stim_table['Time_s']<stim_start-.01]
baseline_current=np.mean(before_stim_start_table['Input_current_pA'])
during_stimulus_table=stim_table[stim_table['Time_s']<stim_end]
during_stimulus_table=during_stimulus_table[during_stimulus_table['Time_s']>stim_start]
estimate_stim_amp=np.median(during_stimulus_table.loc[:,'Input_current_pA'])
y_data=stim_table.loc[:,"Input_current_pA"]
stim_table['weight']=np.abs(1/stim_table['Filtered_Stimulus_trace_derivative_pA/ms'])**2
weight=stim_table.loc[:,"weight"]
if np.isinf(weight).sum!=0:
if np.isinf(weight).sum() >= (len(weight)/2): # if inf values represent more than half the values
weight=np.ones(len(weight))
else: # otherwise replace inf values by the maximum value non inf
max_weight_without_inf=np.nanmax(weight[weight != np.inf])
weight.replace([np.inf], max_weight_without_inf, inplace=True)
weight/=np.nanmax(weight) # normalize the weigth to the maximum weight
double_step_model=Model(Double_Heaviside_function)
double_step_model_parameters=Parameters()
double_step_model_parameters.add('stim_start',value=stim_start,vary=False)
double_step_model_parameters.add('stim_end',value=stim_end,vary=False)
double_step_model_parameters.add('baseline',value=baseline_current)
double_step_model_parameters.add('stim_amplitude',value=estimate_stim_amp)
#return stim_table
double_step_out=double_step_model.fit(y_data,double_step_model_parameters,x=x_data,weights=weight)
best_baseline=double_step_out.best_values['baseline']
best_stim_amp=double_step_out.best_values['stim_amplitude']
best_stim_start=double_step_out.best_values['stim_start']
best_stim_end=double_step_out.best_values['stim_end']
NRMSE_double_Heaviside=mean_squared_error(y_data.iloc[index_stim_start:index_stim_end], Double_Heaviside_function(x_data, best_stim_start, best_stim_end, best_baseline, best_stim_amp)[index_stim_start:index_stim_end],squared=(False))/(best_stim_amp)
if do_plot:
computed_y_data=pd.Series(Double_Heaviside_function(x_data, best_stim_start,best_stim_end, best_baseline, best_stim_amp))
model_table=pd.DataFrame({'Time_s' :x_data,
'Input_current_pA': computed_y_data})#np.column_stack((x_data,computed_y_data)),columns=['Time_s ',"Stim_amp_pA"])
TVC_table['Legend']='Original_Data'
stim_table['Legend']='Filtered_fitted_Data'
model_table['Legend']='Fit'
data_table = pd.concat([TVC_table,stim_table],ignore_index=True)
data_table = pd.concat([data_table,model_table],ignore_table = True)
my_plot = p9.ggplot()
my_plot += p9.geom_line(TVC_table, p9.aes(x='Time_s',y='Input_current_pA'),colour = 'black')
my_plot += p9.geom_line(stim_table,p9.aes(x='Time_s',y='Input_current_pA'),colour = 'red')
my_plot += p9.geom_line(model_table,p9.aes(x='Time_s',y='Input_current_pA'),colour='blue')
my_plot += p9.xlab(str("Time_s"))
my_plot += p9.xlim((stim_start-0.05), (stim_end+0.05))
print(my_plot)
return best_baseline,best_stim_amp,best_stim_start,best_stim_end,NRMSE_double_Heaviside
def estimate_bridge_error_test(original_TVC_table,stim_amplitude,stim_start_time,stim_end_time,do_plot=False):
'''
A posteriori estimation of bridge error, by estimating 'very fast' membrane voltage transient around stimulus start and end
Parameters
----------
original_TVC_table : pd.DataFrame
Contains the Time, voltage, Current and voltage 1st and 2nd derivatives arranged in columns.
stim_amplitude : float
Value of Stimulus amplitude (between stimulus start and end).
stim_start_time : float
Stimulus start time.
stim_end_time : float
Stimulus end time.
do_plot : TYPE, optional
If True, returns Bridge Error Plots. The default is False.
Returns
-------
if do_plot == True: return plots
if do_plot == False: return Bridge Error in GOhms
'''
try:
TVC_table=original_TVC_table.reset_index(drop=True).copy()
start_time_index = np.argmin(abs(np.array(TVC_table['Time_s']) - stim_start_time))
stimulus_baseline=np.mean(TVC_table.loc[:(start_time_index-1),'Input_current_pA'])
point_table=pd.DataFrame(columns=["Time_s","Membrane_potential_mV","Feature"])
Five_kHz_LP_filtered_current_trace = np.array(ordifunc.filter_trace(np.array(TVC_table.loc[:,'Input_current_pA']),
np.array(TVC_table.loc[:,'Time_s']),
filter=5,
filter_order=4,
zero_phase=True,
do_plot=False
))
current_trace_derivative_5kHz = np.array(ordifunc.get_derivative(Five_kHz_LP_filtered_current_trace,
np.array(TVC_table.loc[:,'Time_s'])))
#current_trace_derivative_5kHz=np.insert(current_trace_derivative_5kHz,0,np.nan)
TVC_table.loc[:,"I_dot_five_kHz"] = current_trace_derivative_5kHz
Five_kHz_LP_filtered_voltage_trace = np.array(ordifunc.filter_trace(np.array(TVC_table.loc[:,'Membrane_potential_mV']),
np.array(TVC_table.loc[:,'Time_s']),
filter=5,
filter_order=4,
zero_phase=True,
do_plot=False
))
voltage_trace_derivative_5kHz = np.array(ordifunc.get_derivative(Five_kHz_LP_filtered_voltage_trace,
np.array(TVC_table.loc[:,'Time_s'])))
voltage_trace_second_derivative_5kHz = np.array(ordifunc.get_derivative(voltage_trace_derivative_5kHz,
np.array(TVC_table.loc[:,'Time_s'])))
# voltage_trace_derivative_5kHz=np.insert(voltage_trace_derivative_5kHz,0,np.nan)
# voltage_trace_second_derivative_5kHz=np.insert(voltage_trace_second_derivative_5kHz,0,np.nan)
# voltage_trace_second_derivative_5kHz=np.insert(voltage_trace_second_derivative_5kHz,0,np.nan)
TVC_table.loc[:,"V_dot_five_kHz"] = voltage_trace_derivative_5kHz
TVC_table.loc[:,"V_double_dot_five_kHz"] = voltage_trace_second_derivative_5kHz
One_kHz_LP_filtered_voltage_trace = np.array(ordifunc.filter_trace(np.array(TVC_table.loc[:,'Membrane_potential_mV']),
np.array(TVC_table.loc[:,'Time_s']),
filter=1,
filter_order=4,
zero_phase = True,
do_plot=False
))
voltage_trace_derivative_1kHz = np.array(ordifunc.get_derivative(One_kHz_LP_filtered_voltage_trace,
np.array(TVC_table.loc[:,'Time_s'])))
#voltage_trace_derivative_1kHz=np.insert(voltage_trace_derivative_1kHz,0,np.nan)
TVC_table.loc[:,"V_dot_one_kHz"] = voltage_trace_derivative_1kHz
# Determine actual stimulus transition time and current step
stimulus_end_table = TVC_table.loc[(TVC_table["Time_s"]<=(stim_end_time+.004))&(TVC_table["Time_s"]>=(stim_end_time-.004)),:]
stimulus_end_table = stimulus_end_table.reset_index(drop=True)
if stim_amplitude <= stimulus_baseline: # negative current_step
maximum_current_derivative_index = stimulus_end_table['I_dot_five_kHz'].idxmax()
actual_transition_time = stimulus_end_table.loc[maximum_current_derivative_index, 'Time_s']
elif stim_amplitude > stimulus_baseline:# Positive current_step
minimum_current_derivative_index = stimulus_end_table['I_dot_five_kHz'].idxmin()
actual_transition_time = stimulus_end_table.loc[minimum_current_derivative_index, 'Time_s']
#Fit a sigmoid to current trace
linear_slope, linear_intercept = fir_an.linear_fit(np.array(stimulus_end_table.loc[:,'Time_s']),
np.array(stimulus_end_table.loc[:,'Input_current_pA']))
init_sigmoid_float = (np.abs(stimulus_baseline-stim_amplitude)/(4*linear_slope))
current_trace_table = TVC_table.loc[(TVC_table["Time_s"]<=(stim_end_time+.01))&(TVC_table["Time_s"]>=(stim_end_time-.01)),:]
Sigmoid_fit = Model(fir_an.sigmoid_function, prefix = "Sigmoid_")
Sigmoid_fit_params = Sigmoid_fit.make_params()
Sigmoid_fit_params.add("Sigmoid_x0",value=stim_end_time)
if stim_amplitude <= stimulus_baseline:# negative current_step
Sigmoid_fit_params.add("Sigmoid_sigma",value=init_sigmoid_float,min=1e-9)
elif stim_amplitude > stimulus_baseline:# Positive current_step
Sigmoid_fit_params.add("Sigmoid_sigma",value=init_sigmoid_float,max=-1e-9)
scale_fit = ConstantModel(prefix='scale_')
scale_fit_pars = scale_fit.make_params()
scale_fit_pars['scale_c'].set(value=np.abs(stimulus_baseline-stim_amplitude), min=1e-9)
offset_fit = ConstantModel(prefix='offset_')
offset_fit_pars = offset_fit.make_params()
offset_fit_pars['offset_c'].set(value=stimulus_baseline)
Sigmoid_amp_fit = scale_fit*Sigmoid_fit+offset_fit
Sigmoid_amp_fit_params = Sigmoid_fit_params+scale_fit_pars+offset_fit_pars
Sigmoid_amp_fit_result = Sigmoid_amp_fit.fit(current_trace_table.loc[:,'Input_current_pA'], Sigmoid_amp_fit_params, x=current_trace_table.loc[:,'Time_s'])
Sigmoid_amp_scale = Sigmoid_amp_fit_result.best_values["scale_c"]
Sigmoid_amp_x0 = Sigmoid_amp_fit_result.best_values["Sigmoid_x0"]
Sigmoid_amp_sigma = Sigmoid_amp_fit_result.best_values["Sigmoid_sigma"]
Sigmoid_amp_offset = Sigmoid_amp_fit_result.best_values["offset_c"]
sigmoid_fit_trace = fir_an.sigmoid_function(current_trace_table.loc[:,'Time_s'],Sigmoid_amp_x0,Sigmoid_amp_sigma)*Sigmoid_amp_scale+Sigmoid_amp_offset
sigmoid_fit_trace_table = pd.DataFrame({'Time_s':np.array(current_trace_table.loc[:,'Time_s']),
"Input_current_pA_Fit" : sigmoid_fit_trace})
min_time_fit = np.nanmin(sigmoid_fit_trace_table.loc[:,'Time_s'])
max_time_fit = np.nanmax(sigmoid_fit_trace_table.loc[:,'Time_s'])
pre_T_current = np.median(np.array(sigmoid_fit_trace_table.loc[(sigmoid_fit_trace_table["Time_s"]<=(min_time_fit+0.005))&(sigmoid_fit_trace_table["Time_s"]>=(min_time_fit)),"Input_current_pA_Fit"]))
post_T_current = np.median(np.array(sigmoid_fit_trace_table.loc[(sigmoid_fit_trace_table["Time_s"]<=(max_time_fit))&(sigmoid_fit_trace_table["Time_s"]>=(max_time_fit-0.005)),"Input_current_pA_Fit"]))
# pre_T_current = np.median(np.array(stimulus_end_table.loc[(stimulus_end_table["Time_s"]<=(actual_transition_time -.001))&(stimulus_end_table["Time_s"]>=(actual_transition_time-.002)),"Input_current_pA"]))
# post_T_current = np.median(stimulus_end_table.loc[(stimulus_end_table["Time_s"]<=(actual_transition_time +.002))&(stimulus_end_table["Time_s"]>=(actual_transition_time+.001)),"Input_current_pA"])
delta_I = post_T_current - pre_T_current
##Is there fluctuations?
#Compute std of voltage trace in the first half of the trace before the stimulus start
std_v_double_dot = np.nanstd(np.array(TVC_table.loc[(TVC_table['Time_s']>=0.)&(TVC_table['Time_s']<=(stim_start_time/2)),'V_double_dot_five_kHz']))
alpha_FT = 6*std_v_double_dot
Fast_ringing_table = TVC_table.loc[(TVC_table["Time_s"]<=(actual_transition_time+.005))&(TVC_table["Time_s"]>=actual_transition_time),:]
filtered_Fast_ringing_table = Fast_ringing_table[abs(Fast_ringing_table['V_double_dot_five_kHz']) > alpha_FT]
if not filtered_Fast_ringing_table.empty:
T_FT = np.nanmax(filtered_Fast_ringing_table.loc[:,'Time_s'])
T_ref_cell = T_FT
else:
T_FT = np.nan
T_ref_cell = actual_transition_time
# get T_Start_fit
Post_T_ref_table = TVC_table.loc[TVC_table['Time_s'] >= T_ref_cell,:]
Post_T_ref_table = Post_T_ref_table.reset_index(drop=True)
if stim_amplitude <= stimulus_baseline: # negative current_step and Positive curent transition (as we are at stim end)
filtered_Post_T_ref_table = Post_T_ref_table.loc[Post_T_ref_table['V_dot_one_kHz'] > 0,:]
if not filtered_Post_T_ref_table.empty:
first_positive_time = np.nanmin(filtered_Post_T_ref_table.loc[:,'Time_s'])
delta_t_ref_first_positive = first_positive_time - T_ref_cell
else:
delta_t_ref_first_positive = np.nan
elif stim_amplitude > stimulus_baseline:# Positive current_step and Negative curent transition (as we are at stim end)
filtered_Post_T_ref_table = Post_T_ref_table.loc[Post_T_ref_table['V_dot_one_kHz'] < 0,:]
if not filtered_Post_T_ref_table.empty:
first_positive_time = np.nanmin(filtered_Post_T_ref_table.loc[:,'Time_s'])
delta_t_ref_first_positive = first_positive_time - T_ref_cell
else:
delta_t_ref_first_positive = np.nan
T_start_fit = T_ref_cell + np.nanmax(np.array([2*delta_t_ref_first_positive, 0.0005]))
# Fit double exponential
best_single_A,best_single_tau, best_single_C,RMSE_single_expo = np.nan, np.nan, np.nan, np.nan
Double_Exponential_TVC_table = TVC_table.loc[(TVC_table['Time_s'] >= T_start_fit)&(TVC_table['Time_s'] <= T_start_fit+0.005),:]
best_first_A,best_first_tau,best_second_A, best_second_tau, best_C, RMSE_double_expo, fit_table = fit_double_exponential_BE (Double_Exponential_TVC_table,False)
Double_Exponential_TVC_table_extended = TVC_table.loc[(TVC_table['Time_s'] >= actual_transition_time ) & ( TVC_table['Time_s'] <= T_start_fit+0.005 ),:]
V_2exp_fit_extended = double_exponential_decay_function(Double_Exponential_TVC_table_extended.loc[:,'Time_s'],
best_first_A,best_first_tau,best_second_A, best_second_tau, best_C)
std_V_2exp_fit_extended = np.nanstd(V_2exp_fit_extended)
std_V = np.nanstd(Double_Exponential_TVC_table.loc[:,'Membrane_potential_mV'])
#Determine which exponential is the fast and which is the slow
if best_second_tau>=best_first_tau:
fast_tau = best_first_tau
fast_A = best_first_A
slow_tau = best_second_tau
slow_A = best_second_A
else:
fast_tau = best_second_tau
fast_A = best_second_A
slow_tau = best_first_tau
slow_A = best_first_A
if std_V_2exp_fit_extended/std_V < 2. and fast_A/slow_A > 0.1:
best_first_A,best_first_tau,best_second_A, best_second_tau, best_C, RMSE_double_expo, V_2exp_fit = fit_double_exponential_BE (Double_Exponential_TVC_table,False)
extended_time_trace = np.array(TVC_table.loc[(TVC_table['Time_s'] >= actual_transition_time)&(TVC_table['Time_s'] <= T_start_fit+0.005),'Time_s'])
extended_time_trace_shifted = extended_time_trace-np.nanmin(np.array(Double_Exponential_TVC_table.loc[:,"Time_s"]))
estimated_membrane_potential = double_exponential_decay_function(extended_time_trace_shifted ,
best_first_A,best_first_tau,best_second_A, best_second_tau, best_C)
V_fit_table = pd.DataFrame({'Time_s':np.array(TVC_table.loc[(TVC_table['Time_s'] >= actual_transition_time)&(TVC_table['Time_s'] <= T_start_fit+0.005),'Time_s']),
'Membrane_potential_mV' : np.array(estimated_membrane_potential)})
V_table_to_fit = V_2exp_fit.loc[V_2exp_fit['Data'] == 'Original_Data',:]
exponential_fit = 'Double_exponential'
shift_transition_time = actual_transition_time-np.nanmin(Double_Exponential_TVC_table.loc[:,'Time_s'])
V_fit_at_transition_time = double_exponential_decay_function(shift_transition_time , best_first_A,best_first_tau,best_second_A, best_second_tau, best_C)
else:
best_single_A,best_single_tau, best_single_C, RMSE_single_expo, V_1exp_fit = fit_single_exponential_BE(Double_Exponential_TVC_table,False)
extended_time_trace = np.array(TVC_table.loc[(TVC_table['Time_s'] >= actual_transition_time)&(TVC_table['Time_s'] <= T_start_fit+0.005),'Time_s'])
extended_time_trace_shifted = extended_time_trace-np.nanmin(np.array(Double_Exponential_TVC_table.loc[:,"Time_s"]))
estimated_membrane_potential = time_cst_model(extended_time_trace_shifted,
best_single_A, best_single_tau, best_single_C)
V_fit_table = pd.DataFrame({'Time_s':np.array(TVC_table.loc[(TVC_table['Time_s'] >= actual_transition_time)&(TVC_table['Time_s'] <= T_start_fit+0.005),'Time_s']),
'Membrane_potential_mV' : np.array(estimated_membrane_potential)})
# V_1exp_fit = time_cst_model(Double_Exponential_TVC_table.loc[:,'Time_s'],
# best_single_A, best_single_tau, best_single_C)
V_table_to_fit = V_1exp_fit.loc[V_1exp_fit['Data'] == 'Original_Data',:]
exponential_fit = 'Single_exponential'
shift_transition_time = actual_transition_time-np.nanmin(Double_Exponential_TVC_table.loc[:,'Time_s'])
V_fit_at_transition_time = time_cst_model(shift_transition_time, best_single_A, best_single_tau, best_single_C)
#V_fit_table = pd.DataFrame({'Time_s' : Double_Exponential_TVC_table.loc[:,'Time_s'],
# "Membrane_potential_mV" : V_fit})
#Determine V_pre and V_post
TVC_table_subset = TVC_table.loc[(TVC_table["Time_s"]>=(actual_transition_time-0.005)) & (TVC_table["Time_s"]<=(actual_transition_time)), :]
Zero_5_kHz_LP_filtered_voltage_trace_subset = np.array(ordifunc.filter_trace(np.array(TVC_table_subset.loc[:,'Membrane_potential_mV']),
np.array(TVC_table_subset.loc[:,'Time_s']),
filter=.5,
filter_order=4,
zero_phase = True,
do_plot=False
))
TVC_table_subset.loc[:,"Membrane_potential_0_5_LPF"] = Zero_5_kHz_LP_filtered_voltage_trace_subset
TVC_table = pd.merge(TVC_table, TVC_table_subset.loc[:,['Time_s','Membrane_potential_0_5_LPF']], on="Time_s", how='outer')
V_pre_transition_time = TVC_table_subset.loc[TVC_table_subset['Time_s']==actual_transition_time, "Membrane_potential_0_5_LPF"].values[0]
#return V_fit_table
V_post_transition_time = V_fit_at_transition_time
delta_V = V_post_transition_time - V_pre_transition_time
Bridge_Error = delta_V/delta_I
BE_accepted = True
# Check if Bridge Error is accepted
## Avoid Delayed Response
Filtered_TVC_V_dot_one_kHz = TVC_table.loc[(TVC_table['Time_s'] >= T_ref_cell) & (TVC_table['Time_s'] <= T_ref_cell+0.005),:]
max_abs_V_dot_index = Filtered_TVC_V_dot_one_kHz['V_dot_one_kHz'].abs().idxmax()
# Get the corresponding time value
time_at_max_abs_value = Filtered_TVC_V_dot_one_kHz.loc[max_abs_V_dot_index, 'Time_s']
BE_accepted, test_table = accept_or_reject_BE(TVC_table, time_at_max_abs_value, T_ref_cell, actual_transition_time, delta_t_ref_first_positive, exponential_fit, RMSE_double_expo, best_first_A, best_second_A, RMSE_single_expo, best_single_A)
if BE_accepted == False:
Bridge_Error = np.nan
#print(obs)
#print(test_table.iloc[:,:2])
if do_plot:
dict_plot = {'TVC_table':TVC_table,
"Transition_time" : actual_transition_time,
"min_time_fit":min_time_fit,
"max_time_fit":max_time_fit,
"T_FT" : T_FT,
"alpha_FT":alpha_FT,
"T_ref_cell":T_ref_cell,
"delta_t_ref_first_positive":delta_t_ref_first_positive,
"Membrane_potential_mV" : {"V_fit_table" : V_fit_table,
"V_table_to_fit" : V_table_to_fit,
"Voltage_Pre_transition" : V_pre_transition_time,
"Voltage_Post_transition" :V_post_transition_time},
"Input_current_pA" : {"pre_T_current":pre_T_current,
"post_T_current" : post_T_current,
"Sigmoid_fit" : sigmoid_fit_trace_table}}
return dict_plot
#print(stimulus_end_table.loc[(TVC_table["Time_s"]<=(actual_transition_time -.001))&(TVC_table["Time_s"]>=(actual_transition_time-.002)),"Input_current_pA"])
return Bridge_Error, test_table
except RuntimeError:
error= traceback.format_exc()
Bridge_Error = np.nan
test_table = pd.DataFrame()
return Bridge_Error, test_table
def accept_or_reject_BE(TVC_table, time_at_max_abs_value, T_ref_cell,Transition_time, delta_t_ref_first_positive, exponential_fit, RMSE_double_expo, best_first_A, best_second_A, RMSE_single_expo, best_single_A):
BE_accepted = True # Start with the assumption that the condition is accepted
obs = '--'
# Initialize a list to store test results
test_results = {
'Condition': [],
'Met': [],
'Details': []
}
# Condition 1: Check for delayed response
if time_at_max_abs_value > T_ref_cell + 0.002:
BE_accepted = False
obs = f"time_at_max_abs_value = {time_at_max_abs_value}, T_Ref + 0.002={T_ref_cell+0.002}"
test_results['Condition'].append('time_at_max_abs_value <=T_ref_cell+0.002')
test_results['Met'].append(False)
test_results['Details'].append(obs)
else:
obs = f"time_at_max_abs_value = {time_at_max_abs_value}, T_ref_cell + 0.002={T_ref_cell+0.002}"
test_results['Condition'].append('time_at_max_abs_value <= T_ref_cell+0.002')
test_results['Met'].append(True)
test_results['Details'].append(obs)
# Condition 2: Avoid long biphasic phase
if delta_t_ref_first_positive-Transition_time > 1:
BE_accepted = False
obs = f"delta_t_ref_first_positive - Transition_time = {delta_t_ref_first_positive} - {Transition_time} = {delta_t_ref_first_positive - Transition_time}"
test_results['Condition'].append('Long biphasic phase, delta_t_ref_first_positive - Transition_time ≤ 1 ')
test_results['Met'].append(False)
test_results['Details'].append(obs)
else:
obs = f"delta_t_ref_first_positive - Transition_time = {delta_t_ref_first_positive} - {Transition_time} = {delta_t_ref_first_positive - Transition_time}"
test_results['Condition'].append('Long biphasic phase,delta_t_ref_first_positive - Transition_time ≤ 1 ')
test_results['Met'].append(True)
test_results['Details'].append(obs)
# Condition 3: Reliable estimate of V_pre_transition_time
sub_table = TVC_table.loc[(TVC_table['Time_s'] >= Transition_time-0.005) & (TVC_table['Time_s'] <= Transition_time),:]
sub_membrane_trace = np.array(sub_table.loc[:,'Membrane_potential_mV'])
std_V = np.nanstd(sub_membrane_trace)
if std_V > 2.0:
BE_accepted = False
obs = f"Reliability of V_pre_transition_time estimate, std_V = {std_V}"
test_results['Condition'].append('std_V ≤ 2')
test_results['Met'].append(False)
test_results['Details'].append(obs)
else:
obs = f"Reliability of V_pre_transition_time estimate, std_V = {std_V}"
test_results['Condition'].append('std_V ≤ 2')
test_results['Met'].append(True)
test_results['Details'].append(obs)
# Condition 4: Error limit for 2 exponential fit
if exponential_fit == 'Double_exponential':
error_ratio = RMSE_double_expo / (best_first_A + best_second_A)
if error_ratio > 0.12:
BE_accepted = False
obs = f"Error for 2 exponential fit, RMSE_double_expo / (best_first_A + best_second_A) = {error_ratio}"
test_results['Condition'].append('RMSE/(best_first_A + best_second_A) ≤ 0.12')
test_results['Met'].append(False)
test_results['Details'].append(obs)
else:
obs = f"Error for 2 exponential fit, RMSE_double_expo / (best_first_A + best_second_A) = {error_ratio}"
test_results['Condition'].append('RMSE/(best_first_A + best_second_A) ≤ 0.12')
test_results['Met'].append(True)
test_results['Details'].append(obs)
# Condition 5: Error limit for 1 exponential fit
elif exponential_fit == 'Single_exponential':
error_ratio = RMSE_single_expo / best_single_A
if error_ratio > 0.12:
BE_accepted = False
obs = f"Error for 1 exponential fit, RMSE_single_expo / best_single_A = {error_ratio}"
test_results['Condition'].append('RMSE_single_expo / best_single_A ≤ 0.12')
test_results['Met'].append(False)
test_results['Details'].append(obs)
else:
obs = f"Error for 1 exponential fit, RMSE_single_expo / best_single_A = {error_ratio}"
test_results['Condition'].append('RMSE_single_expo / best_single_A ≤ 0.12')
test_results['Met'].append(True)
test_results['Details'].append(obs)
voltage_spike_table = sp_an.identify_spike(np.array(TVC_table.Membrane_potential_mV),
np.array(TVC_table.Time_s),
np.array(TVC_table.Input_current_pA),
T_ref_cell,
np.nanmax(np.array(TVC_table.Time_s)),do_plot=False)
if len(voltage_spike_table['Peak']) != 0:
BE_accepted = False
obs = f"Presence of {len(voltage_spike_table['Peak'])} rebound spikes"
test_results['Condition'].append('No rebound spike must be present')
test_results['Met'].append(False)
test_results['Details'].append(obs)
else:
obs = f"Presence of {len(voltage_spike_table['Peak'])} rebound spikes"
test_results['Condition'].append('No rebound spike must be present')
test_results['Met'].append(True)
test_results['Details'].append(obs)
# Create the test_table DataFrame
test_table = pd.DataFrame(test_results)
return BE_accepted, test_table
def plot_BE(dict_plot):
TVC_table = dict_plot['TVC_table']
#min_time_fit
min_time_fit = dict_plot['min_time_fit']
max_time_fit = dict_plot['max_time_fit']
# Transition_time
actual_transition_time = dict_plot["Transition_time"]
alpha_FT = dict_plot['alpha_FT']
T_FT = dict_plot['T_FT']
delta_t_ref_first_positive = dict_plot["delta_t_ref_first_positive"]
T_ref_cell = dict_plot['T_ref_cell']
# Membrane_potential_mV
V_fit_table = dict_plot["Membrane_potential_mV"]["V_fit_table"]
V_table_to_fit = dict_plot['Membrane_potential_mV']['V_table_to_fit']
V_pre_transition_time = dict_plot["Membrane_potential_mV"]["Voltage_Pre_transition"]
V_post_transition_time = dict_plot["Membrane_potential_mV"]["Voltage_Post_transition"]
# Input_current_pA
pre_T_current = dict_plot["Input_current_pA"]["pre_T_current"]
post_T_current = dict_plot["Input_current_pA"]["post_T_current"]
sigmoid_fit_trace_table = dict_plot["Input_current_pA"]["Sigmoid_fit"]
# Create subplots
fig = make_subplots(rows=5, cols=1, shared_xaxes=True, subplot_titles=("Membrane Potential plot", "Input Current plot", "Membrane potential first derivative 1kHz LPF","Membrane potential second derivative 5kHz LPF","Input current derivative 5kHz LPF"), vertical_spacing=0.03)