Skip to content

Network Connections Plotting API

bmtool.bmplot.connections.is_notebook()

Detect if code is running in a Jupyter notebook environment.

Returns:

Type Description
bool

True if running in a Jupyter notebook, False otherwise.

Notes

This is used to determine whether to call plt.show() explicitly or rely on Jupyter's automatic display functionality.

Examples:

>>> if is_notebook():
...     plt.show()
Source code in bmtool/bmplot/connections.py
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
def is_notebook() -> bool:
    """
    Detect if code is running in a Jupyter notebook environment.

    Returns
    -------
    bool
        True if running in a Jupyter notebook, False otherwise.

    Notes
    -----
    This is used to determine whether to call plt.show() explicitly or
    rely on Jupyter's automatic display functionality.

    Examples
    --------
    >>> if is_notebook():
    ...     plt.show()
    """
    try:
        shell = get_ipython().__class__.__name__
        if shell == "ZMQInteractiveShell":
            return True  # Jupyter notebook or qtconsole
        elif shell == "TerminalInteractiveShell":
            return False  # Terminal running IPython
        else:
            return False  # Other type (?)
    except NameError:
        return False  # Probably standard Python interpreter

bmtool.bmplot.connections.total_connection_matrix(config, title=None, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=False, synaptic_info='0', include_gap=True)

Generate a plot displaying total connections or other synaptic statistics.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
title str

Title for the plot. If None, a default title will be used.

None
sources str

Comma-separated string of network names to use as sources.

None
targets str

Comma-separated string of network names to use as targets.

None
sids str

Comma-separated string of source node identifiers to filter.

None
tids str

Comma-separated string of target node identifiers to filter.

None
no_prepend_pop bool

If True, don't display population name before sid or tid in the plot. Default is False.

False
synaptic_info str

Type of information to display. Options: - '0': Total connections (default) - '1': Mean and standard deviation of connections - '2': All synapse .mod files used - '3': All synapse .json files used

'0'
include_gap bool

If True, include gap junctions and chemical synapses in the analysis. If False, only include chemical synapses. Default is True.

True

Returns:

Type Description
tuple of (Figure, Axes)

The matplotlib Figure and Axes objects for further customization or saving.

Raises:

Type Description
Exception

If config is not defined or sources/targets are not defined.

Examples:

>>> total_connection_matrix(
...     config='config.json',
...     sources='PN',
...     targets='LN',
...     title='PN to LN Connections'
... )
Source code in bmtool/bmplot/connections.py
 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
def total_connection_matrix(
    config: str,
    title: Optional[str] = None,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: bool = False,
    synaptic_info: str = "0",
    include_gap: bool = True,
) -> Tuple[Any, Any]:
    """
    Generate a plot displaying total connections or other synaptic statistics.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    title : str, optional
        Title for the plot. If None, a default title will be used.
    sources : str, optional
        Comma-separated string of network names to use as sources.
    targets : str, optional
        Comma-separated string of network names to use as targets.
    sids : str, optional
        Comma-separated string of source node identifiers to filter.
    tids : str, optional
        Comma-separated string of target node identifiers to filter.
    no_prepend_pop : bool, optional
        If True, don't display population name before sid or tid in the plot. Default is False.
    synaptic_info : str, optional
        Type of information to display. Options:
        - '0': Total connections (default)
        - '1': Mean and standard deviation of connections
        - '2': All synapse .mod files used
        - '3': All synapse .json files used
    include_gap : bool, optional
        If True, include gap junctions and chemical synapses in the analysis.
        If False, only include chemical synapses. Default is True.

    Returns
    -------
    tuple of (Figure, Axes)
        The matplotlib Figure and Axes objects for further customization or saving.

    Raises
    ------
    Exception
        If config is not defined or sources/targets are not defined.

    Examples
    --------
    >>> total_connection_matrix(
    ...     config='config.json',
    ...     sources='PN',
    ...     targets='LN',
    ...     title='PN to LN Connections'
    ... )
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    sources = sources.split(",")
    targets = targets.split(",")
    if sids:
        sids = sids.split(",")
    else:
        sids = []
    if tids:
        tids = tids.split(",")
    else:
        tids = []
    text, num, source_labels, target_labels = util.connection_totals(
        config=config,
        nodes=None,
        edges=None,
        sources=sources,
        targets=targets,
        sids=sids,
        tids=tids,
        prepend_pop=not no_prepend_pop,
        synaptic_info=synaptic_info,
        include_gap=include_gap,
    )

    if title is None or title == "":
        title = "Total Connections"
    if synaptic_info == "1":
        title = "Mean and Stdev # of Conn on Target"
    if synaptic_info == "2":
        title = "All Synapse .mod Files Used"
    if synaptic_info == "3":
        title = "All Synapse .json Files Used"

    return plot_connection_info(
        text, num, source_labels, target_labels, title, syn_info=synaptic_info
    )

bmtool.bmplot.connections.percent_connection_matrix(config, nodes=None, edges=None, title=None, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=False, method='total', include_gap=True, return_dict=False)

Generates a plot showing the percent connectivity of a network.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
nodes DataFrame

Pre-loaded node data. If None, will be loaded from config.

None
edges DataFrame

Pre-loaded edge data. If None, will be loaded from config.

None
title str

Title for the plot. If None, a default title will be used.

None
sources str

Comma-separated string of network name(s) to plot.

None
targets str

Comma-separated string of network name(s) to plot.

None
sids str

Comma-separated string of source node identifier(s) to filter.

None
tids str

Comma-separated string of target node identifier(s) to filter.

None
no_prepend_pop bool

If True, population name is not displayed before sid or tid in the plot. Default is False.

False
method str

Method for calculating percent connectivity. Options: 'total', 'uni', 'bi'. Default is 'total'.

'total'
include_gap bool

If True, include gap junctions in analysis. If False, only include chemical synapses. Default is True.

True
return_dict bool

If True, return connection information as a dictionary. Default is False.

False

Returns:

Type Description
Union[Tuple[Figure, Axes], Dict]

If return_dict=True, returns a dictionary of connection information. Otherwise, returns a tuple of (Figure, Axes) for further customization or saving.

Raises:

Type Description
Exception

If config is not defined or sources/targets are not defined.

Examples:

>>> result = percent_connection_matrix(
...     config='config.json',
...     sources='PN',
...     targets='LN',
...     return_dict=True
... )
Source code in bmtool/bmplot/connections.py
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
def percent_connection_matrix(
    config: str,
    nodes: Optional[pd.DataFrame] = None,
    edges: Optional[pd.DataFrame] = None,
    title: Optional[str] = None,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: bool = False,
    method: str = "total",
    include_gap: bool = True,
    return_dict: bool = False,
) -> Union[Tuple[Any, Any], Dict]:
    """
    Generates a plot showing the percent connectivity of a network.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    nodes : pd.DataFrame, optional
        Pre-loaded node data. If None, will be loaded from config.
    edges : pd.DataFrame, optional
        Pre-loaded edge data. If None, will be loaded from config.
    title : str, optional
        Title for the plot. If None, a default title will be used.
    sources : str, optional
        Comma-separated string of network name(s) to plot.
    targets : str, optional
        Comma-separated string of network name(s) to plot.
    sids : str, optional
        Comma-separated string of source node identifier(s) to filter.
    tids : str, optional
        Comma-separated string of target node identifier(s) to filter.
    no_prepend_pop : bool, optional
        If True, population name is not displayed before sid or tid in the plot. Default is False.
    method : str, optional
        Method for calculating percent connectivity. Options: 'total', 'uni', 'bi'.
        Default is 'total'.
    include_gap : bool, optional
        If True, include gap junctions in analysis. If False, only include chemical synapses.
        Default is True.
    return_dict : bool, optional
        If True, return connection information as a dictionary. Default is False.

    Returns
    -------
    Union[Tuple[Figure, Axes], Dict]
        If return_dict=True, returns a dictionary of connection information.
        Otherwise, returns a tuple of (Figure, Axes) for further customization or saving.

    Raises
    ------
    Exception
        If config is not defined or sources/targets are not defined.

    Examples
    --------
    >>> result = percent_connection_matrix(
    ...     config='config.json',
    ...     sources='PN',
    ...     targets='LN',
    ...     return_dict=True
    ... )
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")

    sources = sources.split(",")
    targets = targets.split(",")
    if sids:
        sids = sids.split(",")
    else:
        sids = []
    if tids:
        tids = tids.split(",")
    else:
        tids = []
    text, num, source_labels, target_labels = util.percent_connections(
        config=config,
        nodes=None,
        edges=None,
        sources=sources,
        targets=targets,
        sids=sids,
        tids=tids,
        prepend_pop=not no_prepend_pop,
        method=method,
        include_gap=include_gap,
    )
    if title is None or title == "":
        title = "Percent Connectivity"

    if return_dict:
        result_dict = plot_connection_info(
            text, num, source_labels, target_labels, title, return_dict=return_dict
        )
        return result_dict
    else:
        return plot_connection_info(text, num, source_labels, target_labels, title)

