-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconn_prob.py
2985 lines (2622 loc) · 130 KB
/
conn_prob.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
# This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
"""Module for building stochastic connection probability models of various model orders"""
from functools import partial
import itertools
import os.path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import progressbar
from scipy.ndimage import gaussian_filter
from scipy.optimize import curve_fit
from scipy.sparse import csr_matrix
from voxcell import VoxelData
from connectome_manipulator import log
from connectome_manipulator.model_building import model_types
from connectome_manipulator.access_functions import (
get_node_ids,
get_edges_population,
get_node_positions,
get_connections,
get_cv_data,
)
JET = plt.get_cmap("jet")
HOT = plt.get_cmap("hot")
def extract(
circuit,
order,
sel_src=None,
sel_dest=None,
sample_size=None,
edges_popul_name=None,
CV_dict=None,
**kwargs,
):
"""Extracts the connection probabilities between samples of neurons.
Args:
circuit (bluepysnap.Circuit): Input circuit
order (str): Model order, such as "1" (constant), "2" (distance-dependent), "3" (bipolar distance-dependent), "4" (offset-dependent), "4R" (reduced offset-dependent), "5" (position-dependent), "5R" (reduced position dependent)
sel_src (str/list-like/dict): Source (pre-synaptic) neuron selection
sel_dest (str/list-like/dict): Target (post-synaptic) neuron selection
sample_size (int): Size of random subsample of data to extract data from
edges_popul_name (str): Name of SONATA egdes population to extract data from
CV_dict (dict): Optional cross-validation dictionary, containing "n_folds" (int), "fold_idx" (int), "training_set" (bool) keys; will be automatically provided by the framework if "CV_folds" are specified
**kwargs: Additional keyword arguments depending on the model order; see Notes
Returns:
dict: Dictionary containing the extracted connection probability data depending on the model order
Note:
For (optional) keyword arguments, see details in the respective helper functions:
* Order 1: :func:`extract_1st_order`
* Order 2: :func:`extract_2nd_order`
* Order 3: :func:`extract_3rd_order`
* Order 4: :func:`extract_4th_order`
* Order 4R: :func:`extract_4th_order_reduced`
* Order 5: :func:`extract_5th_order`
* Order 5R: :func:`extract_5th_order_reduced`
"""
log.info(
f"Running order-{order} data extraction (sel_src={sel_src}, sel_dest={sel_dest}, sample_size={sample_size} neurons, CV_dict={CV_dict})..."
)
# Select edge population
edges = get_edges_population(circuit, edges_popul_name)
# Select corresponding source/target nodes populations
src_nodes = edges.source
tgt_nodes = edges.target
nodes = [src_nodes, tgt_nodes]
node_ids_src = get_node_ids(src_nodes, sel_src)
node_ids_dest = get_node_ids(tgt_nodes, sel_dest)
if map_file := kwargs.get("pos_map_file") is not None:
log.log_assert(
(src_nodes.name == tgt_nodes.name)
or (isinstance(map_file, list) and len(map_file) == 2),
f'Separate source/target position mappings required for different node populations "{src_nodes.name}" and "{tgt_nodes.name}"!',
)
if sample_size is None or sample_size <= 0:
sample_size = np.inf # Select all nodes
if sample_size < len(node_ids_src) or sample_size < len(node_ids_dest):
log.warning(
"Sub-sampling neurons! Consider running model building with a different random sub-samples!"
)
sample_size_src = min(sample_size, len(node_ids_src))
sample_size_dest = min(sample_size, len(node_ids_dest))
log.log_assert(sample_size_src > 0 and sample_size_dest > 0, "ERROR: Empty nodes selection!")
node_ids_src_sel = node_ids_src[
np.random.permutation(
[True] * sample_size_src + [False] * (len(node_ids_src) - sample_size_src)
)
]
node_ids_dest_sel = node_ids_dest[
np.random.permutation(
[True] * sample_size_dest + [False] * (len(node_ids_dest) - sample_size_dest)
)
]
# Cross-validation (optional)
node_ids_src_sel, node_ids_dest_sel = get_cv_data(
[node_ids_src_sel, node_ids_dest_sel], CV_dict
)
if not isinstance(order, str):
order = str(order)
if order == "1":
return extract_1st_order(nodes, edges, node_ids_src_sel, node_ids_dest_sel, **kwargs)
elif order == "2":
return extract_2nd_order(nodes, edges, node_ids_src_sel, node_ids_dest_sel, **kwargs)
elif order == "3":
return extract_3rd_order(nodes, edges, node_ids_src_sel, node_ids_dest_sel, **kwargs)
elif order == "4":
return extract_4th_order(nodes, edges, node_ids_src_sel, node_ids_dest_sel, **kwargs)
elif order == "4R":
return extract_4th_order_reduced(
nodes, edges, node_ids_src_sel, node_ids_dest_sel, **kwargs
)
elif order == "5":
return extract_5th_order(nodes, edges, node_ids_src_sel, node_ids_dest_sel, **kwargs)
elif order == "5R":
return extract_5th_order_reduced(
nodes, edges, node_ids_src_sel, node_ids_dest_sel, **kwargs
)
else:
log.log_assert(False, f"ERROR: Order-{order} data extraction not supported!")
return None
def build(order, **kwargs):
"""Builds a stochastic connection probability model from (binned) data.
Args:
order (str): Model order, such as "1" (constant), "2" (distance-dependent), "3" (bipolar distance-dependent), "4" (offset-dependent), "4R" (reduced offset-dependent), "5" (position-dependent), "5R" (reduced position dependent)
**kwargs: Additional keyword arguments depending on the model order; see Notes
Returns:
Type depends on the model order; see Notes: Fitted stochastic connection probability model
Note:
For (optional) keyword arguments and return types, see details in the respective helper functions:
* Order 1: :func:`build_1st_order`
* Order 2: :func:`build_2nd_order`
* Order 3: :func:`build_3rd_order`
* Order 4: :func:`build_4th_order`
* Order 4R: :func:`build_4th_order_reduced`
* Order 5: :func:`build_5th_order`
* Order 5R: :func:`build_5th_order_reduced`
"""
log.info(f"Running order-{order} model building...")
if not isinstance(order, str):
order = str(order)
if order == "1":
return build_1st_order(**kwargs)
elif order == "2":
return build_2nd_order(**kwargs)
elif order == "3":
return build_3rd_order(**kwargs)
elif order == "4":
return build_4th_order(**kwargs)
elif order.upper() == "4R":
return build_4th_order_reduced(**kwargs)
elif order == "5":
return build_5th_order(**kwargs)
elif order == "5R":
return build_5th_order_reduced(**kwargs)
else:
log.log_assert(False, f"ERROR: Order-{order} model building not supported!")
return None
def plot(order, **kwargs):
"""Visualizes extracted data vs. actual model output.
Args:
order (str): Model order, such as "1" (constant), "2" (distance-dependent), "3" (bipolar distance-dependent), "4" (offset-dependent), "4R" (reduced offset-dependent), "5" (position-dependent), "5R" (reduced position dependent)
**kwargs: Additional keyword arguments depending on the model order; see Notes
Note:
For (optional) keyword arguments, see details in the respective helper functions:
* Order 1: :func:`plot_1st_order`
* Order 2: :func:`plot_2nd_order`
* Order 3: :func:`plot_3rd_order`
* Order 4: :func:`plot_4th_order`
* Order 4R: :func:`plot_4th_order_reduced`
* Order 5: :func:`plot_5th_order`
* Order 5R: :func:`plot_5th_order_reduced`
"""
log.info(f"Running order-{order} data/model visualization...")
if not isinstance(order, str):
order = str(order)
if order == "1":
return plot_1st_order(**kwargs)
elif order == "2":
return plot_2nd_order(**kwargs)
elif order == "3":
return plot_3rd_order(**kwargs)
elif order == "4":
return plot_4th_order(**kwargs)
elif order == "4R":
return plot_4th_order_reduced(**kwargs)
elif order == "5":
return plot_5th_order(**kwargs)
elif order == "5R":
return plot_5th_order_reduced(**kwargs)
else:
log.log_assert(False, f"ERROR: Order-{order} data/model visualization not supported!")
return None
###################################################################################################
# Helper functions
###################################################################################################
def pos_accessor(pos_map, gids):
"""Access function"""
if pos_map is None:
return None
else:
return pos_map.apply(gids=gids)
def get_pos_mapping_fcts(pos_map_file):
"""Get access functions to one or two (src/tgt) position mappings from model (.json) or voxel data (.nrrd) file(s)."""
def get_mapping(file):
"""Returns single mapping from .json or .nrrd file."""
pos_acc = None
vox_map = None
if str.lower(os.path.splitext(file)[-1]) == ".json":
_, pos_acc = load_pos_mapping_model(file) # Model access
elif str.lower(os.path.splitext(file)[-1]) == ".nrrd":
vox_map = VoxelData.load_nrrd(file) # Direct access to voxel data
log.info(f"Loading position mapping (voxel data) from {file}")
log.log_assert(vox_map.ndim == 3, "3D voxel data required!")
else:
log.log_assert(False, "Position mapping file error (must be .json or .nrrd)!")
return pos_acc, vox_map
if pos_map_file is None:
pos_acc_src = pos_acc_tgt = None
vox_map_src = vox_map_tgt = None
elif isinstance(pos_map_file, list):
log.log_assert(
len(pos_map_file) == 2, "Two position mapping files (source/target) expected!"
)
log.log_assert(
str.lower(os.path.splitext(pos_map_file[0])[-1])
== str.lower(os.path.splitext(pos_map_file[1])[-1]),
"Same file type for source/target position mappings required!",
)
pos_acc_src, vox_map_src = get_mapping(pos_map_file[0])
pos_acc_tgt, vox_map_tgt = get_mapping(pos_map_file[1])
else: # Same mapping for src/tgt
pos_acc_src, vox_map_src = get_mapping(pos_map_file)
pos_acc_tgt = pos_acc_src
vox_map_tgt = vox_map_src
if pos_acc_src is None and pos_acc_tgt is None:
pos_acc = None
else:
pos_acc = [pos_acc_src, pos_acc_tgt]
if vox_map_src is None and vox_map_tgt is None:
vox_map = None
else:
vox_map = [vox_map_src, vox_map_tgt]
if pos_acc is None and vox_map is None:
log.debug("No position mapping provided")
return pos_acc, vox_map
def load_pos_mapping_model(pos_map_file):
"""Load a position mapping model from file (incl. access function)."""
if pos_map_file is None:
pos_map = None
pos_acc = None
else:
log.log_assert(os.path.exists(pos_map_file), "Position mapping model file not found!")
log.info(f"Loading position mapping model from {pos_map_file}")
pos_map = model_types.AbstractModel.model_from_file(pos_map_file)
log.log_assert(
pos_map.input_names == ["gids"],
'ERROR: Position mapping model error (must take "gids" as input)!',
)
pos_acc = partial(pos_accessor, pos_map)
return pos_map, pos_acc
def get_neuron_positions(nodes, node_ids, pos_acc=None, vox_map=None):
"""Get neuron positions, optionally using a position mapping.
Two types of mappings are supported:
- pos_acc: Position access function indexed by node ID
- vox_map: Voxel map accessed by node position
"""
if pos_acc: # Position mapping model provided
nrn_pos = get_neuron_positions_by_id(pos_acc, node_ids)
log.log_assert(
vox_map is None, "Voxel map not supported when providing position access functions!"
)
else:
nrn_pos = [
get_node_positions(nodes[i], node_ids[i], vox_map[i] if vox_map else None)[1]
for i in range(len(nodes))
]
return nrn_pos
def get_neuron_positions_by_id(pos_fct, node_ids_list):
"""Get neuron positions indexed by node ID (using position access/mapping function).
node_ids_list should be list of node_ids lists!
"""
if not isinstance(pos_fct, list):
pos_fct = [pos_fct for i in node_ids_list]
else:
log.log_assert(
len(pos_fct) == len(node_ids_list),
'ERROR: "pos_fct" must be scalar or a list with same length as "node_ids_list"!',
)
nrn_pos = [np.array(pos_fct[i](node_ids_list[i])) for i in range(len(node_ids_list))]
return nrn_pos
def extract_dependent_p_conn(
src_node_ids, tgt_node_ids, edges, dep_matrices, dep_bins, min_count_per_bin=None
):
"""Extract D-dimensional conn. prob. dependent on D property matrices between source-target pairs of neurons within given range of bins."""
num_dep = len(dep_matrices)
log.log_assert(len(dep_bins) == num_dep, "ERROR: Dependencies/bins mismatch!")
log.log_assert(
np.all(
[
dep_matrices[dim].shape == (len(src_node_ids), len(tgt_node_ids))
for dim in range(num_dep)
]
),
"ERROR: Matrix dimension mismatch!",
)
# Extract adjacency
conns = get_connections(edges, src_node_ids, tgt_node_ids)
if len(conns) > 0:
adj_mat = csr_matrix(
(np.full(conns.shape[0], True), conns.T.tolist()),
shape=(max(src_node_ids) + 1, max(tgt_node_ids) + 1),
)
else:
adj_mat = csr_matrix((max(src_node_ids) + 1, max(tgt_node_ids) + 1)) # Empty matrix
if np.any(adj_mat.diagonal()):
log.debug("Autaptic connection(s) found!")
# Extract connection probability
num_bins = [len(b) - 1 for b in dep_bins]
bin_indices = [list(range(n)) for n in num_bins]
count_all = np.full(
num_bins, -1
) # Count of all pairs of neurons for each combination of dependencies
count_conn = np.full(
num_bins, -1
) # Count of connected pairs of neurons for each combination of dependencies
log.debug(
f'Extracting {num_dep}-dimensional ({"x".join([str(n) for n in num_bins])}) connection probabilities...'
)
pbar = progressbar.ProgressBar(maxval=np.prod(num_bins) - 1)
for idx in pbar(itertools.product(*bin_indices)):
dep_sel = np.full((len(src_node_ids), len(tgt_node_ids)), True)
for dim in range(num_dep):
lower = dep_bins[dim][idx[dim]]
upper = dep_bins[dim][idx[dim] + 1]
dep_sel = np.logical_and(
dep_sel,
np.logical_and(
dep_matrices[dim] >= lower,
(
(dep_matrices[dim] < upper)
if idx[dim] < num_bins[dim] - 1
else (dep_matrices[dim] <= upper)
),
),
) # Including last edge
sidx, tidx = np.nonzero(dep_sel)
count_all[idx] = np.sum(dep_sel)
# count_conn[idx] = np.sum(adj_mat[src_node_ids[sidx], tgt_node_ids[tidx]]) # ERROR in scipy/sparse/compressed.py if len(sidx) >= 2**31: "ValueError: could not convert integer scalar"
# [WORKAROUND]: Split indices into parts of 2**31-1 length and sum them separately
sidx_split = np.split(sidx, np.arange(0, len(sidx), 2**31 - 1)[1:])
tidx_split = np.split(tidx, np.arange(0, len(tidx), 2**31 - 1)[1:])
count_split = 0
for s, t in zip(sidx_split, tidx_split):
count_split = count_split + np.sum(adj_mat[src_node_ids[s], tgt_node_ids[t]])
count_conn[idx] = count_split
p_conn = np.array(count_conn / count_all)
# p_conn[np.isnan(p_conn)] = 0.0
# Check bin counts below threshold and ignore
if min_count_per_bin is None:
min_count_per_bin = 0 # No threshold
bad_bins = np.logical_and(count_all > 0, count_all < min_count_per_bin)
if np.sum(bad_bins) > 0:
log.warning(
f"Found {np.sum(bad_bins)} of {count_all.size} ({100.0 * np.sum(bad_bins) / count_all.size:.1f}%) bins with less than th={min_count_per_bin} pairs of neurons ... IGNORING! (Consider increasing sample size and/or bin size and/or smoothing!)"
)
p_conn[bad_bins] = np.nan # 0.0
return p_conn, count_conn, count_all
def get_value_ranges(max_range, num_coords, pos_range=False):
"""Returns ranges of values for given max. ranges (strictly positive incl. zero, symmetric around zero, or arbitrary)"""
if np.isscalar(pos_range):
pos_range = [pos_range for i in range(num_coords)]
else:
if num_coords == 1: # Special case
pos_range = [pos_range]
log.log_assert(
len(pos_range) == num_coords, f"ERROR: pos_range must have {num_coords} elements!"
)
if np.isscalar(max_range):
max_range = [max_range for i in range(num_coords)]
else:
if num_coords == 1: # Special case
max_range = [max_range]
log.log_assert(
len(max_range) == num_coords, f"ERROR: max_range must have {num_coords} elements!"
)
val_ranges = []
for ridx, (r, p) in enumerate(zip(max_range, pos_range)):
if np.isscalar(r):
log.log_assert(r > 0.0, f"ERROR: Maximum range of coord {ridx} must be larger than 0!")
if p: # Positive range
val_ranges.append([0, r])
else: # Symmetric range
val_ranges.append([-r, r])
else: # Arbitrary range
log.log_assert(len(r) == 2 and r[0] < r[1], f"ERROR: Range of coord {ridx} invalid!")
if p:
log.log_assert(r[0] == 0, f"ERROR: Range of coord {ridx} must include 0!")
val_ranges.append(r)
if num_coords == 1: # Special case
return val_ranges[0]
else:
return val_ranges
###################################################################################################
# Generative models for circuit connectivity from [Gal et al. 2020]:
# 1st order model (Erdos-Renyi)
###################################################################################################
def extract_1st_order(_nodes, edges, src_node_ids, tgt_node_ids, min_count_per_bin=10, **_):
"""Extracts the average connection probability (1st order) from a sample of pairs of neurons.
Args:
_nodes (list): Two-element list containing source and target neuron populations of type bluepysnap.nodes.Nodes - Not used
edges (bluepysnap.edges.Edges): SONATA egdes population to extract connection probabilities from
src_node_ids (list-like): List of source (pre-synaptic) neuron IDs
tgt_node_ids (list-like): List of target (post-synaptic) neuron IDs
min_count_per_bin (int): Minimum number of samples; otherwise, no estimate will be made
Returns:
dict: Dictionary containing the extracted 1st-order connection probability data
"""
p_conn, conn_count, _ = extract_dependent_p_conn(
src_node_ids, tgt_node_ids, edges, [], [], min_count_per_bin
)
src_cell_count = len(src_node_ids)
tgt_cell_count = len(tgt_node_ids)
log.info(
f"Found {conn_count} connections between {src_cell_count}x{tgt_cell_count} neurons (p = {p_conn:.3f})"
)
return {"p_conn": p_conn, "src_cell_count": src_cell_count, "tgt_cell_count": tgt_cell_count}
def build_1st_order(p_conn, **_):
"""Builds a stochastic 1st order connection probability model (Erdos-Renyi).
Args:
p_conn (float): Constant connection probability, as returned by :func:`extract_1st_order`
Returns:
connectome_manipulator.model_building.model_types.ConnProb1stOrderModel: Resulting stochastic 1st order connectivity model
"""
# Create model
model = model_types.ConnProb1stOrderModel(p_conn=float(p_conn))
log.debug("Model description:\n%s", model)
return model
def plot_1st_order(out_dir, p_conn, src_cell_count, tgt_cell_count, model, **_): # pragma: no cover
"""Visualizes 1st order extracted data vs. actual model output.
Args:
out_dir (str): Path to output directory where the results figures will be stored
p_conn (float): Constant connection probability, as returned by :func:`extract_1st_order`
src_cell_count (int): Number of source (pre-synaptic) neurons, as returned by :func:`extract_1st_order`
tgt_cell_count (int): Number or target (post-synaptic) neurons, as returned by :func:`extract_1st_order`
model (connectome_manipulator.model_building.model_types.ConnProb1stOrderModel): Fitted stochastic 1st order connectivity model, as returned by :func:`build_1st_order`
"""
model_params = model.get_param_dict()
model_str = f'f(x) = {model_params["p_conn"]:.3f}'
# Draw figure
plt.figure(figsize=(6, 4), dpi=300)
plt.bar(
0.5,
p_conn,
width=1,
facecolor="tab:blue",
label=f"Data: N = {src_cell_count}x{tgt_cell_count} cells",
)
plt.plot(
[-0.5, 1.5],
np.ones(2) * model.get_conn_prob(),
"--",
color="tab:red",
label=f"Model: {model_str}",
)
plt.text(0.5, 0.99 * p_conn, f"p = {p_conn:.3f}", color="k", ha="center", va="top")
plt.xticks([])
plt.ylabel("Conn. prob.")
plt.title("Average conn. prob. (1st-order)", fontweight="bold")
plt.legend(loc="upper left", bbox_to_anchor=(1.1, 1.0))
plt.tight_layout()
out_fn = os.path.abspath(os.path.join(out_dir, "data_vs_model.png"))
log.info(f"Saving {out_fn}...")
plt.savefig(out_fn)
###################################################################################################
# Generative models for circuit connectivity from [Gal et al. 2020]:
# 2nd order (distance-dependent) => Position mapping model (flatmap) supported
###################################################################################################
def extract_2nd_order(
nodes,
edges,
src_node_ids,
tgt_node_ids,
bin_size_um=100,
max_range_um=None,
pos_map_file=None,
min_count_per_bin=10,
**_,
):
"""Extracts the binned, distance-dependent connection probabilities (2nd order) from a sample of pairs of neurons.
Args:
nodes (list): Two-element list containing source and target neuron populations of type bluepysnap.nodes.Nodes
edges (bluepysnap.edges.Edges): SONATA egdes population to extract connection probabilities from
src_node_ids (list-like): List of source (pre-synaptic) neuron IDs
tgt_node_ids (list-like): List of target (post-synaptic) neuron IDs
bin_size_um (float): Distance bin size in um
max_range_um (float): Maximum distance range in um
pos_map_file (str/list-like): Optional position mapping file pointing to a position mapping model (.json) or voxel data map (.nrrd); one or two files for source/target node populations may be provided
min_count_per_bin (int): Minimum number of samples per bin; otherwise, no estimate will be made for a given bin
Returns:
dict: Dictionary containing the extracted 2nd-order connection probability data
"""
# Get source/target neuron positions (optionally: two types of mappings)
pos_acc, vox_map = get_pos_mapping_fcts(pos_map_file)
src_nrn_pos, tgt_nrn_pos = get_neuron_positions(
nodes, [src_node_ids, tgt_node_ids], pos_acc, vox_map
)
# Compute distance matrix
dist_mat = model_types.ConnProb2ndOrderExpModel.compute_dist_matrix(src_nrn_pos, tgt_nrn_pos)
# Extract distance-dependent connection probabilities
if max_range_um is None:
max_range_um = np.nanmax(dist_mat)
log.log_assert(
max_range_um > 0 and bin_size_um > 0,
"ERROR: Max. range and bin size must be larger than 0um!",
)
num_bins = np.ceil(max_range_um / bin_size_um).astype(int)
dist_bins = np.arange(0, num_bins + 1) * bin_size_um
p_conn_dist, count_conn, count_all = extract_dependent_p_conn(
src_node_ids, tgt_node_ids, edges, [dist_mat], [dist_bins], min_count_per_bin
)
return {
"p_conn_dist": p_conn_dist,
"count_conn": count_conn,
"count_all": count_all,
"dist_bins": dist_bins,
"src_cell_count": len(src_node_ids),
"tgt_cell_count": len(tgt_node_ids),
}
def build_2nd_order(
p_conn_dist, dist_bins, count_all, model_specs=None, rel_fit_err_th=None, strict_fit=False, **_
):
"""Builds a stochastic 2nd order connection probability model (exponential distance-dependent).
Args:
p_conn_dist (numpy.ndarray): Binned connection probabilities, as retuned by :func:`extract_2nd_order`
dist_bins (numpy.ndarray): Distance bin edges, as returned by :func:`extract_2nd_order`
count_all (numpy.ndarray): Count of all pairs of neurons (i.e., all possible connections) in each bin, as retuned by :func:`extract_2nd_order`
model_specs (dict): Model specifications; see Notes
rel_fit_err_th (float): Threshold for rel. standard error of the coefficients; exceeding the threshold will return an invalid model
strict_fit (bool): Flag to enforce strict model fitting, which means that first data bin must contain valid data (otherwise, there is a risk of a bad extrapolation at low distances)
Returns:
connectome_manipulator.model_building.model_types.ConnProb2ndOrder[Complex]ExpModel: Resulting stochastic 2nd order connectivity model
Note:
Info on possible keys contained in `model_specs` dict:
* type (str): Type of the fitted model; either "SimpleExponential" (2 parameters) or "ComplexExponential" (5 parameters)
* p0 (list-like): Initial guess for parameter fit, as used in :func:`scipy.optimize.curve_fit`
* bounds (list-like): Lower and upper bounds on parameters, as used in :func:`scipy.optimize.curve_fit`
"""
if model_specs is None:
model_specs = {"type": "SimpleExponential"}
bin_offset = 0.5 * np.diff(dist_bins[:2])[0]
X = dist_bins[:-1][np.isfinite(p_conn_dist)] + bin_offset
y = p_conn_dist[np.isfinite(p_conn_dist)]
if model_specs.get("type") == "SimpleExponential": # Exponential curve fit with 2 parameters
# Fit simple model
def exp_model(x, a, b):
return a * np.exp(-b * np.array(x))
if np.sum(y) == 0.0: # Special case: No connections at all, skipping model fit
a_opt = b_opt = 0.0
else:
p0 = model_specs.get("p0", [0.0, 0.0])
bounds = model_specs.get("bounds", [0.0, np.inf])
invalid_model = False
try:
(a_opt, b_opt), pcov, *_ = curve_fit(exp_model, X, y, p0=p0, bounds=bounds)
except (
ValueError,
RuntimeError,
) as e: # Raised if input data invalid or optimization fails
log.error(e)
invalid_model = True
if not invalid_model and not 0.0 <= a_opt <= 1.0:
log.error('"Scale" must be between 0 and 1!')
invalid_model = True
if not invalid_model:
rel_err = np.sqrt(np.diag(pcov)) / np.array(
[a_opt, b_opt]
) # Rel. standard error of the coefficients
log.debug(f"Rel. error of simple 2nd-order model fit: {rel_err}")
if rel_fit_err_th is not None and (
not all(np.isfinite(rel_err)) or max(rel_err) > rel_fit_err_th
):
log.error(
f"Rel. error of model fit exceeds error threshold of {rel_fit_err_th} (or could not be determined)!"
)
invalid_model = True
if not invalid_model and strict_fit:
if not np.isfinite(p_conn_dist[0]):
# Strict fit: Must contain data in the first bin (otherwise, resulting in potentially bad extrapolation at low distances)
log.error("Strict fit violation: Lowest-distance bin empty!")
invalid_model = True
if invalid_model:
a_opt = b_opt = np.nan
# Create simple model
model = model_types.ConnProb2ndOrderExpModel(scale=float(a_opt), exponent=float(b_opt))
elif (
model_specs.get("type") == "ComplexExponential"
): # Complex (dual) exponential curve fit with 5 parameters [capturing deflection towards distance zero and slowly decaying offset at large distances]
# Fit complex model
def exp_model(x, a, b, c, d, e):
return a * np.exp(-b * np.array(x) ** c) + d * np.exp(-e * np.array(x))
if np.sum(y) == 0.0: # Special case: No connections at all, skipping model fit
a_opt = b_opt = c_opt = d_opt = e_opt = 0.0
else:
p0 = model_specs.get("p0", [0.0, 0.0, 1.0, 0.0, 0.0])
bounds = model_specs.get(
"bounds", [[0.0, 0.0, 1.0, 0.0, 0.0], [np.inf, np.inf, 2.0, np.inf, np.inf]]
)
invalid_model = False
try:
(a_opt, b_opt, c_opt, d_opt, e_opt), pcov, *_ = curve_fit(
exp_model, X, y, p0=p0, bounds=bounds
)
except (
ValueError,
RuntimeError,
) as e: # Raised if input data invalid or optimization fails
log.error(e)
invalid_model = True
if not invalid_model and not 0.0 <= a_opt <= 1.0:
log.error('Proximal "scale" must be between 0 and 1!')
invalid_model = True
if not invalid_model and not 0.0 <= d_opt <= 1.0:
log.error('Distal "scale" must be between 0 and 1!')
invalid_model = True
if not invalid_model:
rel_err = np.sqrt(np.diag(pcov)) / np.array(
[a_opt, b_opt, c_opt, d_opt, e_opt]
) # Rel. standard error of the coefficients
log.debug(f"Rel. error of complex 2nd-order model fit: {rel_err}")
if rel_fit_err_th is not None and (
not all(np.isfinite(rel_err)) or max(rel_err) > rel_fit_err_th
):
log.error(
f"Rel. error of model fit exceeds error threshold of {rel_fit_err_th} (or could not be determined)!"
)
invalid_model = True
if not invalid_model and strict_fit:
if not np.isfinite(p_conn_dist[0]):
# Strict fit: Must contain data in the first bin (otherwise, resulting in potentially bad extrapolation at low distances)
log.error("Strict fit violation: Lowest-distance bin empty!")
invalid_model = True
if invalid_model:
a_opt = b_opt = c_opt = d_opt = e_opt = np.nan
# Create complex model
model = model_types.ConnProb2ndOrderComplexExpModel(
prox_scale=float(a_opt),
prox_exp=float(b_opt),
prox_exp_pow=float(c_opt),
dist_scale=float(d_opt),
dist_exp=float(e_opt),
)
else:
log.log_assert(False, "ERROR: Model type not specified or unknown!")
log.debug("Model description:\n%s", model) # pylint: disable=E0606
# Check model prediction of total number of connections
conn_count_data = np.nansum(p_conn_dist * count_all).astype(int)
p_conn_model = model.get_conn_prob(distance=dist_bins[:-1] + bin_offset)
conn_count_model = np.nansum(p_conn_model * count_all).astype(int)
log.info(
f"Model prediction of total number of connections: {conn_count_model} (model) vs. {conn_count_data} (data); DIFF {conn_count_model - conn_count_data} ({100.0 * (conn_count_model - conn_count_data) / conn_count_data:.2f}%)"
)
return model
def plot_2nd_order(
out_dir,
p_conn_dist,
count_conn,
count_all,
dist_bins,
src_cell_count,
tgt_cell_count,
model,
pos_map_file=None,
**_,
): # pragma: no cover
"""Visualizes 2nd order extracted data vs. actual model output.
Args:
out_dir (str): Path to output directory where the results figures will be stored
p_conn_dist (numpy.ndarray): Binned connection probabilities, as retuned by :func:`extract_2nd_order`
count_conn (numpy.ndarray): Count of all connected pairs of neurons (i.e., all actual connections) in each bin, as retuned by :func:`extract_2nd_order`
count_all (numpy.ndarray): Count of all pairs of neurons (i.e., all possible connections) in each bin, as retuned by :func:`extract_2nd_order`
dist_bins (numpy.ndarray): Distance bin edges, as returned by :func:`extract_2nd_order`
src_cell_count (int): Number of source (pre-synaptic) neurons, as returned by :func:`extract_2nd_order`
tgt_cell_count (int): Number or target (post-synaptic) neurons, as returned by :func:`extract_2nd_order`
model (connectome_manipulator.model_building.model_types.ConnProb2ndOrder[Complex]ExpModel): Fitted stochastic 2nd order connectivity model, as returned by :func:`extract_2nd_order`
pos_map_file (str/list-like): Optional position mapping file pointing to a position mapping model (.json) or voxel data map (.nrrd); one or two files for source/target node populations may be provided
"""
bin_offset = 0.5 * np.diff(dist_bins[:2])[0]
dist_model = np.linspace(dist_bins[0], dist_bins[-1], 100)
model_str = str(model).split("\n")[1].split("=")[-1].strip()
plt.figure(figsize=(12, 4), dpi=300)
# Data vs. model
plt.subplot(1, 2, 1)
plt.plot(
dist_bins[:-1] + bin_offset,
p_conn_dist,
".-",
label=f"Data: N = {src_cell_count}x{tgt_cell_count} cells",
)
plt.plot(dist_model, model.get_conn_prob(dist_model), "--", label="Model: " + model_str)
plt.grid()
plt.xlabel("Distance [$\\mu$m]")
plt.ylabel("Conn. prob.")
plt.title("Data vs. model fit")
plt.legend(fontsize=6)
# 2D connection probability (model)
plt.subplot(1, 2, 2)
plot_range = 500 # (um)
r_markers = [200, 400] # (um)
dx = np.linspace(-plot_range, plot_range, 201)
dz = np.linspace(plot_range, -plot_range, 201)
xv, zv = np.meshgrid(dx, dz)
vdist = np.sqrt(xv**2 + zv**2)
pdist = model.get_conn_prob(vdist)
plt.imshow(
pdist,
interpolation="bilinear",
extent=(-plot_range, plot_range, -plot_range, plot_range),
cmap=HOT,
vmin=0.0,
)
for r in r_markers:
plt.gca().add_patch(plt.Circle((0, 0), r, edgecolor="w", linestyle="--", fill=False))
plt.text(0, r, f"{r} $\\mu$m", color="w", ha="center", va="bottom")
plt.xticks([])
plt.yticks([])
plt.xlabel("$\\Delta$x")
plt.ylabel("$\\Delta$z")
plt.title("2D model")
plt.colorbar(label="Conn. prob.")
plt.suptitle(
f"Distance-dependent connection probability model (2nd order)\n<Position mapping: {pos_map_file}>"
)
plt.tight_layout()
out_fn = os.path.abspath(os.path.join(out_dir, "data_vs_model.png"))
log.info(f"Saving {out_fn}...")
plt.savefig(out_fn)
# Data counts
plt.figure(figsize=(6, 4), dpi=300)
plt.bar(dist_bins[:-1] + bin_offset, count_all, width=1.5 * bin_offset, label="All pair count")
plt.bar(
dist_bins[:-1] + bin_offset, count_conn, width=1.0 * bin_offset, label="Connection count"
)
plt.gca().set_yscale("log")
plt.grid()
plt.xlabel("Distance [$\\mu$m]")
plt.ylabel("Count")
plt.title(
f"Distance-dependent connection counts (N = {src_cell_count}x{tgt_cell_count} cells)\n<Position mapping: {pos_map_file}>"
)
plt.legend()
plt.tight_layout()
out_fn = os.path.abspath(os.path.join(out_dir, "data_counts.png"))
log.info(f"Saving {out_fn}...")
plt.savefig(out_fn)
###################################################################################################
# Generative models for circuit connectivity from [Gal et al. 2020]:
# 3rd order (bipolar distance-dependent) => Position mapping model (flatmap) supported
###################################################################################################
def extract_3rd_order(
nodes,
edges,
src_node_ids,
tgt_node_ids,
bin_size_um=100,
max_range_um=None,
pos_map_file=None,
no_dist_mapping=False,
min_count_per_bin=10,
bip_coord=2,
**_,
):
"""Extracts the binned, bipolar distance-dependent connection probability (3rd order) from a sample of pairs of neurons.
Args:
nodes (list): Two-element list containing source and target neuron populations of type bluepysnap.nodes.Nodes
edges (bluepysnap.edges.Edges): SONATA egdes population to extract connection probabilities from
src_node_ids (list-like): List of source (pre-synaptic) neuron IDs
tgt_node_ids (list-like): List of target (post-synaptic) neuron IDs
bin_size_um (float): Distance bin size in um
max_range_um (float): Maximum distance range in um
pos_map_file (str/list-like): Optional position mapping file pointing to a position mapping model (.json) or voxel data map (.nrrd); one or two files for source/target node populations may be provided
no_dist_mapping (bool): Flag to disable position mapping for computing distances, i.e., position mapping will only be used to determine the bipolar coordinate if selected
min_count_per_bin (int): Minimum number of samples per bin; otherwise, no estimate will be made for a given bin
bip_coord (int): Index to select bipolar coordinate axis (0..x, 1..y, 2..z), usually perpendicular to layers
Returns:
dict: Dictionary containing the extracted 3rd-order connection probability data
"""
# Get source/target neuron positions (optionally: two types of mappings)
pos_acc, vox_map = get_pos_mapping_fcts(pos_map_file)
src_nrn_pos_raw, tgt_nrn_pos_raw = get_neuron_positions(
nodes, [src_node_ids, tgt_node_ids], None, None
)
src_nrn_pos, tgt_nrn_pos = get_neuron_positions(
nodes, [src_node_ids, tgt_node_ids], pos_acc, vox_map
)
# Compute distance matrix
if no_dist_mapping: # Don't use position mapping for computing distances
dist_mat = model_types.ConnProb3rdOrderExpModel.compute_dist_matrix(
src_nrn_pos_raw, tgt_nrn_pos_raw
)
else: # Use position mapping for computing distances
dist_mat = model_types.ConnProb3rdOrderExpModel.compute_dist_matrix(
src_nrn_pos, tgt_nrn_pos
)
# Compute bipolar matrix (always using position mapping, if provided; along z-axis (by default); post-synaptic neuron below (delta_z < 0) or above (delta_z > 0) pre-synaptic neuron)
bip_mat = model_types.ConnProb3rdOrderExpModel.compute_bip_matrix(
src_nrn_pos, tgt_nrn_pos, bip_coord
)
# Extract bipolar distance-dependent connection probabilities
if max_range_um is None:
max_range_um = np.nanmax(dist_mat)
log.log_assert(
max_range_um > 0 and bin_size_um > 0,
"ERROR: Max. range and bin size must be larger than 0um!",
)
num_dist_bins = np.ceil(max_range_um / bin_size_um).astype(int)
dist_bins = np.arange(0, num_dist_bins + 1) * bin_size_um
bip_bins = [np.min(bip_mat), 0, np.max(bip_mat)]
p_conn_dist_bip, count_conn, count_all = extract_dependent_p_conn(
src_node_ids,
tgt_node_ids,
edges,
[dist_mat, bip_mat],
[dist_bins, bip_bins],
min_count_per_bin,
)
return {
"p_conn_dist_bip": p_conn_dist_bip,
"count_conn": count_conn,
"count_all": count_all,
"dist_bins": dist_bins,
"bip_bins": bip_bins,
"bip_coord_data": bip_coord,
"src_cell_count": len(src_node_ids),
"tgt_cell_count": len(tgt_node_ids),
}
def build_3rd_order(
p_conn_dist_bip,
dist_bins,
count_all,
bip_coord_data,
model_specs=None,
rel_fit_err_th=None,
strict_fit=False,
**_,
):
"""Builds a stochastic 3rd order connection probability model (bipolar exponential distance-dependent).
Args:
p_conn_dist_bip (numpy.ndarray): Binned bipolar connection probabilities, as retuned by :func:`extract_3rd_order`
dist_bins (numpy.ndarray): Distance bin edges, as returned by :func:`extract_3rd_order`
count_all (numpy.ndarray): Count of all pairs of neurons (i.e., all possible connections) in each bin, as retuned by :func:`extract_3rd_order`
bip_coord_data (int): Index of bipolar coordinate axis, as returned by :func:`extract_3rd_order`
model_specs (dict): Model specifications; see Notes
rel_fit_err_th (float): Threshold for rel. standard error of the coefficients; exceeding the threshold will return an invalid model
strict_fit (bool): Flag to enforce strict model fitting, which means that first data bin must contain valid data (otherwise, there is a risk of a bad extrapolation at low distances)