-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptimize_dynamic_model.py
More file actions
1861 lines (1554 loc) · 91.1 KB
/
optimize_dynamic_model.py
File metadata and controls
1861 lines (1554 loc) · 91.1 KB
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
import click
import datetime
import h5py
import sys
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity
from collections.abc import Iterable
from copy import deepcopy
from scipy.integrate import solve_ivp
from nested.utils import read_from_yaml, Context, param_array_to_dict
from distutils.util import strtobool
import os, time
import warnings
warnings.filterwarnings("ignore")
context = Context()
def recursive_append_binary_input_patterns(n, index=None, input_pattern_list=None):
"""
Recursively copy and extend all patterns in the current pattern list to include all binary combinations of length n.
:param n: int
:param index: int
:param input_pattern_list: list of lists of int
:return: list of lists
"""
if input_pattern_list is None:
input_pattern_list = []
index = 0
# If the current list of patterns is empty, generate the first two patterns with length 1
input_pattern_list.append([0])
input_pattern_list.append([1])
else:
# Otherwise, duplicate all previous input patterns of length column - 1, and append either 0 or 1
prev_num_patterns = len(input_pattern_list)
for i in range(prev_num_patterns):
pattern0 = input_pattern_list[i]
pattern1 = list(pattern0)
# This modifies pattern0, which is already contained in the input_pattern_list
pattern0.append(0)
pattern1.append(1)
# This modifies pattern1, which needs to be appended to the input_pattern_list
input_pattern_list.append(pattern1)
if index >= n - 1:
return input_pattern_list
else:
return recursive_append_binary_input_patterns(n, index + 1, input_pattern_list)
def get_binary_input_patterns(n, sort=True, plot=False):
"""
Return a 2D numpy array with 2 ** n rows and n columns containing all possible patterns (rows) comprised of n units
(columns) that can either be on (0) or off (1).
:param n: int; number of units
:param sort: bool; whether to sort input patterns by the summed activity of the inputs
:param plot: bool; whether to plot
:return: 2d array
"""
input_pattern_list = recursive_append_binary_input_patterns(n)
input_pattern_array = np.array(input_pattern_list)
if sort:
summed_input_activities = np.sum(input_pattern_array, axis=1)
sorted_indexes = np.argsort(summed_input_activities)
input_pattern_array = input_pattern_array[sorted_indexes]
summed_input_activities = summed_input_activities[sorted_indexes]
if plot:
fig = plt.figure(figsize=(7, 5))
ax1 = plt.subplot2grid((1, 6), (0, 0), colspan=5, rowspan=1)
ax1.imshow(input_pattern_array, cmap='binary', aspect='auto')
ax1.set_title('Input unit activity')
ax1.set_xlabel('Input unit ID')
ax1.set_ylabel('Input pattern ID')
ax2 = plt.subplot2grid((1, 6), (0, 5), colspan=1, rowspan=1)
ax2.imshow(np.atleast_2d(summed_input_activities).T, cmap='binary', aspect='auto')
ax2.yaxis.set_label_position("right")
ax2.set_ylabel('Summed unit activity', rotation=-90., labelpad=30)
ax2.set_xticks([])
ax2.set_yticks([])
fig.tight_layout(w_pad=4.)
fig.show()
return input_pattern_array
def act_funct_args(population, activation_function_dict):
"""
Gets custom parameters for the given activation function if they are provided
:param population: string
:param activation_function_dict: dictionary
:return: dictionary
"""
if 'Arguments' in activation_function_dict[population]:
this_kwargs = activation_function_dict[population]['Arguments']
else:
this_kwargs = {}
return this_kwargs
def identity_activation(x):
return x
def piecewise_linear_activation(weighted_input, peak_output=3., peak_input=7., threshold=0.):
"""
Output is zero below a threshold, then increases linearly for inputs up to the specified maximum values for inputs
and output.
:param weighted_input: array of float
:param peak_output: float
:param peak_input: float
:param threshold: float
:return: array of float
"""
slope = peak_output / (peak_input - threshold)
input_above_threshold = np.maximum(0., weighted_input-threshold)
output = slope * np.minimum(input_above_threshold, peak_input-threshold)
return output
def get_callable_from_str(func_name):
"""
Look for a callable function with the specified name in the global namespace.
:param func_name: str
:return: callable
"""
if func_name in globals():
func = globals()[func_name]
elif hasattr(sys.modules[__name__], func_name):
func = getattr(sys.modules[__name__], func_name)
else:
raise RuntimeError('get_callable_from_str: %s not found' % func_name)
if callable(func):
return func
else:
raise RuntimeError('get_callable_from_str: %s not found' % func_name)
def get_d_syn_current_dt_array(syn_current, pre_activity, weights, synapse_tau, synapse_scalar):
"""
Compute the rates of change of all synapses from all the units in a single presynaptic population to all the
units in a single postsynaptic population. Initial currents are provided as a 2D matrix. Initial presynaptic
activity is provided as a 1D array. Weights are provided as a 2D matrix.
:param syn_current: array of float (number of presynaptic units, number of postsynaptic units)
:param pre_activity: array of float (number of presynaptic units)
:param weights: array of float (number of presynaptic units, number of postsynaptic units)
:param synapse_tau: float (seconds)
:param synapse_scalar: float
:return: array of float (number of presynaptic units, number of postsynaptic units)
"""
# repeat the array of presynaptic activities along columns to match the shape of the weights and currents
d_syn_current_dt_array = \
-syn_current / synapse_tau + weights * pre_activity[:, None] * synapse_scalar
return d_syn_current_dt_array
def get_d_cell_voltage_dt_array(cell_voltage, net_current, cell_tau, input_resistance=1.):
"""
Computes the rates of change of cellular voltage in all units of a single population. Initial cell voltages are
provided as a 1D array. The summed initial synaptic currents are provided as a 1D array.
:param cell_voltage: array of float (num units in population)
:param net_current: array of float (num units in population)
:param cell_tau: float (seconds)
:param input_resistance: float
:return: array of float (num units in population)
"""
d_cell_voltage_dt_array = (-cell_voltage + input_resistance * net_current) / cell_tau
return d_cell_voltage_dt_array
def get_d_conductance_dt_array(channel_conductance, pre_activity, rise_tau, decay_tau):
d_conductance_dt_array = -channel_conductance / decay_tau + \
np.maximum(0., pre_activity[:, None] - channel_conductance) / rise_tau
return d_conductance_dt_array
def get_net_current(weights, channel_conductances, cell_voltage, reversal_potential):
net_current_array = ((weights * channel_conductances) * (reversal_potential - cell_voltage))
net_current_array = np.sum(net_current_array, axis=0)
return net_current_array
def get_d_network_intermediates_dt_dicts(num_units_dict, synapse_tau_dict, cell_tau_dict, weight_dict,
weight_config_dict, synaptic_reversal_dict, channel_conductance_dict,
cell_voltage_dict, network_activity_dict):
"""
Computes rates of change of all synaptic currents and all cell voltages for all populations in a network.
:param num_units_dict: dict: {'population': int (number of units in this population)}
:param synapse_tau_dict: nested dict:
{'postsynaptic population label':
{'presynaptic population label':
float (seconds)
}
}
:param cell_tau_dict:
{'population label':
float (seconds)
}
:param weight_dict: nested dict:
{'postsynaptic population label':
{'presynaptic population label':
2d array of float (number of presynaptic units, number of postsynaptic units)
}
}
:param weight_config_dict: nested dict:
{'postsynaptic population label':
{'resynaptic population label':
{'distribution: string
:param syn_current_dict:
{'post population label':
{'pre population label':
2d array of float (number of presynaptic units, number of postsynaptic units)
}
}
:param cell_voltage_dict:
{'population label':
1d array of float (number of units)
}
:param network_activity_dict:
{'population label':
1d array of float (number of units)
}
:return: tuple of dict: (d_syn_current_dt_dict, d_cell_voltage_dt_dict)
"""
d_syn_current_dt_dict = {}
d_cell_voltage_dt_dict = {}
d_conductance_dt_dict = {}
for post_population in weight_dict: # get the change in synaptic currents for every connection
d_conductance_dt_dict[post_population] = {}
this_cell_tau = cell_tau_dict[post_population]
this_net_current = np.zeros_like(network_activity_dict[post_population])
this_cell_voltage = cell_voltage_dict[post_population]
for pre_population in weight_dict[post_population]:
this_decay_tau = synapse_tau_dict[post_population][pre_population]['decay']
this_rise_tau = synapse_tau_dict[post_population][pre_population]['rise']
this_channel_conductance = channel_conductance_dict[post_population][pre_population]
this_pre_activity = network_activity_dict[pre_population]
d_conductance_dt_dict[post_population][pre_population] = \
get_d_conductance_dt_array(this_channel_conductance, this_pre_activity, this_rise_tau, this_decay_tau)
this_weights = weight_dict[post_population][pre_population]
this_connection_type = weight_config_dict[post_population][pre_population]['connection_type']
this_reversal_potential = synaptic_reversal_dict[this_connection_type]
# TODO(done): np.sum should be inside get_net_current
this_net_current += get_net_current(this_weights, channel_conductance_dict[post_population][pre_population],
this_cell_voltage, this_reversal_potential)
#this_net_current += np.sum(syn_current_dict[post_population][pre_population], axis=0)
d_cell_voltage_dt_dict[post_population] = \
get_d_cell_voltage_dt_array(this_cell_voltage, this_net_current, this_cell_tau)
return d_conductance_dt_dict, d_cell_voltage_dt_dict
def nested_dicts_to_flat_state_list(channel_conductance_dict, cell_voltage_dict):
"""
Given nested dictionaries of synaptic currents and cell_voltages, return a flat list of state variables.
Also return a legend that can be used to re-construct the original nested dictionaries. This is in the form
of a nested dictionary of indexes into the flat list.
:param cell_voltage_dict: dict of voltages by population; {pop_name: 1d array of float}
:param syn_current_dict: dict of synaptic currents by projection; {post_pop_name: {pre_pop_name: 2d array of float}}
:return: tuple; (list of float, nested dict: tuple of int indexes)
"""
legend = dict()
state_list = []
legend['cell_voltage'] = dict()
start = 0
legend['channel_conductance'] = dict()
for post_population in sorted(list(channel_conductance_dict.keys())):
legend['channel_conductance'][post_population] = {}
for pre_population in sorted(list(channel_conductance_dict[post_population].keys())):
state_list.extend(np.ravel(channel_conductance_dict[post_population][pre_population]))
end = len(state_list)
legend['channel_conductance'][post_population][pre_population] = (start, end)
start = end
for population in sorted(list(cell_voltage_dict.keys())):
state_list.extend(cell_voltage_dict[population])
end = len(state_list)
legend['cell_voltage'][population] = (start, end)
start = end
return state_list, legend
def flat_state_list_to_nested_dicts(state_list, legend, num_units_dict):
"""
Given a flat list of state variables, use the provided legend to construct nested dictionaries of synaptic currents
and cell_voltages. The legend is in the form of a nested dictionary of indexes into the flat list.
:param state_list: list of float
:param legend: nested dict: tuple of of int indexes
:param num_units_dict: dict of int
:return: tuple; nested dicts of states by population
"""
channel_conductance_dict = dict()
cell_voltage_dict = dict()
for post_population in sorted(list(legend['channel_conductance'].keys())):
channel_conductance_dict[post_population] = {}
for pre_population in sorted(list(legend['channel_conductance'][post_population].keys())):
start = legend['channel_conductance'][post_population][pre_population][0]
end = legend['channel_conductance'][post_population][pre_population][1]
this_state_array = np.array(state_list[start:end]).reshape(
(num_units_dict[pre_population], num_units_dict[post_population]))
channel_conductance_dict[post_population][pre_population] = this_state_array
for population in sorted(list(legend['cell_voltage'].keys())):
start = legend['cell_voltage'][population][0]
end = legend['cell_voltage'][population][1]
cell_voltage_dict[population] = np.array(state_list[start:end])
return channel_conductance_dict, cell_voltage_dict
def simulate_network_dynamics(t, state_list, legend, input_pattern, num_units_dict, synapse_tau_dict, cell_tau_dict,
weight_dict, weight_config_dict, activation_function_dict, synaptic_reversal_dict):
"""
Called by scipy.integrate.solve_ivp to compute the rates of change of all network state variables given a flat list
of initial state values and a pattern of activity in a population of inputs.
:param synaptic_reversal_dict:
:param t: float; time point (seconds)
:param state_list: list of float; flat list of intermediate network variables (synaptic currents and cell voltages)
:param legend: nested dict: tuple of of int indexes
:param input_pattern: array of float (num units in Input population)
:param num_units_dict: dict: {'population': int (number of units in this population)}
:param synapse_tau_dict: nested dict:
{'postsynaptic population label':
{'presynaptic population label':
float (seconds)
}
}
:param cell_tau_dict:
{'population label':
float (seconds)
}
:param weight_dict: nested dict:
{'postsynaptic population label':
{'presynaptic population label':
2d array of float (number of presynaptic units, number of postsynaptic units)
}
}
:param activation_function_dict: dict:
{'population': callable (function to call to convert weighted input to output activity for this population)}
}
:return: list of float; (time derivatives of states variables)
"""
channel_conductance_dict, cell_voltage_dict = flat_state_list_to_nested_dicts(state_list, legend, num_units_dict)
network_activity_dict = {}
network_activity_dict['Input'] = np.copy(input_pattern)
for population in cell_voltage_dict:
this_activation_function = get_callable_from_str(activation_function_dict[population]['Name'])
# TODO(done): may want to have a helper function parse this dictionary
this_kwargs = act_funct_args(population, activation_function_dict)
network_activity_dict[population] = this_activation_function(cell_voltage_dict[population],
**this_kwargs)
d_conductance_dt_dict, d_cell_voltage_dt_dict = \
get_d_network_intermediates_dt_dicts(num_units_dict, synapse_tau_dict, cell_tau_dict, weight_dict,
weight_config_dict, synaptic_reversal_dict, channel_conductance_dict,
cell_voltage_dict, network_activity_dict)
d_state_dt_list, legend = nested_dicts_to_flat_state_list(d_conductance_dt_dict, d_cell_voltage_dt_dict)
return d_state_dt_list
def state_dynamics_to_nested_dicts(state_dynamics, legend, input_pattern, num_units_dict, activation_function_dict,
weight_dict, cell_voltage_dict, weight_config_dict, synaptic_reversal_dict):
"""
The output of scipy.integrate.solve_ivp is a 2D array containing the values of all network state variables (rows)
over time (columns). This function uses the provided legend to construct nested dictionaries of network
intermediates and cell activities. The legend is in the form of a nested dictionary of indexes into the rows of the
state matrix.
:param state_dynamics: 2d array of float (num state variables, num time points)
:param legend: nested dict of int indexes
:param input_pattern: array of float (num units in Input population)
:param num_units_dict: dict: {'population': int (number of units in this population)}
:param activation_function_dict: dict:
{'population': callable (function to call to convert weighted input to output activity for this population)}
}
:return: tuple of nested dict
"""
len_t = state_dynamics.shape[1]
#syn_current_dynamics_dict = {}
net_current_dynamics_dict = {}
cell_voltage_dynamics_dict = {}
network_activity_dynamics_dict = {}
channel_conductance_dynamics_dict = {}
# fancy way to copy static input pattern across additional dimension of time
network_activity_dynamics_dict['Input'] = np.broadcast_to(input_pattern[..., None], input_pattern.shape + (len_t,))
for post_population in legend['channel_conductance']:
channel_conductance_dynamics_dict[post_population] = {}
net_current_dynamics_dict[post_population] = np.zeros((num_units_dict[post_population], len_t))
cell_voltage_dynamics_dict[post_population] = np.empty((num_units_dict[post_population], len_t))
network_activity_dynamics_dict[post_population] = np.empty((num_units_dict[post_population], len_t))
for pre_population in legend['channel_conductance'][post_population]:
channel_conductance_dynamics_dict[post_population][pre_population] = \
np.empty((num_units_dict[pre_population], num_units_dict[post_population], len_t))
for i in range(len_t):
channel_conductance_dict, cell_voltage_dict = \
flat_state_list_to_nested_dicts(state_dynamics[:,i], legend, num_units_dict)
for post_population in channel_conductance_dict:
for pre_population in channel_conductance_dict[post_population]:
channel_conductance_dynamics_dict[post_population][pre_population][:,:,i] = \
channel_conductance_dict[post_population][pre_population]
this_weights = weight_dict[post_population][pre_population]
this_cell_voltage = cell_voltage_dict[post_population]
this_connection_type = weight_config_dict[post_population][pre_population]['connection_type']
this_reversal_potential = synaptic_reversal_dict[this_connection_type]
# TODO: np.sum should happen inside get_net_current
net_current_dynamics_dict[post_population][:,i] += \
np.sum(get_net_current(this_weights, channel_conductance_dict[post_population][pre_population],
this_cell_voltage, this_reversal_potential), axis=0)
for population in cell_voltage_dict:
cell_voltage_dynamics_dict[population][:,i] = cell_voltage_dict[population]
this_activation_function = get_callable_from_str(activation_function_dict[population]['Name'])
this_kwargs = act_funct_args(population, activation_function_dict)
network_activity_dynamics_dict[population][:,i] = \
this_activation_function(cell_voltage_dict[population], **this_kwargs)
return channel_conductance_dynamics_dict, net_current_dynamics_dict, cell_voltage_dynamics_dict, \
network_activity_dynamics_dict
def compute_network_activity_dynamics(t, input_pattern, num_units_dict, synapse_tau_dict, cell_tau_dict, weight_dict,
weight_config_dict,
activation_function_dict, synaptic_reversal_dict):
"""
Use scipy.integrate.solve_ivp to calculate network intermediates and activites over time, in response to a single,
static input pattern.
:param t: array of float
:param input_pattern: array of float (num units in Input population)
:param num_units_dict: dict: {'population': int (number of units in each population)}
:param synapse_tau_dict: dict of dicts:
{'postsynaptic population label':
{'presynaptic population label': float (synaptic time constant for each connection)}}
:param cell_tau_dict: dict: {'population label': float (voltage time constant for each population)}
:param weight_dict: nested dict:
{'postsynaptic population label':
{'presynaptic population label': 2d array of float
(number of presynaptic units, number of postsynaptic units)
}
}
:param activation_function_dict: dict:
{'population': callable (function to call to convert weighted input to output activity for this population)}
}
:param synaptic_reversal_dict:
:return: tuple of nested dict
"""
# Initialize nested dictionaries to contain network intermediates for one time step
# in response to one input pattern
cell_voltage_dict = {}
network_activity_dict = {}
channel_conductance_dict = {}
network_activity_dict['Input'] = np.copy(input_pattern)
for post_population in weight_dict:
channel_conductance_dict[post_population] = {}
for pre_population in weight_dict[post_population]:
channel_conductance_dict[post_population][pre_population] = np.zeros(
(num_units_dict[pre_population], num_units_dict[post_population]))
cell_voltage_dict[post_population] = np.zeros(num_units_dict[post_population])
network_activity_dict[post_population] = np.zeros(num_units_dict[post_population])
initial_state_list, legend = nested_dicts_to_flat_state_list(channel_conductance_dict, cell_voltage_dict)
sol = solve_ivp(simulate_network_dynamics, t_span=(t[0], t[-1]), y0=initial_state_list, t_eval=t,
args=(legend, input_pattern, num_units_dict, synapse_tau_dict, cell_tau_dict,
weight_dict, weight_config_dict, activation_function_dict, synaptic_reversal_dict))
channel_conductance_dynamics_dict, net_current_dynamics_dict, cell_voltage_dynamics_dict, \
network_activity_dynamics_dict = state_dynamics_to_nested_dicts(sol.y, legend, input_pattern, num_units_dict,
activation_function_dict, weight_dict,
cell_voltage_dict, weight_config_dict,
synaptic_reversal_dict)
return channel_conductance_dynamics_dict, net_current_dynamics_dict, cell_voltage_dynamics_dict, \
network_activity_dynamics_dict
def get_network_dynamics_dicts(t, input_patterns, num_units_dict, synapse_tau_dict, cell_tau_dict, weight_dict,
weight_config_dict,
activation_function_dict, synaptic_reversal_dict):
"""
Use scipy.integrate.solve_ivp to calculate network intermediates and activites over time, in response to a set of
input patterns.
static input pattern.
:param t: array of float
:param input_patterns: 2D array of float (num input patterns, num units in Input population)
:param num_units_dict: dict: {'population': int (number of units in each population)}
:param synapse_tau_dict: dict of dicts:
{'postsynaptic population label':
{'presynaptic population label': float (synaptic time constant for each connection)}}
:param cell_tau_dict: dict: {'population label': float (voltage time constant for each population)}
:param weight_dict: nested dict:
{'postsynaptic population label':
{'presynaptic population label': 2d array of float
(number of presynaptic units, number of postsynaptic units)
}
}
:param activation_function_dict: dict:
{'population': callable (function to call to convert weighted input to output activity for this population)}
}
:param synaptic_reversal_dict:
:return: tuple of nested dict
"""
# Initialize nested dictionaries to contain network intermediates in response to a set of input patterns across
# all time steps
channel_conductance_dynamics_dict = {}
net_current_dynamics_dict = {}
cell_voltage_dynamics_dict = {}
network_activity_dynamics_dict = {}
for population in num_units_dict:
network_activity_dynamics_dict[population] = np.empty((len(input_patterns), num_units_dict[population], len(t)))
for post_population in weight_dict:
channel_conductance_dynamics_dict[post_population] = {}
for pre_population in weight_dict[post_population]:
channel_conductance_dynamics_dict[post_population][pre_population] = \
np.empty((len(input_patterns), num_units_dict[pre_population], num_units_dict[post_population], len(t)))
net_current_dynamics_dict[post_population] = \
np.empty((len(input_patterns), num_units_dict[post_population], len(t)))
cell_voltage_dynamics_dict[post_population] = \
np.empty((len(input_patterns), num_units_dict[post_population], len(t)))
for pattern_index in range(len(input_patterns)):
this_input_pattern = input_patterns[pattern_index]
this_channel_conductance_dynamics_dict, this_net_current_dynamics_dict, this_cell_voltage_dynamics_dict, \
this_network_activity_dynamics_dict = \
compute_network_activity_dynamics(t, this_input_pattern, num_units_dict, synapse_tau_dict, cell_tau_dict,
weight_dict, weight_config_dict, activation_function_dict,
synaptic_reversal_dict)
for population in this_network_activity_dynamics_dict:
network_activity_dynamics_dict[population][pattern_index, :, :] = \
this_network_activity_dynamics_dict[population]
for post_population in this_channel_conductance_dynamics_dict:
for pre_population in this_channel_conductance_dynamics_dict[post_population]:
channel_conductance_dynamics_dict[post_population][pre_population][pattern_index, :, :, :] = \
this_channel_conductance_dynamics_dict[post_population][pre_population]
net_current_dynamics_dict[post_population][pattern_index, :, :] = \
this_net_current_dynamics_dict[post_population]
cell_voltage_dynamics_dict[post_population][pattern_index, :, :] = \
this_cell_voltage_dynamics_dict[post_population]
return channel_conductance_dynamics_dict, net_current_dynamics_dict, cell_voltage_dynamics_dict, \
network_activity_dynamics_dict
def slice_network_activity_dynamics_dict(network_activity_dynamics_dict, t, time_point):
"""
Given network activity dynamics across a set of input patterns over all time points, return network activity across
all input patterns at the time point specified.
:param network_activity_dynamics_dict: dict of 3d array of float;
{'population label':
3d array of float (number of input patterns, number of units in this population, number of time points)
}
:param t: array of float
:param time_point: float
:return: dict of 2d array of float;
{'population label':
2d array of float (number of input patterns, number of units in this population)
}
"""
network_activity_dict = {}
if isinstance(time_point, (tuple, list)) and len(time_point) == 2:
t_start_index = np.where(t >= time_point[0])[0][0]
t_end_index = np.where(t >= time_point[1])[0][0]
for population in network_activity_dynamics_dict:
network_activity_dict[population] = \
np.mean(network_activity_dynamics_dict[population][:, :, t_start_index:t_end_index], axis=2)
elif isinstance(time_point, (str, int, float)):
time_point = max(float(time_point), t[-1])
t_index = np.where(t >= float(time_point))[0][0]
for population in network_activity_dynamics_dict:
network_activity_dict[population] = network_activity_dynamics_dict[population][:, :, t_index]
else:
raise AssertionError('time_point must be float or length 2 list or tuple')
return network_activity_dict
def gini_coefficient(x):
x = np.asarray(x) + 0.0001
sorted_x = np.sort(x)
n = len(x)
cumx = np.cumsum(sorted_x, dtype=float)
return (n + 1 - 2 * np.sum(cumx) / cumx[-1]) / n
def analyze_slice(network_activity_dict):
"""
For each population, for each input pattern, compute sparsity.
For each population, compare the reponses across all input patterns using cosine similarity. Exclude responses where
all units in a population are zero.
:param network_activity_dict: dict:
{'population label': 2d array of float (number of input patterns, number of units in this population)
}
:return: tuple of dict:
sparsity_dict: dict:
{'population label': 1d array of float (number of input patterns),
similarity_matrix_dict: dict:
{'population label': 2d array of float
(number of valid response patterns, number of valid response patterns)
}
"""
sparsity_dict = {}
similarity_matrix_dict = {}
selectivity_dict = {}
fraction_active_patterns_dict = {}
fraction_active_units_dict = {}
num_patterns = network_activity_dict['Input'].shape[0]
for population in network_activity_dict:
# number of nonzero units per pattern
sparsity_dict[population] = np.count_nonzero(network_activity_dict[population], axis=1)
# if pop activity is 0, remove this sample from similarity calculation
invalid_indexes = np.where(sparsity_dict[population] == 0.)[0]
similarity_matrix_dict[population] = cosine_similarity(network_activity_dict[population])
similarity_matrix_dict[population][invalid_indexes, :] = np.nan
similarity_matrix_dict[population][:, invalid_indexes] = np.nan
invalid_indexes = np.where(sparsity_dict[population] == 0.)[0]
fraction_active_patterns_dict[population] = 1. - len(invalid_indexes) / num_patterns
# number of nonzero patterns per unit
selectivity_dict[population] = np.count_nonzero(network_activity_dict[population], axis=0)
invalid_indexes = np.where(selectivity_dict[population] == 0.)[0]
fraction_active_units_dict[population] = 1. - len(invalid_indexes) / num_patterns
return sparsity_dict, similarity_matrix_dict, selectivity_dict, fraction_active_patterns_dict, \
fraction_active_units_dict
def analyze_dynamics(network_activity_dynamics_dict):
"""
For each population, for each input pattern, for each time point, compute sparsity. For each time
point, return the median activity across input patterns.
For each population, for each time point, compare the reponses across all input patterns using cosine similarity.
Exclude responses where all units in a population are zero. For each time point, return the median similarity across
all valid pairs of response patterns.
:param network_activity_dynamics_dict: dict:
{'population label': 3d array of float
(number of input patterns, number of units in this population, number of timepoints)
}
:return: :return: tuple of dict:
median_sparsity_dynamics_dict: dict:
{'population label': 1d array of float (number of time points),
median_similarity_dynamics_dict: dict:
{'population label': 1d array of float (number of time points)
}
"""
sparsity_dynamics_dict = {}
similarity_dynamics_dict = {}
selectivity_dynamics_dict = {}
fraction_nonzero_response_dynamics_dict = {}
first_activity_dynamics_matrix = next(iter(network_activity_dynamics_dict.values()))
num_patterns = first_activity_dynamics_matrix.shape[0]
len_t = first_activity_dynamics_matrix.shape[-1]
for population in network_activity_dynamics_dict:
pop_size = network_activity_dynamics_dict[population].shape[1]
sparsity_dynamics_dict[population] = np.empty([len_t,num_patterns])
similarity_dynamics_dict[population] = np.empty([len_t,num_patterns, num_patterns])
selectivity_dynamics_dict[population] = np.empty([len_t,pop_size])
fraction_nonzero_response_dynamics_dict[population] = np.empty([len_t])
for i in range(len_t):
sparsity = np.count_nonzero(network_activity_dynamics_dict[population][:, :, i], axis=1)
sparsity_dynamics_dict[population][i] = sparsity
invalid_indexes = np.where(sparsity == 0.)[0]
fraction_nonzero_response_dynamics_dict[population][i] = 1. - len(invalid_indexes) / num_patterns
similarity_matrix = cosine_similarity(network_activity_dynamics_dict[population][:, :, i])
similarity_matrix[invalid_indexes, :] = np.nan
similarity_matrix[:, invalid_indexes] = np.nan
similarity_dynamics_dict[population][i] = similarity_matrix
selectivity = np.count_nonzero(network_activity_dynamics_dict[population][:, :, i], axis=0)
selectivity_dynamics_dict[population][i] = selectivity
# selectivity = []
# for unit in range(pop_size):
# unit_activity = network_activity_dynamics_dict[population][:, unit, i]
# selectivity.append(gini_coefficient(unit_activity))
# selectivity_dynamics_dict[population][i] = np.array(selectivity)
return sparsity_dynamics_dict, similarity_dynamics_dict, \
selectivity_dynamics_dict, fraction_nonzero_response_dynamics_dict
def analyze_median_dynamics(network_activity_dynamics_dict):
"""
For each population, for each input pattern, for each time point, compute sparsity. For each time
point, return the median activity across input patterns.
For each population, for each time point, compare the reponses across all input patterns using cosine similarity.
Exclude responses where all units in a population are zero. For each time point, return the median similarity across
all valid pairs of response patterns.
:param network_activity_dynamics_dict: dict:
{'population label': 3d array of float
(number of input patterns, number of units in this population, number of timepoints)
}
:return: :return: tuple of dict:
median_sparsity_dynamics_dict: dict:
{'population label': 1d array of float (number of time points),
median_similarity_dynamics_dict: dict:
{'population label': 1d array of float (number of time points)
}
"""
median_sparsity_dynamics_dict = {}
median_similarity_dynamics_dict = {}
mean_selectivity_dynamics_dict = {}
fraction_nonzero_response_dynamics_dict = {}
first_activity_dynamics_matrix = next(iter(network_activity_dynamics_dict.values()))
num_patterns = first_activity_dynamics_matrix.shape[0]
len_t = first_activity_dynamics_matrix.shape[-1]
for population in network_activity_dynamics_dict:
median_sparsity_dynamics_dict[population] = np.empty(len_t)
median_similarity_dynamics_dict[population] = np.empty(len_t)
mean_selectivity_dynamics_dict[population] = np.empty(len_t)
fraction_nonzero_response_dynamics_dict[population] = np.empty(len_t)
for i in range(len_t):
sparsity = np.count_nonzero(network_activity_dynamics_dict[population][:, :, i], axis=1)
median_sparsity_dynamics_dict[population][i] = np.median(sparsity)
invalid_indexes = np.where(sparsity == 0.)[0]
fraction_nonzero_response_dynamics_dict[population][i] = 1. - len(invalid_indexes) / num_patterns
similarity_matrix = cosine_similarity(network_activity_dynamics_dict[population][:, :, i])
similarity_matrix[invalid_indexes, :] = np.nan
similarity_matrix[:, invalid_indexes] = np.nan
median_similarity_dynamics_dict[population][i] = np.nanmedian(similarity_matrix)
nonzero_idx = np.where(network_activity_dynamics_dict[population][:, :, i] > 0)
selectivity_nonzero_count = np.unique(nonzero_idx[1], return_counts=True)[1]
mean_selectivity_dynamics_dict[population][i] = np.mean(selectivity_nonzero_count)
# # Compute selectivity using Gini coefficient:
# selectivity = []
# for unit in range(network_activity_dynamics_dict[population].shape[1]):
# unit_activity = network_activity_dynamics_dict[population][:, unit, i]
# selectivity.append(gini_coefficient(unit_activity))
# selectivity_dynamics_dict[population][i] = np.array(selectivity)
return median_sparsity_dynamics_dict, median_similarity_dynamics_dict, \
mean_selectivity_dynamics_dict, fraction_nonzero_response_dynamics_dict
def plot_model_summary(network_activity_dict, sparsity_dict, similarity_matrix_dict, selectivity_dict, description=None):
"""
Generate a panel of plots summarizing the activity of each layer.
:param network_activity_dict: dict:
{'population label': 2d array of float (number of input patterns, number of units in this population)
}
:param sparsity_dict: dict:
{'population label': 1d array of float (number of input patterns)
}
:param similarity_matrix_dict: dict:
{'population label': 2d array of float (number of input patterns, number of input patterns)
}
:param description: str
"""
num_of_populations = len(network_activity_dict)
fig1, axes = plt.subplots(3, num_of_populations, figsize=(3 * num_of_populations, 8))
for i, population in enumerate(network_activity_dict):
# Show activity heatmap of units for all patterns
argmax_indices = np.argmax(network_activity_dict[population], axis=0)
sorted_indices = np.argsort(argmax_indices)
im1 = axes[0, i].imshow(network_activity_dict[population][:, sorted_indices].transpose(), aspect='auto', cmap='binary')
# im1 = axes[0, i].imshow(network_activity_dict[population], aspect='auto')
cbar = plt.colorbar(im1, ax=axes[0, i])
cbar.ax.set_ylabel('Unit activity', rotation=270, labelpad=20)
axes[0, i].set_ylabel('Unit ID')
axes[0, i].set_xlabel('Input pattern ID')
axes[0, i].set_title('Activity\n%s population' % population)
# Plot sparsity over patterns
axes[1, i].scatter(range(len(network_activity_dict[population])), sparsity_dict[population])
axes[1, i].set_xlabel('Input pattern ID')
axes[1, i].set_ylabel('Num nonzero units')
axes[1, i].set_title('Sparsity \n%s population' % population)
axes[1, i].spines["top"].set_visible(False)
axes[1, i].spines["right"].set_visible(False)
# Plot similarity matrix heatmap
im2 = axes[2, i].imshow(similarity_matrix_dict[population], aspect='auto')
axes[2, i].set_xlabel('Input pattern ID')
axes[2, i].set_ylabel('Input pattern ID')
axes[2, i].set_title('Similarity\n%s population' % population)
plt.colorbar(im2, ax=axes[2, i])
fig2, axes = plt.subplots(2, num_of_populations, figsize=(3 * num_of_populations, 5))
for i, population in enumerate(network_activity_dict):
# Plot discriminability distribution
row = 0
bin_width = 0.05
num_valid_patterns = len(np.where(sparsity_dict[population] > 0.)[0])
invalid_indexes = np.isnan(similarity_matrix_dict[population])
if len(invalid_indexes) < similarity_matrix_dict[population].size:
hist, edges = np.histogram(similarity_matrix_dict[population][~invalid_indexes],
bins=np.arange(-bin_width / 2., 1 + bin_width, bin_width), density=True)
axes[row, i].plot(edges[:-1] + bin_width / 2., hist * bin_width,
label='%.0f inactive pattern' %
(len(sparsity_dict[population]) - num_valid_patterns))
axes[row, i].set_xlabel('Cosine similarity')
axes[row, i].set_ylabel('Probability')
axes[row, i].set_title('Pairwise similarity distribution\n%s population' % population)
axes[row, i].legend(loc='best', frameon=False)
axes[row, i].spines["top"].set_visible(False)
axes[row, i].spines["right"].set_visible(False)
# Plot selectivity distribution
row = 1
num_nonzero_units = np.count_nonzero(selectivity_dict[population])
active_units_idx = np.where(selectivity_dict[population] > 0)
if num_nonzero_units > 0:
max_response = np.max(selectivity_dict[population])
else:
max_response = 1.
bin_width = max_response / 20
hist, edges = np.histogram(selectivity_dict[population][active_units_idx],
bins=np.arange(-bin_width / 2., max_response + bin_width, bin_width), density=True)
axes[row, i].plot(edges[:-1] + bin_width / 2., hist * bin_width,
label='%.0f inactive units' %
(len(selectivity_dict[population]) - num_nonzero_units))
axes[row, i].set_xlabel('Selectivity (# patterns w/ activity)')
axes[row, i].set_ylabel('Probability')
axes[row, i].set_title('Selectivity distribution\n%s population' % population)
axes[row, i].legend(loc='best', frameon=False)
axes[row, i].spines["top"].set_visible(False)
axes[row, i].spines["right"].set_visible(False)
if description is not None:
fig1.suptitle(description)
fig2.suptitle(description)
fig1.tight_layout(w_pad=3, h_pad=2, rect=(0., 0., 1., 0.98))
fig1.show()
fig2.tight_layout(w_pad=3, h_pad=2, rect=(0., 0., 1., 0.98))
fig2.show()
def plot_compare_model_sparsity_and_similarity(sparsity_history_dict, similarity_matrix_history_dict):
"""
Generate a panel of plots comparing different model configuration.
:param sparsity_history_dict: nested dict:
{'model description':
{'population label': 1d array of float (number of input patterns)}
}
:param similarity_matrix_history_dict: nested dict:
{'model description':
{'population label': 2d array of float (number of input patterns, number of input patterns)}
}
"""
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
for j, description in enumerate(sparsity_history_dict):
for i, population in enumerate(['Input', 'Output']):
axes[0, i].scatter(range(len(sparsity_history_dict[description][population])),
sparsity_history_dict[description][population], label=description)
bin_width = 0.05
num_valid_patterns = len(np.where(sparsity_history_dict[description][population] > 0.)[0])
invalid_indexes = np.isnan(similarity_matrix_history_dict[description][population])
if len(invalid_indexes) < similarity_matrix_history_dict[description][population].size:
hist, edges = np.histogram(similarity_matrix_history_dict[description][population][~invalid_indexes],
bins=np.arange(-bin_width / 2., 1 + bin_width, bin_width), density=True)
axes[1, i].plot(edges[:-1] + bin_width / 2., hist * bin_width,
label='%.0f%% nonzero' %
(100. * num_valid_patterns /
len(sparsity_history_dict[description][population])))
if j == 0:
axes[0, i].set_xlabel('Input pattern ID')
axes[0, i].set_ylabel('Sparsity')
axes[0, i].set_title('Sparsity\n%s population' % population)
axes[0, i].spines["top"].set_visible(False)
axes[0, i].spines["right"].set_visible(False)
axes[1, i].set_xlabel('Cosine similarity')
axes[1, i].set_ylabel('Probability')
axes[1, i].set_title('Pairwise similarity distribution\n%s population' % population)
axes[1, i].spines["top"].set_visible(False)
axes[1, i].spines["right"].set_visible(False)
axes[0, 0].legend(loc='best', frameon=False)
axes[1, 1].legend(loc='best', frameon=False)
fig.tight_layout(w_pad=3, h_pad=3, rect=(0., 0., 1., 0.98))
fig.show()
def plot_dynamics(t, median_sparsity_dynamics_dict, median_similarity_dynamics_dict,
mean_selectivity_dynamics_dict, fraction_nonzero_response_dynamics_dict, description=None):
"""
:param t: array of float
:param median_sparsity_dynamics_dict: dict:
{'population label': 1d array of float (number of time points)
:param median_similarity_dynamics_dict: dict:
{'population label': 1d array of float (number of time points)
:param mean_selectivity_dynamics_dict: dict:
{'population label': 1d array of float (number of time points)
:param fraction_nonzero_response_dynamics_dict: dict:
{'population label': 1d array of int (number of time points)
:param description: str
"""
num_of_populations = len(median_sparsity_dynamics_dict)
fig, axes = plt.subplots(4, num_of_populations, figsize=(3.5 * num_of_populations, 9))
for i, population in enumerate(median_sparsity_dynamics_dict):
axes[0, i].plot(t, median_sparsity_dynamics_dict[population])
axes[0, i].set_xlabel('Time (s)')
axes[0, i].set_ylabel('sparsity')
axes[0, i].set_title('Median sparsity\n%s population' % population)
axes[0, i].spines["top"].set_visible(False)
axes[0, i].spines["right"].set_visible(False)
axes[1, i].plot(t, 100. * fraction_nonzero_response_dynamics_dict[population])
axes[1, i].set_xlabel('Time (s)')
axes[1, i].set_ylabel('Nonzero responses\n(% of patterns)')
axes[1, i].set_title('Nonzero responses\n%s population' % population)
axes[1, i].set_ylim([0,100])
axes[1, i].spines["top"].set_visible(False)
axes[1, i].spines["right"].set_visible(False)
axes[2, i].plot(t, median_similarity_dynamics_dict[population])
axes[2, i].set_xlabel('Time (s)')
axes[2, i].set_ylabel('Cosine similarity')
axes[2, i].set_title('Median pairwise similarity\n%s population' % population)
axes[2, i].spines["top"].set_visible(False)
axes[2, i].spines["right"].set_visible(False)
axes[3,i].plot(t, mean_selectivity_dynamics_dict[population])
axes[3, i].set_xlabel('Time (s)')
axes[3, i].set_ylabel('Selectivity')
axes[3, i].set_title('Mean selectivity \n%s population' % population)
axes[3, i].spines["top"].set_visible(False)
axes[3, i].spines["right"].set_visible(False)
if description is not None:
fig.suptitle(description)
fig.tight_layout(w_pad=3, h_pad=3, rect=(0., 0., 1., 0.98))
fig.show()
def plot_compare_sparsity_and_similarity_dynamics(t, median_sparsity_history_dict,