bmtool.bmplot.connections.probability_connection_matrix(config, nodes=None, edges=None, title=None, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=False, dist_X=True, dist_Y=True, dist_Z=True, bins=8, line_plot=False, verbose=False, include_gap=True)

Generates probability graphs showing connectivity as a function of distance.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
nodes DataFrame

Pre-loaded node data. If None, will be loaded from config.

None
edges DataFrame

Pre-loaded edge data. If None, will be loaded from config.

None
title str

Title for the plot. If None, a default title will be used.

None
sources str

Comma-separated string of network name(s) to plot.

None
targets str

Comma-separated string of network name(s) to plot.

None
sids str

Comma-separated string of source node identifier(s) to filter.

None
tids str

Comma-separated string of target node identifier(s) to filter.

None
no_prepend_pop bool

If True, population name is not displayed before sid or tid. Default is False.

False
save_file str

Path to save the plot. If None, plot is not saved.

required
dist_X bool

If True, include X distance in calculations. Default is True.

True
dist_Y bool

If True, include Y distance in calculations. Default is True.

True
dist_Z bool

If True, include Z distance in calculations. Default is True.

True
bins int

Number of distance bins for the probability calculation. Default is 8.

8
line_plot bool

If True, plot lines instead of bars. Default is False.

False
verbose bool

If True, print debugging information. Default is False.

False
include_gap bool

If True, include gap junctions in analysis. Default is True.

True

Returns:

Type Description
None

Raises:

Type Description
Exception

If config is not defined or sources/targets are not defined.

Notes

This function needs model_template to be defined to work properly.

