/
druckmann2013.py
1481 lines (1018 loc) · 44.2 KB
/
druckmann2013.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
"""
Tests of features described in Druckmann et. al. 2013 (https://academic.oup.com/cercor/article/23/12/2994/470476)
AP analysis details (from suplementary info): https://github.com/scidash/neuronunit/files/2295064/bhs290supp.pdf
Numbers in class names refer to the numbers in the publication table
"""
from elephant.spike_train_generation import threshold_detection
from neo import AnalogSignal
from numba import jit
from .base import np, pq, ncap, VmTest, scores
# How this file is different to the original.
# Some big functions broken into smaller ones, for greater modularity
# use of numba jit where possible.
# Different inheritance designed to work with optimizer.
per_ms = pq.UnitQuantity('per_ms',1.0/pq.ms,symbol='per_ms')
none_score = {
'mean': None,
'std': None,
'n': 0
}
debug = False #True
@jit
def get_diff_spikes(vm):
differentiated = np.diff(vm)
spikes = len([np.any(differentiated) > 0.000143667327364])
return spikes
@jit
def get_diff(vm,axis=None):
if axis is not None:
differentiated = np.diff(vm,axis=axis)
else:
differentiated = np.diff(vm)
return differentiated
class Druckmann2013AP:
"""
This is a helper class that computes/finds aspects of APs as defined in Druckmann 2013
"""
def __init__(self, waveform, begin_time):
self.waveform = waveform
self.begin_time = begin_time
self.begin_time.units = pq.ms
def get_beginning(self):
"""
The beginning of a spike was then determined by a crossing of a threshold on the derivative of the voltage (12mV/msec).
:return: the voltage and time of the AP beginning
"""
begining_time = self.begin_time
beginning_voltage = self.waveform[0]
return beginning_voltage, begining_time
def get_amplitude(self):
"""
The amplitude of a spike is given by the difference between the voltage at the beginning and peak of the spike.
:return: the amplitude value
"""
v_begin, _ = self.get_beginning()
v_peak, _ = self.get_peak()
return (v_peak - v_begin)
def get_halfwidth(self):
"""
Amount of time in between the first crossing (in the upwards direction) of the
half-height voltage value and the second crossing (in the downwards direction) of
this value, for the first AP. Half-height voltage is the voltage at the beginning
of the AP plus half the AP amplitude.
:return:
"""
v_begin, _ = self.get_beginning()
amp = self.get_amplitude()
half_v = v_begin + amp / 2.0
above_half_v = np.where(self.waveform.magnitude > half_v)[0]
half_start = self.waveform.times[above_half_v[0]]
half_end = self.waveform.times[above_half_v[-1]]
half_width = half_end - half_start
half_width.units = pq.ms
return half_width
def get_peak(self):
"""
The peak point of the spike is the maximum in between the beginning and the end.
:return: the voltage and time of the peak
"""
if not hasattr(self, 'peak'):
value = self.waveform.max()
time = self.begin_time + self.waveform.times[np.where(self.waveform.magnitude == value)[0]]
time.units = pq.ms
self.peak = { 'value': value, 'time': time }
return self.peak['value'], self.peak['time']
def get_trough(self):
peak_v, peak_t = self.get_peak()
post_peak_waveform = self.waveform.magnitude[np.where(self.waveform.times > (peak_t - self.begin_time))]
post_peak_waveform = AnalogSignal(post_peak_waveform, units=self.waveform.units, sampling_period=self.waveform.sampling_period)
value = post_peak_waveform.min()
time = peak_t + post_peak_waveform.times[np.where(post_peak_waveform.magnitude == value)[0]]
time = time[0]
time.units = pq.ms
return value, time
def isolate_code_block(threshold_crosses,start_time,dvdt_threshold_crosses,dvdt_zero_crosses,vm):
'''
The introduction of this function is was not syntactically necissated. The reason for this functions existence
is to support code modularity.
'''
threshold_crosses = threshold_crosses[np.where(threshold_crosses > start_time)]
dvdt_threshold_crosses = dvdt_threshold_crosses[np.where(dvdt_threshold_crosses > start_time)]
dvdt_zero_crosses = dvdt_zero_crosses[np.where(dvdt_zero_crosses > start_time)]
# Normally, there should be at least as many dvdt threshold crosses as there are v threshold crosses
if len(dvdt_threshold_crosses) < len(threshold_crosses):
dvdt_threshold_crosses = threshold_crosses # for slowly rising APs (e.g. muscle) use the vm threshold as the beginning
ap_beginnings = []
prev_beginning = start_time
prev_threshold = start_time
vm_chopped = 0
for ti, curr_thresh in enumerate(threshold_crosses):
prev_dvdt_zero = dvdt_zero_crosses[np.where(dvdt_zero_crosses < curr_thresh)]
if len(prev_dvdt_zero) == 0:
prev_dvdt_zero = start_time
else:
prev_dvdt_zero = prev_dvdt_zero[-1]
earliest_dvdt_thresh_since_prev_ap = dvdt_threshold_crosses[
np.where((dvdt_threshold_crosses > prev_beginning) & (dvdt_threshold_crosses > prev_threshold) & (dvdt_threshold_crosses > prev_dvdt_zero))
]
if len(earliest_dvdt_thresh_since_prev_ap) != 0:
earliest_dvdt_thresh_since_prev_ap = earliest_dvdt_thresh_since_prev_ap[0]
else:
if ti == 0:
earliest_dvdt_thresh_since_prev_ap = prev_beginning
else:
raise Exception("Did not find a dvdt threshold crossing since previous AP")
ap_beginnings.append(earliest_dvdt_thresh_since_prev_ap)
prev_beginning = earliest_dvdt_thresh_since_prev_ap
prev_threshold = curr_thresh
# The number of ap beginnings should match the number aps detected
assert len(np.unique(ap_beginnings)) == len(threshold_crosses)
vm_mag = vm.magnitude
vm_times = vm.times
vm_chopped = np.split(vm_mag, np.isin(vm_times, ap_beginnings).nonzero()[0])
# The waveform should be cut into APs+1 pieces (1st waveform is steady state)
assert len(vm_chopped) == len(threshold_crosses)+1
return vm_chopped, threshold_crosses, ap_beginnings, vm_mag, vm_times
class Druckmann2013Test(VmTest):
"""
All tests inheriting from this class assume that the subject model:
1. Is at steady state at time 0 (i.e. resume from SS)
2. Starting at t=0, will have a 2s step current injected into soma, at least once
"""
required_capabilities = (ncap.ProducesActionPotentials,)
score_type = scores.ZScore
def __init__(self, current_amplitude, **params):
super(Druckmann2013Test, self).__init__(**params)
self.params = {
'injected_square_current': {
'delay': 1000 * pq.ms,
'duration': 2000 * pq.ms,
'amplitude': current_amplitude
},
'threshold': -20 * pq.mV,
'beginning_threshold': 12.0 * pq.mV/pq.ms,
'ap_window': 10 * pq.ms,
'repetitions': 1,
}
# This will be an array that stores DruckmannAPs
self.APs = None
def generate_prediction(self, model):
results = []
reps = self.params['repetitions']
for rep in range(reps):
pred = self.generate_repetition_prediction(model)
results.append(pred)
if reps > 1:
return self.aggregate_repetitions(results)
else:
return results[0]
def generate_repetition_prediction(self, model):
raise NotImplementedError()
def aggregate_repetitions(self, results):
values = [rep['mean'] for rep in results if rep['mean'] is not None]
units = values[0].units if len(values) > 0 else self.units
if len(values) > 0:
return {
'mean': np.mean(values) * units,
'std': np.std(values) * units,
'n': len(results)
}
return none_score
def current_length(self):
return self.params['injected_square_current']['duration']
def get_APs(self, model):
"""
Spikes were detected by a crossing of a voltage threshold (-20 mV).
:param model: model which provides the waveform to analyse
:return: a list of Druckman2013APs
"""
vm = model.get_membrane_potential()
vm_times = vm.times
start_time = self.params['injected_square_current']['delay'].rescale('sec')
end_time = start_time + self.params['injected_square_current']['duration'].rescale('sec')
vm = AnalogSignal(vm.magnitude[np.where(vm_times <= end_time)], sampling_period=vm.sampling_period, units=vm.units)
try:
dvdt = np.array(np.append([0], get_diff(vm, axis=0))) * pq.mV / vm.sampling_period
except:
dvdt = np.array(np.append([0], get_diff(vm))) * pq.mV / vm.sampling_period
dvdt = AnalogSignal(dvdt, sampling_period=vm.sampling_period)
threshold_crosses = threshold_detection(vm,threshold=self.params['threshold'])
dvdt_threshold_crosses = threshold_detection(dvdt,threshold=self.params['beginning_threshold'])
dvdt_zero_crosses = threshold_detection(dvdt, threshold=0 * pq.mV/pq.ms)
vm_chopped, threshold_crosses, ap_beginnings, vm_mag, vm_times = isolate_code_block(
threshold_crosses, \
start_time,dvdt_threshold_crosses,dvdt_zero_crosses,vm \
)
ap_waveforms = []
for i, b in enumerate(ap_beginnings):
if i != len(ap_beginnings)-1:
waveform = vm_chopped[i+1]
else:
# Keep up to 100ms of the last AP
waveform = vm_mag[np.where((vm_times >= b) & (vm_times < b + 100.0*pq.ms))]
waveform = AnalogSignal(waveform, units=vm.units, sampling_rate=vm.sampling_rate)
ap_waveforms.append(waveform)
# Pass in the AP waveforms and the times when they occured
self.APs = []
for i, b in enumerate(ap_beginnings):
self.APs.append(Druckmann2013AP(ap_waveforms[i], ap_beginnings[i]))
return self.APs
def get_ISIs(self, model=None):
aps = self.get_APs(model)
ap_times = np.array([ap.get_beginning()[1] for ap in aps])
isis = get_diff(ap_times)# np.diff(ap_times)
return isis
class AP12AmplitudeDropTest(Druckmann2013Test):
"""
1. Drop in AP amplitude (amp.) from first to second spike (mV)
Difference in the voltage value between the amplitude of the first and second AP.
Negative values indicate 2nd AP amplitude > 1st
"""
name = "Drop in AP amplitude from 1st to 2nd AP"
description = "Difference in the voltage value between the amplitude of the first and second AP"
units = pq.mV
def generate_prediction(self, model):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) >= 2:
if debug:
from matplotlib import pyplot as plt
plt.plot(aps[0].waveform)
plt.plot(aps[1].waveform)
plt.show()
return {
'mean': aps[0].get_amplitude() - aps[1].get_amplitude(),
'std': 0,
'n': 1
}
else:
return none_score
class AP1SSAmplitudeChangeTest(Druckmann2013Test):
"""
2. AP amplitude change from first spike to steady-state (mV)
Steady state AP amplitude is calculated as the mean amplitude of the set of APs
that occurred during the latter third of the current step.
"""
name = "AP amplitude change from 1st AP to steady-state"
description = """Steady state AP amplitude is calculated as the mean amplitude of the set of APs
that occurred during the latter third of the current step."""
units = pq.mV
def generate_prediction(self, model):
current_start = self.params['injected_square_current']['delay']
start_latter_3rd = current_start + self.current_length() * 2.0 / 3.0
end_latter_3rd = current_start + self.current_length()
aps = self.get_APs(model)
amps = np.array([ap.get_amplitude() for ap in aps]) * pq.mV
ap_times = np.array([ap.get_beginning()[1] for ap in aps]) * pq.ms
ss_aps = np.where(
(ap_times >= start_latter_3rd) &
(ap_times <= end_latter_3rd))
ss_amps = amps[ss_aps]
if len(aps) > 0 and len(ss_amps) > 0:
if debug:
from matplotlib import pyplot as plt
plt.plot(aps[0].waveform)
for i in ss_aps[0]:
plt.plot(aps[i].waveform)
plt.show()
return {
'mean': amps[0] - ss_amps.mean(),
'std': ss_amps.std(),
'n': len(ss_amps)
}
return none_score
class AP1AmplitudeTest(Druckmann2013Test):
"""
3. AP 1 amplitude (mV)
Amplitude of the first AP.
"""
name = "First AP amplitude"
description = "Amplitude of the first AP"
units = pq.mV
def generate_prediction(self, model, ap_index=0):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) > ap_index:
amp = aps[ap_index].get_amplitude()
assert 0 * self.units < amp < 200 * self.units
return {
'mean': amp,
'std': 0,
'n': 1
}
else:
return none_score
class AP1WidthHalfHeightTest(Druckmann2013Test):
"""
4. AP 1 width at half height (ms)
"""
name = "First AP width at its half height"
description = """Amount of time in between the first crossing (in the upwards direction) of the
half-height voltage value and the second crossing (in the downwards direction) of
this value, for the first AP. Half-height voltage is the voltage at the beginning of
the AP plus half the AP amplitude."""
units = pq.ms
def generate_prediction(self, model, ap_index=0):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) > ap_index:
hw = aps[ap_index].get_halfwidth()
assert 0 * self.units < hw < 100 * self.units
return {
'mean': hw,
'std': 0,
'n': 1
}
return none_score
class AP1WidthPeakToTroughTest(Druckmann2013Test):
"""
5. AP 1 peak to trough time (ms)
Amount of time between the peak of the first AP and the trough, i.e., the
minimum of the AHP.
"""
name = "AP 1 peak to trough time"
description = """Amount of time between the peak of the first AP and the trough, i.e., the minimum of the AHP"""
units = pq.ms
def generate_prediction(self, model, ap_index=0):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) > ap_index:
ap = aps[ap_index]
_, peak_t = ap.get_peak()
_, trough_t = ap.get_trough()
width = trough_t - peak_t
if debug:
from matplotlib import pyplot as plt
plt.plot(aps[0].waveform)
plt.xlim(0, 1000)
plt.show()
assert 0 * self.units <= width < 100 * self.units
return {
'mean': width,
'std': 0,
'n': 1
}
return none_score
class AP1RateOfChangePeakToTroughTest(Druckmann2013Test):
"""
6. AP 1 peak to trough rate of change (mV/ms)
Difference in voltage value between peak and trough divided by the amount of time in
between the peak and trough.
"""
name = "AP 1 peak to trough rate of change"
description = """Difference in voltage value between peak and trough over the amount of time in between the peak and trough."""
units = pq.mV/pq.ms
def generate_prediction(self, model, ap_index=0):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) > ap_index:
ap = aps[ap_index]
peak_v, peak_t = ap.get_peak()
trough_v, trough_t = ap.get_trough()
width = trough_t - peak_t
if width == 0 * pq.ms:
width = ap.waveform.sampling_period
change = (trough_v - peak_v) / width
assert change < 0 * self.units
return {
'mean': change,
'std': 0,
'n': 1
}
return none_score
class AP1AHPDepthTest(Druckmann2013Test):
"""
7. AP 1 Fast AHP depth (mV)
Difference between the minimum of voltage at the trough and the voltage value at
the beginning of the AP.
"""
name = "AP 1 Fast AHP depth"
description = """Difference between the minimum of voltage at the trough and the voltage value at
the beginning of the AP."""
units = pq.mV
def generate_prediction(self, model, ap_index=0):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) > ap_index:
ap = aps[ap_index]
begin_v, _ = ap.get_beginning()
trough_v, _ = ap.get_trough()
change = begin_v - trough_v
if debug:
from matplotlib import pyplot as plt
plt.plot(aps[0].waveform)
plt.xlim(0, 1000)
plt.show()
return {
'mean': change,
'std': 0,
'n': 1
}
else:
return none_score
class AP2AmplitudeTest(AP1AmplitudeTest):
"""
8. AP 2 amplitude (mV)
Same as :any:`AP1AmplitudeTest` but for second AP
"""
name = "AP 2 amplitude"
description = """Same as :any:`AP1AmplitudeTest` but for second AP"""
def generate_prediction(self, model):
return super(AP2AmplitudeTest, self).generate_prediction(model, ap_index=1)
class AP2WidthHalfHeightTest(AP1WidthHalfHeightTest):
"""
9. AP 2 width at half height (ms)
Same as :any:`AP1WidthHalfHeightTest` but for second AP
"""
name = "AP 2 width at half height"
description = """Same as :any:`AP1WidthHalfHeightTest` but for second AP"""
def generate_prediction(self, model):
return super(AP2WidthHalfHeightTest, self).generate_prediction(model, ap_index=1)
class AP2WidthPeakToTroughTest(AP1WidthPeakToTroughTest):
"""
10. AP 2 peak to trough time (ms)
Same as :any:`AP1WidthPeakToTroughTest` but for second AP
"""
name = "AP 2 peak to trough time"
description = """Same as :any:`AP1WidthPeakToTroughTest` but for second AP"""
def generate_prediction(self, model):
return super(AP2WidthPeakToTroughTest, self).generate_prediction(model, ap_index=1)
class AP2RateOfChangePeakToTroughTest(AP1RateOfChangePeakToTroughTest):
"""
11. AP 2 peak to trough rate of change (mV/ms)
Same as :any:`AP1RateOfChangePeakToTroughTest` but for second AP
"""
name = "AP 2 peak to trough rate of change"
description = """Same as :any:`AP1RateOfChangePeakToTroughTest` but for second AP"""
def generate_prediction(self, model):
return super(AP2RateOfChangePeakToTroughTest, self).generate_prediction(model, ap_index=1)
class AP2AHPDepthTest(AP1AHPDepthTest):
"""
12. AP 2 Fast AHP depth (mV)
Same as :any:`AP1AHPDepthTest` but for second AP
"""
name = "AP 2 Fast AHP depth"
description = """Same as :any:`AP1AHPDepthTest` but for second AP"""
def generate_prediction(self, model):
return super(AP2AHPDepthTest, self).generate_prediction(model, ap_index=1)
class AP12AmplitudeChangePercentTest(Druckmann2013Test):
"""
13. Percent change in AP amplitude, first to second spike (%)
Difference in AP amplitude between first and second AP divided by the first AP
amplitude.
"""
name = "Percent change in AP amplitude, first to second spike "
description = """Difference in AP amplitude between first and second AP divided by the first AP
amplitude."""
units = pq.dimensionless
def generate_prediction(self, model):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) >= 2:
amp = self.params['injected_square_current']['amplitude']
amp1 = AP1AmplitudeTest(amp).generate_prediction(model)["mean"]
amp2 = AP2AmplitudeTest(amp).generate_prediction(model)["mean"]
change = (amp2-amp1)/amp1 * 100.0;
return {
'mean': change,
'std': 0,
'n': 1
}
else:
return none_score
class AP12HalfWidthChangePercentTest(Druckmann2013Test):
"""
14. Percent change in AP width at half height, first to second spike (%)
Difference in AP width at half-height between first and second AP divided by the
first AP width at half-height.
"""
name = "Percent change in AP width at half height, first to second spike"
description = """Difference in AP width at half-height between first and second AP divided by the
first AP width at half-height."""
units = pq.dimensionless
def generate_prediction(self, model):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) >= 2:
amp = self.params['injected_square_current']['amplitude']
width1 = AP1WidthHalfHeightTest(amp).generate_prediction(model)["mean"]
width2 = AP2WidthHalfHeightTest(amp).generate_prediction(model)["mean"]
change = (width2-width1)/width1 * 100.0;
return {
'mean': change,
'std': 0,
'n': 1
}
else:
return none_score
class AP12RateOfChangePeakToTroughPercentChangeTest(Druckmann2013Test):
"""
15. Percent change in AP peak to trough rate of change, first to second spike (%)
Difference in peak to trough rate of change between first and second AP divided
by the first AP peak to trough rate of change.
"""
name = "Percent change in AP peak to trough rate of change, first to second spike"
description = """Difference in peak to trough rate of change between first and second AP divided
by the first AP peak to trough rate of change."""
units = pq.dimensionless
def generate_prediction(self, model):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) >= 2:
amp = self.params['injected_square_current']['amplitude']
roc1 = AP1RateOfChangePeakToTroughTest(amp).generate_prediction(model)["mean"]
roc2 = AP2RateOfChangePeakToTroughTest(amp).generate_prediction(model)["mean"]
change = (roc2-roc1)/roc1 * 100.0;
return {
'mean': change,
'std': 0,
'n': 1
}
else:
return none_score
class AP12AHPDepthPercentChangeTest(Druckmann2013Test):
"""
16 Percent change in AP fast AHP depth, first to second spike (%)
Difference in depth of fast AHP between first and second AP divided by the first
AP depth of fast AHP.
"""
name = "Percent change in AP fast AHP depth, first to second spike"
description = """Difference in depth of fast AHP between first and second AP divided by the first
AP depth of fast AHP."""
units = pq.dimensionless
def generate_prediction(self, model):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) >= 2:
amp = self.params['injected_square_current']['amplitude']
ap1 = AP1AHPDepthTest(amp).generate_prediction(model)["mean"]
ap2 = AP2AHPDepthTest(amp).generate_prediction(model)["mean"]
change = (ap2-ap1)/ap1 * 100.0;
return {
'mean': change,
'std': 0,
'n': 1
}
else:
return none_score
class InputResistanceTest(Druckmann2013Test):
"""
17 Input resistance for steady-state current (MOhm)
Input resistance calculated by injecting weak subthreshold hyperpolarizing and
depolarizing step currents. Input resistance was taken as linear fit of current to
voltage difference.
"""
name = "Input resistance for steady-state current"
description = """Input resistance calculated by injecting weak subthreshold hyperpolarizing and
depolarizing step currents. Input resistance was taken as linear fit of current to
voltage difference"""
units = pq.Quantity(1,'MOhm')
def __init__(self, injection_currents=np.array([])*pq.nA, **params):
super(InputResistanceTest, self).__init__(current_amplitude=None, **params)
if not injection_currents or len(injection_currents) < 1:
raise Exception("Test requires at least one current injection")
for i in injection_currents:
if i.units != pq.nA:
i.units = pq.nA
self.injection_currents = injection_currents
#@jit
def generate_prediction(self, model):
voltages = []
# Loop through the injection currents
for i in self.injection_currents:
# Set the current amplitude
self.params['injected_square_current']['amplitude'] = i
# Inject current
model.inject_square_current(self.params['injected_square_current'])
# Get the voltage waveform
vm = model.get_membrane_potential()
# The voltage at final 1ms of current step is assumed to be steady state
ss_voltage = np.median(vm.magnitude[np.where((vm.times >= 1999*pq.ms) & (vm.times <= 2000*pq.ms))]) * pq.mV
voltages.append(ss_voltage)
if debug:
from matplotlib import pyplot as plt
plt.plot(vm)
if debug:
plt.show()
# Rescale units
amps = [i.rescale('A') for i in self.injection_currents]
volts = [v.rescale('V') for v in voltages]
# If there is only one injection current available, use the resting voltage as 0 Amp current response
if len(self.injection_currents) < 2:
amps.append(0 * pq.A)
resting_voltage = np.median(vm.magnitude[np.where((vm.times >= 999*pq.ms) & (vm.times <= 1000*pq.ms))]) * pq.mV
resting_voltage.units = pq.V
volts.append(resting_voltage)
# v = ir -> r is slope of v(i) curve
slope, _ = np.polyfit(amps, volts, 1)
slope *= pq.Ohm
slope.units = pq.Quantity(1,'MOhm')
if debug:
from matplotlib import pyplot as plt
plt.plot(amps, volts)
plt.show()
assert slope > -0.001 * self.units
return {
'mean': slope,
'std': 0,
'n': 1
}
class AP1DelayMeanTest(Druckmann2013Test):
"""
18 Average delay to AP 1 (ms)
Mean of the delay to beginning of first AP over experimental repetitions of step
currents.
"""
name = "First AP delay mean"
description = "Mean delay to the first AP"
units = pq.ms
def __init__(self, current_amplitude, repetitions=7, **params):
super(AP1DelayMeanTest, self).__init__(current_amplitude, **params)
self.params['repetitions'] = repetitions
def generate_repetition_prediction(self, model, ap_index=0):
model.inject_square_current(self.params['injected_square_current'])
aps = self.get_APs(model)
if len(aps) > ap_index:
delay = self.params['injected_square_current']['delay']
if debug:
from matplotlib import pyplot as plt
vm = model.get_membrane_potential()
plt.plot(vm.times.magnitude, vm.magnitude)
plt.xlim(1, aps[ap_index].get_beginning()[1].rescale('sec').magnitude + 0.1)
plt.show()
ap_delay = aps[ap_index].get_beginning()[1] - delay
assert ap_delay > -1 * self.units
return {
'mean': ap_delay,
'std': 0,
'n': 1
}
return none_score
class AP1DelaySDTest(AP1DelayMeanTest):
"""
19 SD of delay to AP 1 (ms)
Standard deviation of the delay to beginning of first AP over experimental
repetitions of step currents.
"""
name = "First AP delay standard deviation"
description = "Standard deviation of delay to the first AP"
units = pq.ms
def aggregate_repetitions(self, results):
aggregate = super(AP1DelaySDTest, self).aggregate_repetitions(results)
if aggregate['mean'] is not None:
aggregate['mean'] = aggregate['std']
aggregate['std'] = 0 * self.units
assert aggregate['mean'] >= 0 * self.units
return aggregate
return none_score
class AP2DelayMeanTest(AP1DelayMeanTest):
"""
20 Average delay to AP 2 (ms)
Same as :any:`AP1DelayMeanTest` but for 2nd AP
"""
name = "Second AP delay mean"
description = "Mean of delay to the second AP"
def generate_repetition_prediction(self, model, ap_index=0):
return super(AP2DelayMeanTest, self).generate_repetition_prediction(model, ap_index=1)
class AP2DelaySDTest(AP1DelaySDTest):
"""
21 SD of delay to AP 2 (ms)
Same as :any:`AP1DelaySDTest` but for 2nd AP
Only stochastic models will have a non-zero value for this test
"""
name = "Second AP delay standard deviation"
description = "Standard deviation of delay to the second AP"
def generate_repetition_prediction(self, model, ap_index=0):
return super(AP2DelaySDTest, self).generate_repetition_prediction(model, ap_index=1)
class Burst1ISIMeanTest(Druckmann2013Test):
"""
22 Average initial burst interval (ms)
Initial burst interval is defined as the average of the first two ISIs, i.e., the average
of the time differences between the first and second AP and the second and third
AP. This feature is the average the initial burst interval across experimental
repetitions.
"""
name = "Initial burst interval mean"
description = "Mean of the initial burst interval"
units = pq.ms