Source code in bmtool/bmplot/connections.py
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
def probability_connection_matrix(
    config: str,
    nodes: Optional[pd.DataFrame] = None,
    edges: Optional[pd.DataFrame] = None,
    title: Optional[str] = None,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: bool = False,
    dist_X: bool = True,
    dist_Y: bool = True,
    dist_Z: bool = True,
    bins: int = 8,
    line_plot: bool = False,
    verbose: bool = False,
    include_gap: bool = True,
) -> Tuple[Any, Any]:
    """
    Generates probability graphs showing connectivity as a function of distance.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    nodes : pd.DataFrame, optional
        Pre-loaded node data. If None, will be loaded from config.
    edges : pd.DataFrame, optional
        Pre-loaded edge data. If None, will be loaded from config.
    title : str, optional
        Title for the plot. If None, a default title will be used.
    sources : str, optional
        Comma-separated string of network name(s) to plot.
    targets : str, optional
        Comma-separated string of network name(s) to plot.
    sids : str, optional
        Comma-separated string of source node identifier(s) to filter.
    tids : str, optional
        Comma-separated string of target node identifier(s) to filter.
    no_prepend_pop : bool, optional
        If True, population name is not displayed before sid or tid. Default is False.
    save_file : str, optional
        Path to save the plot. If None, plot is not saved.
    dist_X : bool, optional
        If True, include X distance in calculations. Default is True.
    dist_Y : bool, optional
        If True, include Y distance in calculations. Default is True.
    dist_Z : bool, optional
        If True, include Z distance in calculations. Default is True.
    bins : int, optional
        Number of distance bins for the probability calculation. Default is 8.
    line_plot : bool, optional
        If True, plot lines instead of bars. Default is False.
    verbose : bool, optional
        If True, print debugging information. Default is False.
    include_gap : bool, optional
        If True, include gap junctions in analysis. Default is True.

    Returns
    -------
    None

    Raises
    ------
    Exception
        If config is not defined or sources/targets are not defined.

    Notes
    -----
    This function needs model_template to be defined to work properly.
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    sources = sources.split(",")
    targets = targets.split(",")
    if sids:
        sids = sids.split(",")
    else:
        sids = []
    if tids:
        tids = tids.split(",")
    else:
        tids = []

    throwaway, data, source_labels, target_labels = util.connection_probabilities(
        config=config,
        nodes=None,
        edges=None,
        sources=sources,
        targets=targets,
        sids=sids,
        tids=tids,
        prepend_pop=not no_prepend_pop,
        dist_X=dist_X,
        dist_Y=dist_Y,
        dist_Z=dist_Z,
        num_bins=bins,
        include_gap=include_gap,
    )
    if not data.any():
        return
    if data[0][0] == -1:
        return
    # plot_connection_info(data,source_labels,target_labels,title, save_file=save_file)

    # plt.clf()# clears previous plots
    np.seterr(divide="ignore", invalid="ignore")
    num_src, num_tar = data.shape
    fig, axes = plt.subplots(nrows=num_src, ncols=num_tar, figsize=(12, 12))
    fig.subplots_adjust(hspace=0.5, wspace=0.5)

    for x in range(num_src):
        for y in range(num_tar):
            ns = data[x][y]["ns"]
            bins_data = data[x][y]["bins"]

            XX = bins_data[:-1]
            YY = ns[0] / ns[1]

            if line_plot:
                axes[x, y].plot(XX, YY)
            else:
                axes[x, y].bar(XX, YY)

            if x == num_src - 1:
                axes[x, y].set_xlabel(target_labels[y])
            if y == 0:
                axes[x, y].set_ylabel(source_labels[x])

            if verbose:
                print("Source: [" + source_labels[x] + "] | Target: [" + target_labels[y] + "]")
                print("X:")
                print(XX)
                print("Y:")
                print(YY)

    tt = "Distance Probability Matrix"
    if title:
        tt = title
    st = fig.suptitle(tt, fontsize=14)
    fig.text(0.5, 0.04, "Target", ha="center")
    fig.text(0.04, 0.5, "Source", va="center", rotation="vertical")

    return fig, axes

bmtool.bmplot.connections.convergence_connection_matrix(config, title=None, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=False, convergence=True, method='mean+std', include_gap=True, return_dict=None)

Generates connection plot displaying synaptic convergence data.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
title str

Title for the plot. If None, a default title will be used.

None
sources str

Comma-separated string of network name(s) to plot.

None
targets str

Comma-separated string of network name(s) to plot.

None
sids str

Comma-separated string of source node identifier(s) to filter.

None
tids str

Comma-separated string of target node identifier(s) to filter.

None
no_prepend_pop bool

If True, population name is not displayed before sid or tid. Default is False.

False
save_file str

Path to save the plot. If None, plot is not saved.

required
convergence bool

If True, compute convergence; if False, compute divergence. Default is True.

True
method str

Statistical method for display. Options: 'mean', 'min', 'max', 'stdev', 'mean+std'. Default is 'mean+std'.

'mean+std'
include_gap bool

If True, include gap junctions in analysis. Default is True.

True
return_dict bool

If True, return connection information as a dictionary. Default is None.

None

Returns:

Type Description
Union[Tuple[Figure, Axes], Dict, None]

If return_dict=True, returns a dictionary of connection information. Otherwise, returns a tuple of (Figure, Axes) for further customization or saving.

Raises:

Type Description
Exception

If config is not defined or sources/targets are not defined.

Examples:

>>> result = convergence_connection_matrix(
...     config='config.json',
...     sources='PN',
...     targets='LN',
...     method='mean+std'
... )
Source code in bmtool/bmplot/connections.py
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
def convergence_connection_matrix(
    config: str,
    title: Optional[str] = None,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: bool = False,
    convergence: bool = True,
    method: str = "mean+std",
    include_gap: bool = True,
    return_dict: Optional[bool] = None,
) -> Union[Tuple[Any, Any], Dict, None]:
    """
    Generates connection plot displaying synaptic convergence data.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    title : str, optional
        Title for the plot. If None, a default title will be used.
    sources : str, optional
        Comma-separated string of network name(s) to plot.
    targets : str, optional
        Comma-separated string of network name(s) to plot.
    sids : str, optional
        Comma-separated string of source node identifier(s) to filter.
    tids : str, optional
        Comma-separated string of target node identifier(s) to filter.
    no_prepend_pop : bool, optional
        If True, population name is not displayed before sid or tid. Default is False.
    save_file : str, optional
        Path to save the plot. If None, plot is not saved.
    convergence : bool, optional
        If True, compute convergence; if False, compute divergence. Default is True.
    method : str, optional
        Statistical method for display. Options: 'mean', 'min', 'max', 'stdev', 'mean+std'.
        Default is 'mean+std'.
    include_gap : bool, optional
        If True, include gap junctions in analysis. Default is True.
    return_dict : bool, optional
        If True, return connection information as a dictionary. Default is None.

    Returns
    -------
    Union[Tuple[Figure, Axes], Dict, None]
        If return_dict=True, returns a dictionary of connection information.
        Otherwise, returns a tuple of (Figure, Axes) for further customization or saving.

    Raises
    ------
    Exception
        If config is not defined or sources/targets are not defined.

    Examples
    --------
    >>> result = convergence_connection_matrix(
    ...     config='config.json',
    ...     sources='PN',
    ...     targets='LN',
    ...     method='mean+std'
    ... )
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    return divergence_connection_matrix(
        config,
        title,
        sources,
        targets,
        sids,
        tids,
        no_prepend_pop,
        convergence,
        method,
        include_gap=include_gap,
        return_dict=return_dict,
    )

bmtool.bmplot.connections.divergence_connection_matrix(config, title=None, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=False, convergence=False, method='mean+std', include_gap=True, return_dict=None)

Generates connection plot displaying synaptic divergence data.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
title str

Title for the plot. If None, a default title will be used.

None
sources str

Comma-separated string of network name(s) to plot.

None
targets str

Comma-separated string of network name(s) to plot.

None
sids str

Comma-separated string of source node identifier(s) to filter.

None
tids str

Comma-separated string of target node identifier(s) to filter.

None
no_prepend_pop bool

If True, population name is not displayed before sid or tid. Default is False.

False
save_file str

Path to save the plot. If None, plot is not saved.

required
convergence bool

If True, compute convergence; if False, compute divergence. Default is False.

False
method str

Statistical method for display. Options: 'mean', 'min', 'max', 'stdev', 'mean+std'. Default is 'mean+std'.

'mean+std'
include_gap bool

If True, include gap junctions in analysis. Default is True.

True
return_dict bool

If True, return connection information as a dictionary. Default is None.

None

Returns:

Type Description
Union[Tuple[Figure, Axes], Dict, None]

If return_dict=True, returns a dictionary of connection information. Otherwise, returns a tuple of (Figure, Axes) for further customization or saving.

Raises:

Type Description
Exception

If config is not defined or sources/targets are not defined.

Examples:

>>> result = divergence_connection_matrix(
...     config='config.json',
...     sources='PN',
...     targets='LN',
...     method='mean+std'
... )
Source code in bmtool/bmplot/connections.py
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
def divergence_connection_matrix(
    config: str,
    title: Optional[str] = None,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: bool = False,
    convergence: bool = False,
    method: str = "mean+std",
    include_gap: bool = True,
    return_dict: Optional[bool] = None,
) -> Union[Tuple[Any, Any], Dict, None]:
    """
    Generates connection plot displaying synaptic divergence data.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    title : str, optional
        Title for the plot. If None, a default title will be used.
    sources : str, optional
        Comma-separated string of network name(s) to plot.
    targets : str, optional
        Comma-separated string of network name(s) to plot.
    sids : str, optional
        Comma-separated string of source node identifier(s) to filter.
    tids : str, optional
        Comma-separated string of target node identifier(s) to filter.
    no_prepend_pop : bool, optional
        If True, population name is not displayed before sid or tid. Default is False.
    save_file : str, optional
        Path to save the plot. If None, plot is not saved.
    convergence : bool, optional
        If True, compute convergence; if False, compute divergence. Default is False.
    method : str, optional
        Statistical method for display. Options: 'mean', 'min', 'max', 'stdev', 'mean+std'.
        Default is 'mean+std'.
    include_gap : bool, optional
        If True, include gap junctions in analysis. Default is True.
    return_dict : bool, optional
        If True, return connection information as a dictionary. Default is None.

    Returns
    -------
    Union[Tuple[Figure, Axes], Dict, None]
        If return_dict=True, returns a dictionary of connection information.
        Otherwise, returns a tuple of (Figure, Axes) for further customization or saving.

    Raises
    ------
    Exception
        If config is not defined or sources/targets are not defined.

    Examples
    --------
    >>> result = divergence_connection_matrix(
    ...     config='config.json',
    ...     sources='PN',
    ...     targets='LN',
    ...     method='mean+std'
    ... )
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    sources = sources.split(",")
    targets = targets.split(",")
    if sids:
        sids = sids.split(",")
    else:
        sids = []
    if tids:
        tids = tids.split(",")
    else:
        tids = []

    syn_info, data, source_labels, target_labels = util.connection_divergence(
        config=config,
        nodes=None,
        edges=None,
        sources=sources,
        targets=targets,
        sids=sids,
        tids=tids,
        prepend_pop=not no_prepend_pop,
        convergence=convergence,
        method=method,
        include_gap=include_gap,
    )

    # data, labels = util.connection_divergence_average(config=config,nodes=nodes,edges=edges,populations=populations)

    if title is None or title == "":
        if method == "min":
            title = "Minimum "
        elif method == "max":
            title = "Maximum "
        elif method == "std":
            title = "Standard Deviation "
        elif method == "mean":
            title = "Mean "
        else:
            title = "Mean + Std "

        if convergence:
            title = title + "Synaptic Convergence"
        else:
            title = title + "Synaptic Divergence"
    if return_dict:
        result_dict = plot_connection_info(
            syn_info,
            data,
            source_labels,
            target_labels,
            title,
            return_dict=return_dict,
        )
        return result_dict
    else:
        return plot_connection_info(
            syn_info, data, source_labels, target_labels, title
        )

bmtool.bmplot.connections.gap_junction_matrix(config, title=None, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=False, method='convergence')

Generates connection plot displaying gap junction data.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
title str

Title for the plot. If None, a default title will be used.

None
sources str

Comma-separated string of network name(s) to plot.

None
targets str

Comma-separated string of network name(s) to plot.

None
sids str

Comma-separated string of source node identifier(s) to filter.

None
tids str

Comma-separated string of target node identifier(s) to filter.

None
no_prepend_pop bool

If True, population name is not displayed before sid or tid. Default is False.

False
save_file str

Path to save the plot. If None, plot is not saved.

required
method str

Method for computing gap junction statistics. Options: 'convergence', 'percent'. Default is 'convergence'.

'convergence'

Returns:

Type Description
None

Raises:

Type Description
Exception

If config is not defined, sources/targets are not defined, or method is invalid.

Examples:

>>> gap_junction_matrix(
...     config='config.json',
...     sources='PN',
...     targets='LN',
...     method='convergence'
... )
Source code in bmtool/bmplot/connections.py
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
def gap_junction_matrix(
    config: str,
    title: Optional[str] = None,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: bool = False,
    method: str = "convergence",
) -> Tuple[Any, Any]:
    """
    Generates connection plot displaying gap junction data.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    title : str, optional
        Title for the plot. If None, a default title will be used.
    sources : str, optional
        Comma-separated string of network name(s) to plot.
    targets : str, optional
        Comma-separated string of network name(s) to plot.
    sids : str, optional
        Comma-separated string of source node identifier(s) to filter.
    tids : str, optional
        Comma-separated string of target node identifier(s) to filter.
    no_prepend_pop : bool, optional
        If True, population name is not displayed before sid or tid. Default is False.
    save_file : str, optional
        Path to save the plot. If None, plot is not saved.
    method : str, optional
        Method for computing gap junction statistics. Options: 'convergence', 'percent'.
        Default is 'convergence'.

    Returns
    -------
    None

    Raises
    ------
    Exception
        If config is not defined, sources/targets are not defined, or method is invalid.

    Examples
    --------
    >>> gap_junction_matrix(
    ...     config='config.json',
    ...     sources='PN',
    ...     targets='LN',
    ...     method='convergence'
    ... )
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    if method != "convergence" and method != "percent":
        raise Exception("type must be 'convergence' or 'percent'")
    sources = sources.split(",")
    targets = targets.split(",")
    if sids:
        sids = sids.split(",")
    else:
        sids = []
    if tids:
        tids = tids.split(",")
    else:
        tids = []
    syn_info, data, source_labels, target_labels = util.gap_junction_connections(
        config=config,
        nodes=None,
        edges=None,
        sources=sources,
        targets=targets,
        sids=sids,
        tids=tids,
        prepend_pop=not no_prepend_pop,
        method=method,
    )

    def filter_rows(
        syn_info: np.ndarray,
        data: np.ndarray,
        source_labels: List,
        target_labels: List,
    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, List]:
        """
        Filters out rows in a connectivity matrix that contain only NaN or zero values.

        This function is used to clean up connection matrices by removing rows that have
        no meaningful data, which helps create more informative visualizations of network connectivity.

        Parameters
        ----------
        syn_info : np.ndarray
            Array containing synaptic information corresponding to the data matrix.
        data : np.ndarray
            2D matrix containing connectivity data with rows representing sources
            and columns representing targets.
        source_labels : list
            List of labels for the source populations corresponding to rows in the data matrix.
        target_labels : list
            List of labels for the target populations corresponding to columns in the data matrix.

        Returns
        -------
        tuple
            A tuple containing (syn_info, data, source_labels, target_labels) with invalid rows removed.
        """
        # Identify rows with all NaN or all zeros
        valid_rows = ~np.all(np.isnan(data), axis=1) & ~np.all(data == 0, axis=1)

        # Filter rows based on valid_rows mask
        new_syn_info = syn_info[valid_rows]
        new_data = data[valid_rows]
        new_source_labels = np.array(source_labels)[valid_rows]

        return new_syn_info, new_data, new_source_labels, target_labels

    def filter_rows_and_columns(
        syn_info: np.ndarray,
        data: np.ndarray,
        source_labels: List,
        target_labels: List,
    ) -> Tuple[np.ndarray, np.ndarray, List, List]:
        """
        Filters out both rows and columns in a connectivity matrix that contain only NaN or zero values.

        This function performs a two-step filtering process: first removing rows with no data,
        then transposing the matrix and removing columns with no data (by treating them as rows).
        This creates a cleaner, more informative connectivity matrix visualization.

        Parameters
        ----------
        syn_info : np.ndarray
            Array containing synaptic information corresponding to the data matrix.
        data : np.ndarray
            2D matrix containing connectivity data with rows representing sources
            and columns representing targets.
        source_labels : list
            List of labels for the source populations corresponding to rows in the data matrix.
        target_labels : list
            List of labels for the target populations corresponding to columns in the data matrix.

        Returns
        -------
        tuple
            A tuple containing (syn_info, data, source_labels, target_labels) with both
            invalid rows and columns removed.
        """
        # Filter rows first
        syn_info, data, source_labels, target_labels = filter_rows(
            syn_info, data, source_labels, target_labels
        )

        # Transpose data to filter columns
        transposed_syn_info = np.transpose(syn_info)
        transposed_data = np.transpose(data)
        transposed_source_labels = target_labels
        transposed_target_labels = source_labels

        # Filter columns (by treating them as rows in transposed data)
        (
            transposed_syn_info,
            transposed_data,
            transposed_source_labels,
            transposed_target_labels,
        ) = filter_rows(
            transposed_syn_info, transposed_data, transposed_source_labels, transposed_target_labels
        )

        # Transpose back to original orientation
        filtered_syn_info = np.transpose(transposed_syn_info)
        filtered_data = np.transpose(transposed_data)
        filtered_source_labels = transposed_target_labels  # Back to original source_labels
        filtered_target_labels = transposed_source_labels  # Back to original target_labels

        return filtered_syn_info, filtered_data, filtered_source_labels, filtered_target_labels

    syn_info, data, source_labels, target_labels = filter_rows_and_columns(
        syn_info, data, source_labels, target_labels
    )

    if title is None or title == "":
        title = "Gap Junction"
        if method == "convergence":
            title += " Syn Convergence"
        elif method == "percent":
            title += " Percent Connectivity"
    return plot_connection_info(syn_info, data, source_labels, target_labels, title)

bmtool.bmplot.connections.connection_histogram(config, nodes=None, edges=None, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=True, synaptic_info='0', source_cell=None, target_cell=None, include_gap=True)

Generates histogram of the number of connections individual cells receive from another population.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
nodes DataFrame

Pre-loaded node data. If None, will be loaded from config.

None
edges DataFrame

Pre-loaded edge data. If None, will be loaded from config.

None
sources str

Comma-separated string of network name(s) to plot as sources.

None
targets str

Comma-separated string of network name(s) to plot as targets.

None
sids str

Comma-separated string of source node identifier(s) to filter by.

None
tids str

Comma-separated string of target node identifier(s) to filter by.

None
no_prepend_pop bool

If True, population name is not prepended to sid or tid. Default is True.

True
synaptic_info str

Type of synaptic information to display. Default is '0'.

'0'
source_cell str

Specific source cell type to plot connections from.

None
target_cell str

Specific target cell type to plot connections onto.

None
include_gap bool

If True, include gap junctions in analysis. Default is True.

True

Returns:

Type Description
tuple

(matplotlib.figure.Figure, matplotlib.axes.Axes) containing the histogram.

Source code in bmtool/bmplot/connections.py
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
def connection_histogram(
    config: str,
    nodes: Optional[pd.DataFrame] = None,
    edges: Optional[pd.DataFrame] = None,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: bool = True,
    synaptic_info: str = "0",
    source_cell: Optional[str] = None,
    target_cell: Optional[str] = None,
    include_gap: bool = True,
) -> Tuple[Any, Any]:
    """
    Generates histogram of the number of connections individual cells receive from another population.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    nodes : pd.DataFrame, optional
        Pre-loaded node data. If None, will be loaded from config.
    edges : pd.DataFrame, optional
        Pre-loaded edge data. If None, will be loaded from config.
    sources : str, optional
        Comma-separated string of network name(s) to plot as sources.
    targets : str, optional
        Comma-separated string of network name(s) to plot as targets.
    sids : str, optional
        Comma-separated string of source node identifier(s) to filter by.
    tids : str, optional
        Comma-separated string of target node identifier(s) to filter by.
    no_prepend_pop : bool, optional
        If True, population name is not prepended to sid or tid. Default is True.
    synaptic_info : str, optional
        Type of synaptic information to display. Default is '0'.
    source_cell : str, optional
        Specific source cell type to plot connections from.
    target_cell : str, optional
        Specific target cell type to plot connections onto.
    include_gap : bool, optional
        If True, include gap junctions in analysis. Default is True.

    Returns
    -------
    tuple
        (matplotlib.figure.Figure, matplotlib.axes.Axes) containing the histogram.
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")

    sources_list = sources.split(",") if sources else []
    targets_list = targets.split(",") if targets else []
    if sids:
        sids_list = sids.split(",")
    else:
        sids_list = []
    if tids:
        tids_list = tids.split(",")
    else:
        tids_list = []

    def connection_pair_histogram(ax=None, **kwargs: Dict) -> None:
        """
        Creates a histogram showing the distribution of connection counts between specific cell types.

        This function is designed to be used with the relation_matrix utility and will only
        create histograms for the specified source and target cell types.

        Parameters
        ----------
        ax : matplotlib.axes.Axes, optional
            The axes object on which to create the histogram. If None, uses current axes.
        kwargs : dict
            Dictionary containing edge data and filtering information.
            - edges: DataFrame containing edge information
            - sid: Column name for source ID type in the edges DataFrame
            - tid: Column name for target ID type in the edges DataFrame
            - source_id: Value to filter edges by source ID type
            - target_id: Value to filter edges by target ID type

        Returns
        -------
        None
        """
        if ax is None:
            ax = plt.gca()
        edges_data = kwargs["edges"]
        source_id_type = kwargs["sid"]
        target_id_type = kwargs["tid"]
        source_id = kwargs["source_id"]
        target_id = kwargs["target_id"]
        if source_id == source_cell and target_id == target_cell:
            temp = edges_data[
                (edges_data[source_id_type] == source_id) & (edges_data[target_id_type] == target_id)
            ]
            if not include_gap:
                gap_col = temp["is_gap_junction"].fillna(False).astype(bool)
                temp = temp[~gap_col]
            node_pairs = temp.groupby("target_node_id")["source_node_id"].count()
            try:
                conn_mean = statistics.mean(node_pairs.values)
                conn_std = statistics.stdev(node_pairs.values)
                conn_median = statistics.median(node_pairs.values)
                label = "mean {:.2f} std {:.2f} median {:.2f}".format(
                    conn_mean, conn_std, conn_median
                )
            except (statistics.StatisticsError, ValueError):  # lazy fix for std not calculated with 1 node
                conn_mean = statistics.mean(node_pairs.values)
                conn_median = statistics.median(node_pairs.values)
                label = "mean {:.2f} median {:.2f}".format(conn_mean, conn_median)
            ax.hist(node_pairs.values, density=False, bins="auto", stacked=True, label=label)
            ax.legend()
            ax.set_xlabel("# of conns from {} to {}".format(source_cell, target_cell))
            ax.set_ylabel("# of cells")
        else:  # dont care about other cell pairs so pass
            pass

    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")

    # Create figure for the histogram
    fig, ax = plt.subplots()

    # Wrapper to pass ax to the connection_pair_histogram function
    def relation_func_wrapper(**kwargs):
        return connection_pair_histogram(ax=ax, **kwargs)

    util.relation_matrix(
        config,
        nodes,
        edges,
        sources_list,
        targets_list,
        sids_list,
        tids_list,
        not no_prepend_pop,
        relation_func=relation_func_wrapper,
        synaptic_info=synaptic_info,
    )

    return fig, ax

bmtool.bmplot.connections.connection_distance(config, sources, targets, source_cell_id, target_id_type, ignore_z=False)

Plots the 3D spatial distribution of target nodes relative to a source node and a histogram of distances from the source node to each target node.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
sources str

Network name(s) to plot as sources.

required
targets str

Network name(s) to plot as targets.

required
source_cell_id int

ID of the source cell for calculating distances to target nodes.

required
target_id_type str

String to filter target nodes based off the target_query.

required
ignore_z bool

If True, ignore Z axis when calculating distance. Default is False.

False

Returns:

Type Description
tuple

Two tuples, each containing (matplotlib.figure.Figure, matplotlib.axes.Axes): - First tuple: 3D/2D scatter plot of node positions - Second tuple: Histogram of distances

Examples:

>>> (fig1, ax1), (fig2, ax2) = connection_distance(
...     config='config.json',
...     sources='PN',
...     targets='LN',
...     source_cell_id=0,
...     target_id_type='LN',
...     ignore_z=False
... )
Source code in bmtool/bmplot/connections.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def connection_distance(
    config: str,
    sources: str,
    targets: str,
    source_cell_id: int,
    target_id_type: str,
    ignore_z: bool = False,
) -> Tuple[Tuple[Any, Any], Tuple[Any, Any]]:
    """
    Plots the 3D spatial distribution of target nodes relative to a source node
    and a histogram of distances from the source node to each target node.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    sources : str
        Network name(s) to plot as sources.
    targets : str
        Network name(s) to plot as targets.
    source_cell_id : int
        ID of the source cell for calculating distances to target nodes.
    target_id_type : str
        String to filter target nodes based off the target_query.
    ignore_z : bool, optional
        If True, ignore Z axis when calculating distance. Default is False.

    Returns
    -------
    tuple
        Two tuples, each containing (matplotlib.figure.Figure, matplotlib.axes.Axes):
        - First tuple: 3D/2D scatter plot of node positions
        - Second tuple: Histogram of distances

    Examples
    --------
    >>> (fig1, ax1), (fig2, ax2) = connection_distance(
    ...     config='config.json',
    ...     sources='PN',
    ...     targets='LN',
    ...     source_cell_id=0,
    ...     target_id_type='LN',
    ...     ignore_z=False
    ... )
    """
    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    # if source != target:
    # raise Exception("Code is setup for source and target to be the same! Look at source code for function to add feature")

    # Load nodes and edges based on config file
    nodes, edges = util.load_nodes_edges_from_config(config)

    edge_network = sources + "_to_" + targets
    node_network = sources

    # Filter edges to obtain connections originating from the source node
    edge = edges[edge_network]
    edge = edge[edge["source_node_id"] == source_cell_id]
    if target_id_type:
        edge = edge[edge["target_query"].str.contains(target_id_type, na=False)]

    target_node_ids = edge["target_node_id"]

    # Filter nodes to obtain only the target and source nodes
    node = nodes[node_network]
    target_nodes = node.loc[node.index.isin(target_node_ids)]
    source_node = node.loc[node.index == source_cell_id]

    # Calculate distances between source node and each target node
    if ignore_z:
        target_positions = target_nodes[["pos_x", "pos_y"]].values
        source_position = np.array(
            [source_node["pos_x"], source_node["pos_y"]]
        ).ravel()  # Ensure 1D shape
    else:
        target_positions = target_nodes[["pos_x", "pos_y", "pos_z"]].values
        source_position = np.array(
            [source_node["pos_x"], source_node["pos_y"], source_node["pos_z"]]
        ).ravel()  # Ensure 1D shape
    distances = np.linalg.norm(target_positions - source_position, axis=1)

    # Plot positions of source and target nodes in 3D space or 2D
    if ignore_z:
        fig = plt.figure(figsize=(8, 6))
        ax = fig.add_subplot(111)
        ax.scatter(target_nodes["pos_x"], target_nodes["pos_y"], c="blue", label="target cells")
        ax.scatter(source_node["pos_x"], source_node["pos_y"], c="red", label="source cell")
    else:
        fig = plt.figure(figsize=(8, 6))
        ax = fig.add_subplot(111, projection="3d")
        ax.scatter(
            target_nodes["pos_x"],
            target_nodes["pos_y"],
            target_nodes["pos_z"],
            c="blue",
            label="target cells",
        )
        ax.scatter(
            source_node["pos_x"],
            source_node["pos_y"],
            source_node["pos_z"],
            c="red",
            label="source cell",
        )

    # Optional: Add text annotations for distances
    # for i, distance in enumerate(distances):
    #     ax.text(target_nodes['pos_x'].iloc[i], target_nodes['pos_y'].iloc[i], target_nodes['pos_z'].iloc[i],
    #             f'{distance:.2f}', color='black', fontsize=8, ha='center')

    plt.legend()

    # Plot distances in a separate 2D plot
    fig2, ax2 = plt.subplots(figsize=(8, 6))
    ax2.hist(distances, bins=20, color="blue", edgecolor="black")
    ax2.set_xlabel("Distance")
    ax2.set_ylabel("Count")
    ax2.set_title("Distance from Source Node to Each Target Node")
    ax2.grid(True)

    return (fig, ax), (fig2, ax2)

bmtool.bmplot.connections.edge_histogram_matrix(config, sources=None, targets=None, sids=None, tids=None, no_prepend_pop=None, edge_property=None, time=None, time_compare=None, report=None, title=None)

Generates a matrix of histograms showing the distribution of edge properties between populations.

This function creates a grid of histograms where each cell represents the distribution of a specific edge property between source and target populations.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

required
sources str

Comma-separated list of source network names.

None
targets str

Comma-separated list of target network names.

None
sids str

Comma-separated list of source node identifiers to filter by.

None
tids str

Comma-separated list of target node identifiers to filter by.

None
no_prepend_pop bool

If True, population names are not prepended to node identifiers.

None
edge_property str

The edge property to analyze (e.g., 'syn_weight', 'delay').

None
time int

Time point to analyze from a time series report.

None
time_compare int

Second time point for comparison with time.

None
report str

Name of the report to analyze.

None
title str

Custom title for the plot.

None
save_file str

Path to save the generated plot.

required

Returns:

Type Description
tuple

(matplotlib.figure.Figure, matplotlib.axes.Axes) containing the histogram matrix.

Examples:

>>> fig, axes = edge_histogram_matrix(
...     config='config.json',
...     sources='PN',
...     targets='LN',
...     edge_property='syn_weight'
... )
Source code in bmtool/bmplot/connections.py
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
def edge_histogram_matrix(
    config: str,
    sources: Optional[str] = None,
    targets: Optional[str] = None,
    sids: Optional[str] = None,
    tids: Optional[str] = None,
    no_prepend_pop: Optional[bool] = None,
    edge_property: Optional[str] = None,
    time: Optional[int] = None,
    time_compare: Optional[int] = None,
    report: Optional[str] = None,
    title: Optional[str] = None,

) -> Tuple[Any, Any]:
    """
    Generates a matrix of histograms showing the distribution of edge properties between populations.

    This function creates a grid of histograms where each cell represents the distribution
    of a specific edge property between source and target populations.

    Parameters
    ----------
    config : str
        Path to a BMTK simulation config file.
    sources : str, optional
        Comma-separated list of source network names.
    targets : str, optional
        Comma-separated list of target network names.
    sids : str, optional
        Comma-separated list of source node identifiers to filter by.
    tids : str, optional
        Comma-separated list of target node identifiers to filter by.
    no_prepend_pop : bool, optional
        If True, population names are not prepended to node identifiers.
    edge_property : str, optional
        The edge property to analyze (e.g., 'syn_weight', 'delay').
    time : int, optional
        Time point to analyze from a time series report.
    time_compare : int, optional
        Second time point for comparison with time.
    report : str, optional
        Name of the report to analyze.
    title : str, optional
        Custom title for the plot.
    save_file : str, optional
        Path to save the generated plot.

    Returns
    -------
    tuple
        (matplotlib.figure.Figure, matplotlib.axes.Axes) containing the histogram matrix.

    Examples
    --------
    >>> fig, axes = edge_histogram_matrix(
    ...     config='config.json',
    ...     sources='PN',
    ...     targets='LN',
    ...     edge_property='syn_weight'
    ... )
    """

    if not config:
        raise Exception("config not defined")
    if not sources or not targets:
        raise Exception("Sources or targets not defined")
    targets = targets.split(",")
    if sids:
        sids = sids.split(",")
    else:
        sids = []
    if tids:
        tids = tids.split(",")
    else:
        tids = []

    if time_compare:
        time_compare = int(time_compare)

    data, source_labels, target_labels = util.edge_property_matrix(
        edge_property,
        nodes=None,
        edges=None,
        config=config,
        sources=sources,
        targets=targets,
        sids=sids,
        tids=tids,
        prepend_pop=not no_prepend_pop,
        report=report,
        time=time,
        time_compare=time_compare,
    )

    # Fantastic resource
    # https://stackoverflow.com/questions/7941207/is-there-a-function-to-make-scatterplot-matrices-in-matplotlib
    num_src, num_tar = data.shape
    fig, axes = plt.subplots(nrows=num_src, ncols=num_tar, figsize=(12, 12))
    fig.subplots_adjust(hspace=0.5, wspace=0.5)

    for x in range(num_src):
        for y in range(num_tar):
            axes[x, y].hist(data[x][y])

            if x == num_src - 1:
                axes[x, y].set_xlabel(target_labels[y])
            if y == 0:
                axes[x, y].set_ylabel(source_labels[x])

    tt = edge_property + " Histogram Matrix"
    if title:
        tt = title
    st = fig.suptitle(tt, fontsize=14)
    fig.text(0.5, 0.04, "Target", ha="center")
    fig.text(0.04, 0.5, "Source", va="center", rotation="vertical")
    plt.draw()

    return fig, axes

bmtool.bmplot.connections.distance_delay_plot(simulation_config, source, target, group_by, sid, tid)

Plots the relationship between the distance and delay of connections between nodes in a neural network.

This function loads node and edge data from a simulation configuration file, filters nodes by population, identifies connections (edges) between source and target node populations, calculates the Euclidean distance between connected nodes, and plots the delay as a function of distance.

Parameters:

Name Type Description Default
simulation_config str

Path to the simulation config file.

required
source str

The name of the source population in the edge data.

required
target str

The name of the target population in the edge data.

required
group_by str

Column name to group nodes by (e.g., population name).

required
sid str

Identifier for the source group (e.g., 'PN').

required
tid str

Identifier for the target group (e.g., 'PN').

required

Returns:

Type Description
tuple

(matplotlib.figure.Figure, matplotlib.axes.Axes) containing the scatter plot.

Examples:

>>> fig, ax = distance_delay_plot(
...     'config.json',
...     'cortex',
...     'cortex',
...     'node_type_id',
...     'E',
...     'E'
... )
Source code in bmtool/bmplot/connections.py
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
def distance_delay_plot(
    simulation_config: str, source: str, target: str, group_by: str, sid: str, tid: str
) -> Tuple[Any, Any]:
    """
    Plots the relationship between the distance and delay of connections between nodes in a neural network.

    This function loads node and edge data from a simulation configuration file, filters nodes by population,
    identifies connections (edges) between source and target node populations, calculates the Euclidean distance
    between connected nodes, and plots the delay as a function of distance.

    Parameters
    ----------
    simulation_config : str
        Path to the simulation config file.
    source : str
        The name of the source population in the edge data.
    target : str
        The name of the target population in the edge data.
    group_by : str
        Column name to group nodes by (e.g., population name).
    sid : str
        Identifier for the source group (e.g., 'PN').
    tid : str
        Identifier for the target group (e.g., 'PN').

    Returns
    -------
    tuple
        (matplotlib.figure.Figure, matplotlib.axes.Axes) containing the scatter plot.

    Examples
    --------
    >>> fig, ax = distance_delay_plot(
    ...     'config.json',
    ...     'cortex',
    ...     'cortex',
    ...     'node_type_id',
    ...     'E',
    ...     'E'
    ... )
    """
    nodes, edges = util.load_nodes_edges_from_config(simulation_config)
    nodes = nodes[target]
    # node id is index of nodes df
    node_id_source = nodes[nodes[group_by] == sid].index
    node_id_target = nodes[nodes[group_by] == tid].index

    edges = edges[f"{source}_to_{target}"]
    edges = edges[
        edges["source_node_id"].isin(node_id_source) & edges["target_node_id"].isin(node_id_target)
    ]

    stuff_to_plot = []
    for index, row in edges.iterrows():
        try:
            source_node = row["source_node_id"]
            target_node = row["target_node_id"]

            source_pos = nodes.loc[[source_node], ["pos_x", "pos_y", "pos_z"]]
            target_pos = nodes.loc[[target_node], ["pos_x", "pos_y", "pos_z"]]

            distance = np.linalg.norm(source_pos.values - target_pos.values)

            delay = row["delay"]  # This line may raise KeyError
            stuff_to_plot.append([distance, delay])

        except KeyError as e:
            print(f"KeyError: Missing key {e} in either edge properties or node positions.")
        except IndexError as e:
            print(f"IndexError: Node ID {source_node} or {target_node} not found in nodes.")
        except Exception as e:
            print(f"Unexpected error at edge index {index}: {e}")

    fig, ax = plt.subplots()
    ax.scatter([x[0] for x in stuff_to_plot], [x[1] for x in stuff_to_plot])
    ax.set_xlabel("Distance")
    ax.set_ylabel("Delay")
    ax.set_title(f"Distance vs Delay for edge between {sid} and {tid}")

    return fig, ax

bmtool.bmplot.connections.plot_synapse_location(config, source, target, sids, tids, syn_feature='afferent_section_id')

Generates a connectivity matrix showing synaptic distribution across different cell sections.

Note: Excludes gap junctions since they don't have an afferent id stored in the h5 file.

Parameters:

Name Type Description Default
config str

Path to BMTK config file.

required
source str

The source BMTK network name.

required
target str

The target BMTK network name.

required
sids str

Column name in nodes file containing source population identifiers.

required
tids str

Column name in nodes file containing target population identifiers.

required
syn_feature str

Synaptic feature to analyze. Default is 'afferent_section_id'. Options: 'afferent_section_id' or 'afferent_section_pos'.

'afferent_section_id'

Returns:

Type Description
tuple

(matplotlib.figure.Figure, matplotlib.axes.Axes) containing the plot.

Raises:

Type Description
ValueError

If required parameters are missing or invalid.

RuntimeError

If template loading or cell instantiation fails.

Examples:

>>> fig, ax = plot_synapse_location(
...     config='config.json',
...     source='LGN',
...     target='cortex',
...     sids='node_type_id',
...     tids='node_type_id'
... )
Source code in bmtool/bmplot/connections.py
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
def plot_synapse_location(
    config: str,
    source: str,
    target: str,
    sids: str,
    tids: str,
    syn_feature: str = "afferent_section_id",
) -> Tuple[Any, Any]:
    """
    Generates a connectivity matrix showing synaptic distribution across different cell sections.

    Note: Excludes gap junctions since they don't have an afferent id stored in the h5 file.

    Parameters
    ----------
    config : str
        Path to BMTK config file.
    source : str
        The source BMTK network name.
    target : str
        The target BMTK network name.
    sids : str
        Column name in nodes file containing source population identifiers.
    tids : str
        Column name in nodes file containing target population identifiers.
    syn_feature : str, optional
        Synaptic feature to analyze. Default is 'afferent_section_id'.
        Options: 'afferent_section_id' or 'afferent_section_pos'.

    Returns
    -------
    tuple
        (matplotlib.figure.Figure, matplotlib.axes.Axes) containing the plot.

    Raises
    ------
    ValueError
        If required parameters are missing or invalid.
    RuntimeError
        If template loading or cell instantiation fails.

    Examples
    --------
    >>> fig, ax = plot_synapse_location(
    ...     config='config.json',
    ...     source='LGN',
    ...     target='cortex',
    ...     sids='node_type_id',
    ...     tids='node_type_id'
    ... )
    """
    # Validate inputs
    if not all([config, source, target, sids, tids]):
        raise ValueError(
            "Missing required parameters: config, source, target, sids, and tids must be provided"
        )

    # Fix the validation logic - it was using 'or' instead of 'and'
    #if syn_feature not in ["afferent_section_id", "afferent_section_pos"]:
    #    raise ValueError("Currently only syn features supported are afferent_section_id or afferent_section_pos")

    try:
        # Load mechanisms and template
        util.load_templates_from_config(config)
    except Exception as e:
        raise RuntimeError(f"Failed to load templates from config: {str(e)}")

    try:
        # Load node and edge data
        nodes, edges = util.load_nodes_edges_from_config(config)
        if source not in nodes or f"{source}_to_{target}" not in edges:
            raise ValueError(f"Source '{source}' or target '{target}' networks not found in data")

        target_nodes = nodes[target]
        source_nodes = nodes[source]
        edges = edges[f"{source}_to_{target}"]

        # Find edges with NaN values in the specified feature
        nan_edges = edges[edges[syn_feature].isna()]
        # Print information about removed edges
        if not nan_edges.empty:
            unique_indices = sorted(list(set(nan_edges.index.tolist())))
            print(f"Removing {len(nan_edges)} edges with missing {syn_feature}")
            print(f"Unique indices removed: {unique_indices}")

        # Filter out edges with NaN values in the specified feature
        edges = edges[edges[syn_feature].notna()]

    except Exception as e:
        raise RuntimeError(f"Failed to load nodes and edges: {str(e)}")

    # Map identifiers while checking for missing values
    edges["target_model_template"] = edges["target_node_id"].map(target_nodes["model_template"])
    edges["target_pop_name"] = edges["target_node_id"].map(target_nodes[tids])
    edges["source_pop_name"] = edges["source_node_id"].map(source_nodes[sids])

    if edges["target_model_template"].isnull().any():
        print("Warning: Some target nodes missing model template")
    if edges["target_pop_name"].isnull().any():
        print("Warning: Some target nodes missing population name")
    if edges["source_pop_name"].isnull().any():
        print("Warning: Some source nodes missing population name")

    # Get unique populations
    source_pops = edges["source_pop_name"].unique()
    target_pops = edges["target_pop_name"].unique()

    # Initialize matrices
    num_connections = np.zeros((len(source_pops), len(target_pops)))
    text_data = np.empty((len(source_pops), len(target_pops)), dtype=object)

    # Create mappings for indices
    source_pop_to_idx = {pop: idx for idx, pop in enumerate(source_pops)}
    target_pop_to_idx = {pop: idx for idx, pop in enumerate(target_pops)}

    # Cache for section mappings to avoid recreating cells
    section_mappings = {}

    # Calculate connectivity statistics
    for source_pop in source_pops:
        for target_pop in target_pops:
            # Filter edges for this source-target pair
            filtered_edges = edges[
                (edges["source_pop_name"] == source_pop) & (edges["target_pop_name"] == target_pop)
            ]

            source_idx = source_pop_to_idx[source_pop]
            target_idx = target_pop_to_idx[target_pop]

            if len(filtered_edges) == 0:
                num_connections[source_idx, target_idx] = 0
                text_data[source_idx, target_idx] = "No connections"
                continue

            total_connections = len(filtered_edges)
            target_model_template = filtered_edges["target_model_template"].iloc[0]

            try:
                # Get or create section mapping for this model
                if target_model_template not in section_mappings:
                    cell_class_name = (
                        target_model_template.split(":")[1]
                        if ":" in target_model_template
                        else target_model_template
                    )
                    cell = getattr(h, cell_class_name)()

                    # Create section mapping
                    section_mapping = {}
                    for idx, sec in enumerate(cell.all):
                        section_mapping[idx] = sec.name().split(".")[-1]  # Clean name
                    section_mappings[target_model_template] = section_mapping

                section_mapping = section_mappings[target_model_template]

                # Calculate section distribution
                section_counts = filtered_edges[syn_feature].value_counts()
                section_percentages = (section_counts / total_connections * 100).round(1)

                # Format section distribution text - show all sections
                section_display = []
                for section_id, percentage in section_percentages.items():
                    section_name = section_mapping.get(section_id, f"sec_{section_id}")
                    section_display.append(f"{section_name}:{percentage}%")


                num_connections[source_idx, target_idx] = total_connections
                text_data[source_idx, target_idx] = "\n".join(section_display)

            except Exception as e:
                print(f"Warning: Error processing {target_model_template}: {str(e)}")
                num_connections[source_idx, target_idx] = total_connections
                text_data[source_idx, target_idx] = "Feature info N/A"

    # Create the plot
    title = f"Synaptic Distribution by {syn_feature.replace('_', ' ').title()}: {source} to {target}"
    fig, ax = plot_connection_info(
        text=text_data,
        num=num_connections,
        source_labels=list(source_pops),
        target_labels=list(target_pops),
        title=title,
        syn_info="1",
    )
    return fig, ax