Skip to content

BMPlot API Reference

This page provides API reference documentation for the BMPlot module which contains functions for plotting and visualizing BMTK network models and simulation results.

Connections Module

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.plot_connection_info(text, num, source_labels, target_labels, title, syn_info='0', return_dict=None)

Plot connection information as a heatmap with text annotations.

Parameters:

Name Type Description Default
text ndarray

2D array of text annotations for each cell.

required
num ndarray

2D array of numerical values for the heatmap colors.

required
source_labels list of str

Labels for source populations (rows).

required
target_labels list of str

Labels for target populations (columns).

required
title str

Title for the plot.

required
syn_info str

Type of synaptic information being displayed. Options: '0', '1', '2', '3'. Default is '0'.

'0'
save_file str

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

required
return_dict bool

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

None

Returns:

Type Description
Union[Tuple, Dict, None]

If return_dict=True, returns a dictionary of connection information. Otherwise, returns a tuple of (Figure, Axes), or None if just displaying.

Notes

Handles missing source and target values by setting them to 0.

Source code in bmtool/bmplot/connections.py
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
def plot_connection_info(
    text: np.ndarray,
    num: np.ndarray,
    source_labels: List[str],
    target_labels: List[str],
    title: str,
    syn_info: str = "0",

    return_dict: Optional[bool] = None,
) -> Union[Tuple, Dict, None]:
    """
    Plot connection information as a heatmap with text annotations.

    Parameters
    ----------
    text : np.ndarray
        2D array of text annotations for each cell.
    num : np.ndarray
        2D array of numerical values for the heatmap colors.
    source_labels : list of str
        Labels for source populations (rows).
    target_labels : list of str
        Labels for target populations (columns).
    title : str
        Title for the plot.
    syn_info : str, optional
        Type of synaptic information being displayed. Options: '0', '1', '2', '3'.
        Default is '0'.
    save_file : str, optional
        Path to save the plot. If None, plot is not saved.
    return_dict : bool, optional
        If True, return connection information as a dictionary. Default is None.

    Returns
    -------
    Union[Tuple, Dict, None]
        If return_dict=True, returns a dictionary of connection information.
        Otherwise, returns a tuple of (Figure, Axes), or None if just displaying.

    Notes
    -----
    Handles missing source and target values by setting them to 0.
    """
    # Ensure text dimensions match num dimensions
    num_source = len(source_labels)
    num_target = len(target_labels)

    # Set color map
    matplotlib.rc("image", cmap="viridis")

    # Calculate square cell size to ensure proper aspect ratio
    base_cell_size = 0.6  # Base size per cell

    # Calculate figure dimensions with proper aspect ratio
    # Make sure width and height are proportional to the matrix dimensions
    fig_width = max(8, num_target * base_cell_size + 4)  # Width based on columns
    fig_height = max(6, num_source * base_cell_size + 3)  # Height based on rows

    # Ensure minimum readable size
    min_fig_size = 8
    if fig_width < min_fig_size or fig_height < min_fig_size:
        scale_factor = min_fig_size / min(fig_width, fig_height)
        fig_width *= scale_factor
        fig_height *= scale_factor

    # Create figure and axis
    fig1, ax1 = plt.subplots(figsize=(fig_width, fig_height))

    # Replace NaN with 0 and create heatmap
    num_clean = np.nan_to_num(num, nan=0)
    # if string is nan\nnan make it 0

    # Use 'auto' aspect ratio to let matplotlib handle it properly
    # This prevents the stretching issue
    im1 = ax1.imshow(num_clean, aspect="auto", interpolation="nearest")

    # Set ticks and labels
    ax1.set_xticks(list(np.arange(len(target_labels))))
    ax1.set_yticks(list(np.arange(len(source_labels))))
    ax1.set_xticklabels(target_labels)
    ax1.set_yticklabels(source_labels)

    # Improved font sizing based on matrix size
    label_font_size = max(8, min(14, 120 / max(num_source, num_target)))

    # Style the tick labels
    ax1.tick_params(axis="y", labelsize=label_font_size, pad=5)
    plt.setp(
        ax1.get_xticklabels(),
        rotation=45,
        ha="right",
        rotation_mode="anchor",
        fontsize=label_font_size,
    )

    # Dictionary to store connection information
    graph_dict = {}

    # Improved text size calculation - more readable for larger matrices
    text_size = max(6, min(12, 80 / max(num_source, num_target)))

    # Loop over data dimensions and create text annotations
    for i in range(num_source):
        for j in range(num_target):
            edge_info = text[i, j] if text[i, j] is not None else "0\n0"

            if source_labels[i] not in graph_dict:
                graph_dict[source_labels[i]] = {}
            graph_dict[source_labels[i]][target_labels[j]] = edge_info

            # Skip displaying text for NaN values to reduce clutter
            if edge_info == "nan\nnan":
                edge_info = "0\n±0"

            # Format the text display
            if isinstance(edge_info, str) and "\n" in edge_info:
                # For mean/std format (e.g. "15.5\n4.0")
                parts = edge_info.split("\n")
                if len(parts) == 2:
                    try:
                        mean_val = float(parts[0])
                        std_val = float(parts[1])
                        display_text = f"{mean_val:.1f}\n±{std_val:.1f}"
                    except ValueError:
                        display_text = edge_info
                else:
                    display_text = edge_info
            else:
                display_text = str(edge_info)

            # Add text to plot with better contrast
            text_color = "white" if num_clean[i, j] < (np.nanmax(num_clean) * 0.9) else "black"

            if syn_info == "2" or syn_info == "3":
                ax1.text(
                    j,
                    i,
                    display_text,
                    ha="center",
                    va="center",
                    color=text_color,
                    rotation=37.5,
                    fontsize=text_size,
                    weight="bold",
                )
            else:
                ax1.text(
                    j,
                    i,
                    display_text,
                    ha="center",
                    va="center",
                    color=text_color,
                    fontsize=text_size,
                    weight="bold",
                )

    # Set labels and title
    title_font_size = max(12, min(18, label_font_size + 4))
    ax1.set_ylabel("Source", fontsize=title_font_size, weight="bold", labelpad=10)
    ax1.set_xlabel("Target", fontsize=title_font_size, weight="bold", labelpad=10)
    ax1.set_title(title, fontsize=title_font_size + 2, weight="bold", pad=20)

    # Add colorbar
    cbar = plt.colorbar(im1, shrink=0.8)
    cbar.ax.tick_params(labelsize=label_font_size)

    # Adjust layout to minimize whitespace and prevent stretching
    plt.tight_layout(pad=1.5)

    # Force square cells by setting equal axis limits if needed
    ax1.set_xlim(-0.5, num_target - 0.5)
    ax1.set_ylim(num_source - 0.5, -0.5)  # Inverted for proper matrix orientation

    # Display or save the plot
    try:
        # Check if running in notebook
        from IPython import get_ipython

        notebook = get_ipython() is not None
    except ImportError:
        notebook = False

    if not notebook:
        plt.show()

    if return_dict:
        return graph_dict
    else:
        return fig1, ax1

bmtool.bmplot.connections.connector_percent_matrix(csv_path=None, exclude_strings=None, assemb_key=None, title='Percent connection matrix', pop_order=None)

Generates and plots a connection matrix based on connection probabilities from a CSV file.

This function visualizes percent connectivity while factoring in population distance and other parameters. It processes connection data by filtering 'Source' and 'Target' columns in the CSV and displays the percentage of connected pairs for each population combination in a matrix.

Parameters:

Name Type Description Default
csv_path str

Path to the CSV file containing connection data. The CSV should be an output from the bmtool.connector classes, specifically generated by the save_connection_report() function.

None
exclude_strings list of str

List of strings to exclude rows where 'Source' or 'Target' contain these strings.

None
assemb_key str

Key to identify and process assembly connections.

None
title str

Title for the generated plot. Default is 'Percent connection matrix'.

'Percent connection matrix'
pop_order list of str

List of population labels to specify the order for x- and y-ticks in the plot.

None

Returns:

Type Description
tuple

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

Examples:

>>> fig, ax = connector_percent_matrix(
...     csv_path='connections.csv',
...     exclude_strings=['Gap'],
...     title='Network Connectivity'
... )
Source code in bmtool/bmplot/connections.py
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
def connector_percent_matrix(
    csv_path: Optional[str] = None,
    exclude_strings: Optional[List[str]] = None,
    assemb_key: Optional[str] = None,
    title: str = "Percent connection matrix",
    pop_order: Optional[List[str]] = None,
) -> Tuple[Any, Any]:
    """
    Generates and plots a connection matrix based on connection probabilities from a CSV file.

    This function visualizes percent connectivity while factoring in population distance and other parameters.
    It processes connection data by filtering 'Source' and 'Target' columns in the CSV and displays the
    percentage of connected pairs for each population combination in a matrix.

    Parameters
    ----------
    csv_path : str, optional
        Path to the CSV file containing connection data. The CSV should be an output from the
        bmtool.connector classes, specifically generated by the `save_connection_report()` function.
    exclude_strings : list of str, optional
        List of strings to exclude rows where 'Source' or 'Target' contain these strings.
    assemb_key : str, optional
        Key to identify and process assembly connections.
    title : str, optional
        Title for the generated plot. Default is 'Percent connection matrix'.
    pop_order : list of str, optional
        List of population labels to specify the order for x- and y-ticks in the plot.

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

    Examples
    --------
    >>> fig, ax = connector_percent_matrix(
    ...     csv_path='connections.csv',
    ...     exclude_strings=['Gap'],
    ...     title='Network Connectivity'
    ... )
    """
    # Read the CSV data
    df = pd.read_csv(csv_path)

    # Choose the column to display
    selected_column = "Percent connectionivity within possible connections"

    # Filter the DataFrame based on exclude_strings
    def filter_dataframe(df, column_name, exclude_strings):
        def process_string(string):
            match = re.search(r"\[\'(.*?)\'\]", string)
            if exclude_strings and any(ex_string in string for ex_string in exclude_strings):
                return None
            elif match:
                filtered_string = match.group(1)
                if "Gap" in string:
                    filtered_string = filtered_string + "-Gap"

                if assemb_key:
                    if assemb_key in string:
                        filtered_string = filtered_string + assemb_key

                return filtered_string  # Return matched string

            return string  # If no match, return the original string

        df[column_name] = df[column_name].apply(process_string)
        df = df.dropna(subset=[column_name])

        return df

    df = filter_dataframe(df, "Source", exclude_strings)
    df = filter_dataframe(df, "Target", exclude_strings)

    # process assem rows and combine them into one prob per assem type
    if assemb_key:
        assems = df[df["Source"].str.contains(assemb_key)]
        unique_sources = assems["Source"].unique()

        for source in unique_sources:
            source_assems = assems[assems["Source"] == source]
            unique_targets = source_assems[
                "Target"
            ].unique()  # Filter targets for the current source

            for target in unique_targets:
                # Filter the assemblies with the current source and target
                unique_assems = source_assems[source_assems["Target"] == target]

                # find the prob of a conn
                forward_probs = []
                for _, row in unique_assems.iterrows():
                    selected_percentage = row[selected_column]
                    selected_percentage = [
                        float(p) for p in selected_percentage.strip("[]").split()
                    ]
                    if len(selected_percentage) == 1 or len(selected_percentage) == 2:
                        forward_probs.append(selected_percentage[0])
                    if len(selected_percentage) == 3:
                        forward_probs.append(selected_percentage[0])
                        forward_probs.append(selected_percentage[1])

                mean_probs = np.mean(forward_probs)
                source = source.replace(assemb_key, "")
                target = target.replace(assemb_key, "")
                new_row = pd.DataFrame(
                    {
                        "Source": [source],
                        "Target": [target],
                        "Percent connectionivity within possible connections": [mean_probs],
                        "Percent connectionivity within all connections": [0],
                    }
                )

                df = pd.concat([df, new_row], ignore_index=False)

    # Prepare connection data
    connection_data = {}
    for _, row in df.iterrows():
        source, target, selected_percentage = row["Source"], row["Target"], row[selected_column]
        if isinstance(selected_percentage, str):
            selected_percentage = [float(p) for p in selected_percentage.strip("[]").split()]
        connection_data[(source, target)] = selected_percentage

    # Determine population order
    populations = sorted(list(set(df["Source"].unique()) | set(df["Target"].unique())))
    if pop_order:
        populations = [
            pop for pop in pop_order if pop in populations
        ]  # Order according to pop_order, if provided
    num_populations = len(populations)

    # Create an empty matrix and populate it
    connection_matrix = np.zeros((num_populations, num_populations), dtype=float)
    for (source, target), probabilities in connection_data.items():
        if source in populations and target in populations:
            source_idx = populations.index(source)
            target_idx = populations.index(target)

            if isinstance(probabilities, float):
                connection_matrix[source_idx][target_idx] = probabilities
            elif len(probabilities) == 1:
                connection_matrix[source_idx][target_idx] = probabilities[0]
            elif len(probabilities) == 2:
                connection_matrix[source_idx][target_idx] = probabilities[0]
            elif len(probabilities) == 3:
                connection_matrix[source_idx][target_idx] = probabilities[0]
                connection_matrix[target_idx][source_idx] = probabilities[1]
            else:
                raise Exception("unsupported format")

    # Plotting
    fig, ax = plt.subplots(figsize=(10, 8))
    im = ax.imshow(connection_matrix, cmap="viridis", interpolation="nearest")

    # Add annotations
    for i in range(num_populations):
        for j in range(num_populations):
            text = ax.text(
                j,
                i,
                f"{connection_matrix[i, j]:.2f}%",
                ha="center",
                va="center",
                color="w",
                size=10,
                weight="semibold",
            )

    # Add colorbar
    plt.colorbar(im, label=f"{selected_column}")

    # Set title and axis labels
    ax.set_title(title)
    ax.set_xlabel("Target Population")
    ax.set_ylabel("Source Population")

    # Set ticks and labels based on populations in specified order
    ax.set_xticks(np.arange(num_populations))
    ax.set_yticks(np.arange(num_populations))
    ax.set_xticklabels(populations, rotation=45, ha="right", size=12, weight="semibold")
    ax.set_yticklabels(populations, size=12, weight="semibold")

    plt.tight_layout()

    return fig, ax

bmtool.bmplot.connections.plot_3d_positions(config=None, sources=None, sid=None, title=None, subset=None)

Plots a 3D graph of all cells with x, y, z location.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

None
sources str

Which network(s) to plot. If None or 'all', plots all networks.

None
sid str

Column name to group cell types (node grouping criteria).

None
title str

Plot title. Default is '3D positions'.

None
subset int

Take every Nth row. This makes plotting large networks easier to visualize.

None

Returns:

Type Description
tuple

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

Examples:

>>> fig, ax = plot_3d_positions(
...     config='config.json',
...     sources='cortex',
...     sid='node_type_id',
...     title='3D Neuron Positions'
... )
Source code in bmtool/bmplot/connections.py
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
def plot_3d_positions(
    config: Optional[str] = None,
    sources: Optional[str] = None,
    sid: Optional[str] = None,
    title: Optional[str] = None,

    subset: Optional[int] = None,
) -> Tuple[Any, Any]:
    """
    Plots a 3D graph of all cells with x, y, z location.

    Parameters
    ----------
    config : str, optional
        Path to a BMTK simulation config file.
    sources : str, optional
        Which network(s) to plot. If None or 'all', plots all networks.
    sid : str, optional
        Column name to group cell types (node grouping criteria).
    title : str, optional
        Plot title. Default is '3D positions'.
    subset : int, optional
        Take every Nth row. This makes plotting large networks easier to visualize.

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

    Examples
    --------
    >>> fig, ax = plot_3d_positions(
    ...     config='config.json',
    ...     sources='cortex',
    ...     sid='node_type_id',
    ...     title='3D Neuron Positions'
    ... )
    """

    if not config:
        raise Exception("config not defined")

    if sources is None:
        sources = "all"

    # Set group keys (e.g., node types)
    group_keys = sid
    if title is None:
        title = "3D positions"

    # Load nodes from the configuration
    nodes = util.load_nodes_from_config(config)

    # Get the list of populations to plot
    if "all" in sources:
        populations = list(nodes)
    else:
        populations = sources.split(",")

    # Split group_by into list
    group_keys = group_keys.split(",")
    group_keys += (len(populations) - len(group_keys)) * [
        "node_type_id"
    ]  # Extend the array to default values if not enough given
    if len(group_keys) > 1:
        raise Exception("Only one group by is supported currently!")

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(projection="3d")
    handles = []

    for pop in list(nodes):
        if "all" not in populations and pop not in populations:
            continue

        nodes_df = nodes[pop]
        group_key = group_keys[0]

        # If group_key is provided, ensure the column exists in the dataframe
        if group_key is not None:
            if group_key not in nodes_df:
                raise Exception(f"Could not find column '{group_key}' in {pop}")

            groupings = nodes_df.groupby(group_key)
            n_colors = nodes_df[group_key].nunique()
            color_norm = colors.Normalize(vmin=0, vmax=(n_colors - 1))
            scalar_map = cmx.ScalarMappable(norm=color_norm, cmap="hsv")
            color_map = [scalar_map.to_rgba(i) for i in range(n_colors)]
        else:
            groupings = [(None, nodes_df)]
            color_map = ["blue"]

        # Loop over groupings and plot
        for color, (group_name, group_df) in zip(color_map, groupings):
            if "pos_x" not in group_df or "pos_y" not in group_df or "pos_z" not in group_df:
                print(
                    f"Warning: Missing position columns in group '{group_name}' for {pop}. Skipping this group."
                )
                continue  # Skip if position columns are missing

            # Subset the dataframe by taking every Nth row if subset is provided
            if subset is not None:
                group_df = group_df.iloc[::subset]

            h = ax.scatter(
                group_df["pos_x"],
                group_df["pos_y"],
                group_df["pos_z"],
                color=color,
                label=group_name,
            )
            handles.append(h)

    if not handles:
        print("No data to plot.")
        return fig, ax

    # Set plot title and legend
    plt.title(title)
    plt.legend(handles=handles)

    # Add axis labels
    ax.set_xlabel("X Position (μm)")
    ax.set_ylabel("Y Position (μm)")
    ax.set_zlabel("Z Position (μm)")

    # Draw the plot
    plt.draw()
    plt.tight_layout()

    return fig, ax

bmtool.bmplot.connections.plot_3d_cell_rotation(config=None, sources=None, sids=None, title=None, quiver_length=None, arrow_length_ratio=None, group=None, subset=None)

Plot 3D visualization of cell rotations with quiver arrows showing rotation orientations.

Parameters:

Name Type Description Default
config str

Path to a BMTK simulation config file.

None
sources list of str

Network names to plot. If None or contains 'all', plots all networks.

None
sids str

Comma-separated column names to group cell types.

None
title str

Plot title. Default is 'Cell rotations'.

None
quiver_length float

Length of the quiver arrows. If None, use matplotlib default.

None
arrow_length_ratio float

Ratio of arrow head size to quiver length.

None
group str

Comma-separated group names to include. If None, include all groups.

None
subset int

Take every Nth row. Useful for visualizing large networks.

None

Returns:

Type Description
tuple

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

Examples:

>>> fig, ax = plot_3d_cell_rotation(
...     config='config.json',
...     sources=['cortex'],
...     sids='node_type_id',
...     title='Cell Rotation Vectors'
... )
Source code in bmtool/bmplot/connections.py
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
def plot_3d_cell_rotation(
    config: Optional[str] = None,
    sources: Optional[List[str]] = None,
    sids: Optional[str] = None,
    title: Optional[str] = None,

    quiver_length: Optional[float] = None,
    arrow_length_ratio: Optional[float] = None,
    group: Optional[str] = None,
    subset: Optional[int] = None,
) -> Tuple[Any, Any]:
    """
    Plot 3D visualization of cell rotations with quiver arrows showing rotation orientations.

    Parameters
    ----------
    config : str, optional
        Path to a BMTK simulation config file.
    sources : list of str, optional
        Network names to plot. If None or contains 'all', plots all networks.
    sids : str, optional
        Comma-separated column names to group cell types.
    title : str, optional
        Plot title. Default is 'Cell rotations'.
    quiver_length : float, optional
        Length of the quiver arrows. If None, use matplotlib default.
    arrow_length_ratio : float, optional
        Ratio of arrow head size to quiver length.
    group : str, optional
        Comma-separated group names to include. If None, include all groups.
    subset : int, optional
        Take every Nth row. Useful for visualizing large networks.

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

    Examples
    --------
    >>> fig, ax = plot_3d_cell_rotation(
    ...     config='config.json',
    ...     sources=['cortex'],
    ...     sids='node_type_id',
    ...     title='Cell Rotation Vectors'
    ... )
    """
    from scipy.spatial.transform import Rotation as R

    if not config:
        raise Exception("config not defined")

    if sources is None:
        sources = ["all"]

    group_keys = sids.split(",") if sids else []

    if title is None:
        title = "Cell rotations"

    nodes = util.load_nodes_from_config(config)

    if "all" in sources:
        populations = list(nodes)
    else:
        populations = sources

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection="3d")
    handles = []

    for nodes_key, group_key in zip(list(nodes), group_keys):
        if "all" not in populations and nodes_key not in populations:
            continue

        nodes_df = nodes[nodes_key]

        if group_key is not None:
            if group_key not in nodes_df.columns:
                raise Exception(f"Could not find column {group_key}")
            groupings = nodes_df.groupby(group_key)

            n_colors = nodes_df[group_key].nunique()
            color_norm = colors.Normalize(vmin=0, vmax=(n_colors - 1))
            scalar_map = cmx.ScalarMappable(norm=color_norm, cmap="hsv")
            color_map = [scalar_map.to_rgba(i) for i in range(n_colors)]
        else:
            groupings = [(None, nodes_df)]
            color_map = ["blue"]

        for color, (group_name, group_df) in zip(color_map, groupings):
            if subset is not None:
                group_df = group_df.iloc[::subset]

            if group and group_name not in group.split(","):
                continue

            if "pos_x" not in group_df or "rotation_angle_xaxis" not in group_df:
                continue

            X = group_df["pos_x"]
            Y = group_df["pos_y"]
            Z = group_df["pos_z"]
            U = group_df["rotation_angle_xaxis"].values
            V = group_df["rotation_angle_yaxis"].values
            W = group_df["rotation_angle_zaxis"].values

            if U is None:
                U = np.zeros(len(X))
            if V is None:
                V = np.zeros(len(Y))
            if W is None:
                W = np.zeros(len(Z))

            # Create rotation matrices from Euler angles
            rotations = R.from_euler("xyz", np.column_stack((U, V, W)), degrees=False)

            # Define initial vectors
            init_vectors = np.column_stack((np.ones(len(X)), np.zeros(len(Y)), np.zeros(len(Z))))

            # Apply rotations to initial vectors
            rots = np.dot(rotations.as_matrix(), init_vectors.T).T

            # Extract x, y, and z components of the rotated vectors
            rot_x = rots[:, 0]
            rot_y = rots[:, 1]
            rot_z = rots[:, 2]

            h = ax.quiver(
                X,
                Y,
                Z,
                rot_x,
                rot_y,
                rot_z,
                color=color,
                label=group_name,
                arrow_length_ratio=arrow_length_ratio,
                length=quiver_length,
            )
            ax.scatter(X, Y, Z, color=color, label=group_name)
            ax.set_xlim([min(X), max(X)])
            ax.set_ylim([min(Y), max(Y)])
            ax.set_zlim([min(Z), max(Z)])
            handles.append(h)

    if not handles:
        return fig, ax

    plt.title(title)
    plt.legend(handles=handles)
    plt.draw()

    return fig, ax

Spikes Module

bmtool.bmplot.spikes.raster(spikes_df=None, config=None, network_name=None, groupby='pop_name', sortby=None, ax=None, tstart=None, tstop=None, color_map=None, dot_size=0.3)

Plots a raster plot of neural spikes, with different colors for each population.

Parameters:

spikes_df : pd.DataFrame, optional DataFrame containing spike data with columns 'timestamps', 'node_ids', and optional 'pop_name'. config : str, optional Path to the configuration file used to load node data. network_name : str, optional Specific network name to select from the configuration; if not provided, uses the first network. groupby : str, optional Column name to group spikes by for coloring. Default is 'pop_name'. sortby : str, optional Column name to sort node_ids within each group. If provided, nodes within each population will be sorted by this column. ax : matplotlib.axes.Axes, optional Axes on which to plot the raster; if None, a new figure and axes are created. tstart : float, optional Start time for filtering spikes; only spikes with timestamps greater than tstart will be plotted. tstop : float, optional Stop time for filtering spikes; only spikes with timestamps less than tstop will be plotted. color_map : dict, optional Dictionary specifying colors for each population. Keys should be population names, and values should be color values. dot_size: float, optional Size of the dot to display on the scatterplot

Returns:

matplotlib.axes.Axes Axes with the raster plot.

Notes:
  • If config is provided, the function merges population names from the node data with spikes_df.
  • Each unique population from groupby in spikes_df will be represented by a different color if color_map is not specified.
  • If color_map is provided, it should contain colors for all unique pop_name values in spikes_df.
Source code in bmtool/bmplot/spikes.py
 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
def raster(
    spikes_df: Optional[pd.DataFrame] = None,
    config: Optional[str] = None,
    network_name: Optional[str] = None,
    groupby: str = "pop_name",
    sortby: Optional[str] = None,
    ax: Optional[Axes] = None,
    tstart: Optional[float] = None,
    tstop: Optional[float] = None,
    color_map: Optional[Dict[str, str]] = None,
    dot_size: float = 0.3,
) -> Axes:
    """
    Plots a raster plot of neural spikes, with different colors for each population.

    Parameters:
    ----------
    spikes_df : pd.DataFrame, optional
        DataFrame containing spike data with columns 'timestamps', 'node_ids', and optional 'pop_name'.
    config : str, optional
        Path to the configuration file used to load node data.
    network_name : str, optional
        Specific network name to select from the configuration; if not provided, uses the first network.
    groupby : str, optional
        Column name to group spikes by for coloring. Default is 'pop_name'.
    sortby : str, optional
        Column name to sort node_ids within each group. If provided, nodes within each population will be sorted by this column.
    ax : matplotlib.axes.Axes, optional
        Axes on which to plot the raster; if None, a new figure and axes are created.
    tstart : float, optional
        Start time for filtering spikes; only spikes with timestamps greater than `tstart` will be plotted.
    tstop : float, optional
        Stop time for filtering spikes; only spikes with timestamps less than `tstop` will be plotted.
    color_map : dict, optional
        Dictionary specifying colors for each population. Keys should be population names, and values should be color values.
    dot_size: float, optional
        Size of the dot to display on the scatterplot

    Returns:
    -------
    matplotlib.axes.Axes
        Axes with the raster plot.

    Notes:
    -----
    - If `config` is provided, the function merges population names from the node data with `spikes_df`.
    - Each unique population from groupby in `spikes_df` will be represented by a different color if `color_map` is not specified.
    - If `color_map` is provided, it should contain colors for all unique `pop_name` values in `spikes_df`.
    """
    # Initialize axes if none provided
    sns.set_style("whitegrid")
    if ax is None:
        _, ax = plt.subplots(1, 1)

    # Filter spikes by time range if specified
    if tstart is not None:
        spikes_df = spikes_df[spikes_df["timestamps"] > tstart]
    if tstop is not None:
        spikes_df = spikes_df[spikes_df["timestamps"] < tstop]

    # Load and merge node population data if config is provided
    if config:
        nodes = load_nodes_from_config(config)
        if network_name:
            nodes = nodes.get(network_name, {})
        else:
            nodes = list(nodes.values())[0] if nodes else {}
            print(
                "Grabbing first network; specify a network name to ensure correct node population is selected."
            )

        # Find common columns, but exclude the join key from the list
        common_columns = spikes_df.columns.intersection(nodes.columns).tolist()
        common_columns = [
            col for col in common_columns if col != "node_ids"
        ]  # Remove our join key from the common list

        # Drop all intersecting columns except the join key column from df2
        spikes_df = spikes_df.drop(columns=common_columns)
        # merge nodes and spikes df
        spikes_df = spikes_df.merge(
            nodes[groupby], left_on="node_ids", right_index=True, how="left"
        )

    # Get unique population names
    unique_pop_names = spikes_df[groupby].unique()

    # Generate colors if no color_map is provided
    if color_map is None:
        cmap = plt.get_cmap("tab10")  # Default colormap
        color_map = {
            pop_name: cmap(i / len(unique_pop_names)) for i, pop_name in enumerate(unique_pop_names)
        }
    else:
        # Ensure color_map contains all population names
        missing_colors = [pop for pop in unique_pop_names if pop not in color_map]
        if missing_colors:
            raise ValueError(f"color_map is missing colors for populations: {missing_colors}")

    # Plot each population with its specified or generated color
    legend_handles = []
    y_offset = 0  # Track y-position offset for stacking populations

    for pop_name, group in spikes_df.groupby(groupby):
        if sortby:
            # Sort by the specified column, putting NaN values at the end
            group_sorted = group.sort_values(by=sortby, na_position='last')
            # Create a mapping from node_ids to consecutive y-positions based on sorted order
            # Use the sorted order to maintain the same sequence for all spikes from same node
            unique_nodes_sorted = group_sorted['node_ids'].drop_duplicates()
            node_to_y = {node_id: y_offset + i for i, node_id in enumerate(unique_nodes_sorted)}
            # Map node_ids to new y-positions for ALL spikes (not just the sorted group)
            y_positions = group['node_ids'].map(node_to_y)
            # Verify no data was lost
            assert len(y_positions) == len(group), f"Data loss detected in population {pop_name}"
            assert y_positions.isna().sum() == 0, f"Unmapped node_ids found in population {pop_name}"
        else:
            y_positions = group['node_ids']

        ax.scatter(group["timestamps"], y_positions, color=color_map[pop_name], s=dot_size)
        # Dummy scatter for consistent legend appearance
        handle = ax.scatter([], [], color=color_map[pop_name], label=pop_name, s=20)
        legend_handles.append(handle)

        # Update y_offset for next population if sortby is used
        if sortby:
            y_offset += len(unique_nodes_sorted)

    # Label axes
    ax.set_xlabel("Time")
    ax.set_ylabel("Node ID")
    ax.legend(handles=legend_handles, title="Population", loc="upper right", framealpha=0.9)

    return ax

bmtool.bmplot.spikes.plot_firing_rate_pop_stats(firing_stats, groupby, ax=None, color_map=None)

Plots a bar graph of mean firing rates with error bars (standard deviation).

Parameters:

firing_stats : pd.DataFrame Dataframe containing 'firing_rate_mean' and 'firing_rate_std'. groupby : str or list of str Column(s) used for grouping. ax : matplotlib.axes.Axes, optional Axes on which to plot the bar chart; if None, a new figure and axes are created. color_map : dict, optional Dictionary specifying colors for each group. Keys should be group names, and values should be color values.

Returns:

matplotlib.axes.Axes Axes with the bar plot.

Source code in bmtool/bmplot/spikes.py
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
def plot_firing_rate_pop_stats(
    firing_stats: pd.DataFrame,
    groupby: Union[str, List[str]],
    ax: Optional[Axes] = None,
    color_map: Optional[Dict[str, str]] = None,
) -> Axes:
    """
    Plots a bar graph of mean firing rates with error bars (standard deviation).

    Parameters:
    ----------
    firing_stats : pd.DataFrame
        Dataframe containing 'firing_rate_mean' and 'firing_rate_std'.
    groupby : str or list of str
        Column(s) used for grouping.
    ax : matplotlib.axes.Axes, optional
        Axes on which to plot the bar chart; if None, a new figure and axes are created.
    color_map : dict, optional
        Dictionary specifying colors for each group. Keys should be group names, and values should be color values.

    Returns:
    -------
    matplotlib.axes.Axes
        Axes with the bar plot.
    """
    # Ensure groupby is a list for consistent handling
    sns.set_style("whitegrid")
    if isinstance(groupby, str):
        groupby = [groupby]

    # Create a categorical column for grouping
    firing_stats["group"] = firing_stats[groupby].astype(str).agg("_".join, axis=1)

    # Get unique group names
    unique_groups = firing_stats["group"].unique()

    # Generate colors if no color_map is provided
    if color_map is None:
        cmap = plt.get_cmap("viridis")
        color_map = {group: cmap(i / len(unique_groups)) for i, group in enumerate(unique_groups)}
    else:
        # Ensure color_map contains all groups
        missing_colors = [group for group in unique_groups if group not in color_map]
        if missing_colors:
            raise ValueError(f"color_map is missing colors for groups: {missing_colors}")

    # Create new figure and axes if ax is not provided
    if ax is None:
        fig, ax = plt.subplots(figsize=(10, 6))

    # Sort data for consistent plotting
    firing_stats = firing_stats.sort_values(by="group")

    # Extract values for plotting
    x_labels = firing_stats["group"]
    means = firing_stats["firing_rate_mean"]
    std_devs = firing_stats["firing_rate_std"]

    # Get colors for each group
    colors = [color_map[group] for group in x_labels]

    # Create bar plot
    bars = ax.bar(x_labels, means, yerr=std_devs, capsize=5, color=colors, edgecolor="black")

    # Add error bars manually with caps
    _, caps, _ = ax.errorbar(
        x=np.arange(len(x_labels)),
        y=means,
        yerr=std_devs,
        fmt="none",
        capsize=5,
        capthick=2,
        color="black",
    )

    # Formatting
    ax.set_xticks(np.arange(len(x_labels)))
    ax.set_xticklabels(x_labels, rotation=45, ha="right")
    ax.set_xlabel("Population Group")
    ax.set_ylabel("Mean Firing Rate (spikes/s)")
    ax.set_title("Firing Rate Statistics by Population")
    ax.grid(axis="y", linestyle="--", alpha=0.7)

    return ax

bmtool.bmplot.spikes.plot_firing_rate_distribution(individual_stats, groupby, ax=None, color_map=None, plot_type='box', swarm_alpha=0.6, logscale=False)

Plots a distribution of individual firing rates using one or more plot types (box plot, violin plot, or swarm plot), overlaying them on top of each other.

Parameters:

individual_stats : pd.DataFrame Dataframe containing individual firing rates and corresponding group labels. groupby : str or list of str Column(s) used for grouping. ax : matplotlib.axes.Axes, optional Axes on which to plot the graph; if None, a new figure and axes are created. color_map : dict, optional Dictionary specifying colors for each group. Keys should be group names, and values should be color values. plot_type : str or list of str, optional List of plot types to generate. Options: "box", "violin", "swarm". Default is "box". swarm_alpha : float, optional Transparency of swarm plot points. Default is 0.6. logscale : bool, optional If True, use logarithmic scale for the y-axis (default is False).

Returns:

matplotlib.axes.Axes Axes with the selected plot type(s) overlayed.

Source code in bmtool/bmplot/spikes.py
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
def plot_firing_rate_distribution(
    individual_stats: pd.DataFrame,
    groupby: Union[str, List[str]],
    ax: Optional[Axes] = None,
    color_map: Optional[Dict[str, str]] = None,
    plot_type: Union[str, List[str]] = "box",
    swarm_alpha: float = 0.6,
    logscale: bool = False,
) -> Axes:
    """
    Plots a distribution of individual firing rates using one or more plot types
    (box plot, violin plot, or swarm plot), overlaying them on top of each other.

    Parameters:
    ----------
    individual_stats : pd.DataFrame
        Dataframe containing individual firing rates and corresponding group labels.
    groupby : str or list of str
        Column(s) used for grouping.
    ax : matplotlib.axes.Axes, optional
        Axes on which to plot the graph; if None, a new figure and axes are created.
    color_map : dict, optional
        Dictionary specifying colors for each group. Keys should be group names, and values should be color values.
    plot_type : str or list of str, optional
        List of plot types to generate. Options: "box", "violin", "swarm". Default is "box".
    swarm_alpha : float, optional
        Transparency of swarm plot points. Default is 0.6.
    logscale : bool, optional
        If True, use logarithmic scale for the y-axis (default is False).

    Returns:
    -------
    matplotlib.axes.Axes
        Axes with the selected plot type(s) overlayed.
    """
    sns.set_style("whitegrid")
    # Ensure groupby is a list for consistent handling
    if isinstance(groupby, str):
        groupby = [groupby]

    # Create a categorical column for grouping
    individual_stats["group"] = individual_stats[groupby].astype(str).agg("_".join, axis=1)

    # Validate plot_type (it can be a list or a single type)
    if isinstance(plot_type, str):
        plot_type = [plot_type]

    for pt in plot_type:
        if pt not in ["box", "violin", "swarm"]:
            raise ValueError("plot_type must be one of: 'box', 'violin', 'swarm'.")

    # Get unique groups for coloring
    unique_groups = individual_stats["group"].unique()

    # Generate colors if no color_map is provided
    if color_map is None:
        cmap = plt.get_cmap("viridis")
        color_map = {group: cmap(i / len(unique_groups)) for i, group in enumerate(unique_groups)}

    # Ensure color_map contains all groups
    missing_colors = [group for group in unique_groups if group not in color_map]
    if missing_colors:
        raise ValueError(f"color_map is missing colors for groups: {missing_colors}")

    # Create new figure and axes if ax is not provided
    if ax is None:
        fig, ax = plt.subplots(figsize=(10, 6))

    # Sort data for consistent plotting
    individual_stats = individual_stats.sort_values(by="group")

    # Loop over each plot type and overlay them
    for pt in plot_type:
        if pt == "box":
            sns.boxplot(
                data=individual_stats,
                x="group",
                y="firing_rate",
                ax=ax,
                palette=color_map,
                width=0.5,
            )
        elif pt == "violin":
            sns.violinplot(
                data=individual_stats,
                x="group",
                y="firing_rate",
                ax=ax,
                palette=color_map,
                inner="box",
                alpha=0.4,
                cut=0,  # This prevents the KDE from extending beyond the data range
            )
        elif pt == "swarm":
            sns.swarmplot(
                data=individual_stats,
                x="group",
                y="firing_rate",
                ax=ax,
                palette=color_map,
                alpha=swarm_alpha,
            )

    # Formatting
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right")
    ax.set_xlabel("Population Group")
    ax.set_ylabel("Firing Rate (spikes/s)")
    ax.set_title("Firing Rate Distribution for individual cells")
    ax.grid(axis="y", linestyle="--", alpha=0.7)

    if logscale:
        ax.set_yscale('log')

    return ax

Entrainment Module

bmtool.bmplot.entrainment.plot_spike_power_correlation(spike_df, lfp_data, fs, pop_names, filter_method='wavelet', bandwidth=2.0, lowcut=None, highcut=None, freq_range=(10, 100), freq_step=5, type_name='raw', figsize=(12, 8))

Calculate and plot spike rate-LFP power correlation across frequencies for full signal.

Analyzes the relationship between population spike rates and LFP power across a range of frequencies, using Spearman correlation for the entire signal duration.

Parameters:

Name Type Description Default
spike_df DataFrame

DataFrame containing spike data with columns 'timestamps', 'node_ids', and 'pop_name'.

required
lfp_data DataArray

LFP data with time dimension.

required
fs float

Sampling frequency in Hz.

required
pop_names List[str]

List of population names to analyze.

required
filter_method str

Filtering method: 'wavelet' or 'butter' (default: 'wavelet').

'wavelet'
bandwidth float

Bandwidth parameter for wavelet filter (default: 2.0).

2.0
lowcut float

Lower frequency bound (Hz) for butterworth filter. Required if filter_method='butter'.

None
highcut float

Upper frequency bound (Hz) for butterworth filter. Required if filter_method='butter'.

None
freq_range Tuple[float, float]

Min and max frequency to analyze in Hz (default: (10, 100)).

(10, 100)
freq_step float

Step size for frequency analysis in Hz (default: 5).

5
type_name str

Which type of spike rate to use (default: 'raw').

'raw'
figsize Tuple[float, float]

Figure size (width, height) in inches (default: (12, 8)).

(12, 8)

Returns:

Type Description
Figure

Figure containing the correlation plot.

Notes
  • Uses Spearman correlation (rank-based, robust to outliers).
  • Pre-computes LFP power at all frequencies for efficiency.

Examples:

>>> fig = plot_spike_power_correlation(
...     spike_df=spike_df,
...     lfp_data=lfp,
...     fs=400,
...     pop_names=['PV', 'SST'],
...     freq_range=(10, 100),
...     freq_step=5
... )
Source code in bmtool/bmplot/entrainment.py
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
def plot_spike_power_correlation(
    spike_df: pd.DataFrame,
    lfp_data: xr.DataArray,
    fs: float,
    pop_names: List[str],
    filter_method: str = "wavelet",
    bandwidth: float = 2.0,
    lowcut: Optional[float] = None,
    highcut: Optional[float] = None,
    freq_range: Tuple[float, float] = (10, 100),
    freq_step: float = 5,
    type_name: str = "raw",
    figsize: Tuple[float, float] = (12, 8),
) -> Figure:
    """
    Calculate and plot spike rate-LFP power correlation across frequencies for full signal.

    Analyzes the relationship between population spike rates and LFP power across a range
    of frequencies, using Spearman correlation for the entire signal duration.

    Parameters
    ----------
    spike_df : pd.DataFrame
        DataFrame containing spike data with columns 'timestamps', 'node_ids', and 'pop_name'.
    lfp_data : xr.DataArray
        LFP data with time dimension.
    fs : float
        Sampling frequency in Hz.
    pop_names : List[str]
        List of population names to analyze.
    filter_method : str, optional
        Filtering method: 'wavelet' or 'butter' (default: 'wavelet').
    bandwidth : float, optional
        Bandwidth parameter for wavelet filter (default: 2.0).
    lowcut : float, optional
        Lower frequency bound (Hz) for butterworth filter. Required if filter_method='butter'.
    highcut : float, optional
        Upper frequency bound (Hz) for butterworth filter. Required if filter_method='butter'.
    freq_range : Tuple[float, float], optional
        Min and max frequency to analyze in Hz (default: (10, 100)).
    freq_step : float, optional
        Step size for frequency analysis in Hz (default: 5).
    type_name : str, optional
        Which type of spike rate to use (default: 'raw').
    figsize : Tuple[float, float], optional
        Figure size (width, height) in inches (default: (12, 8)).

    Returns
    -------
    matplotlib.figure.Figure
        Figure containing the correlation plot.

    Notes
    -----
    - Uses Spearman correlation (rank-based, robust to outliers).
    - Pre-computes LFP power at all frequencies for efficiency.

    Examples
    --------
    >>> fig = plot_spike_power_correlation(
    ...     spike_df=spike_df,
    ...     lfp_data=lfp,
    ...     fs=400,
    ...     pop_names=['PV', 'SST'],
    ...     freq_range=(10, 100),
    ...     freq_step=5
    ... )
    """
    # Compute spike rate for all spikes
    spike_rate = bmspikes.get_population_spike_rate(spike_df, fs=fs)

    # Setup frequencies for analysis
    frequencies = np.arange(freq_range[0], freq_range[1] + 1, freq_step)

    # Pre-calculate LFP power for all frequencies
    power_by_freq = {}
    for freq in frequencies:
        power_by_freq[freq] = get_lfp_power(
            lfp_data, freq, fs, filter_method, lowcut=lowcut, highcut=highcut, bandwidth=bandwidth
        )

    # Calculate correlations for each population and frequency
    results = {}
    for pop in pop_names:
        results[pop] = {}
        pop_spike_rate = spike_rate.sel(population=pop, type=type_name)

        for freq in frequencies:
            lfp_power = power_by_freq[freq]

            if len(pop_spike_rate) != len(lfp_power):
                print(f"Warning: Length mismatch for {pop} at {freq} Hz")
                print(f"{len(pop_spike_rate)} {len(lfp_power)}")
                continue

            corr, p_val = stats.spearmanr(pop_spike_rate.values, lfp_power.values)
            results[pop][freq] = {"correlation": corr, "p_value": p_val}

    # Create plot
    sns.set_style("whitegrid")
    fig = plt.figure(figsize=figsize)

    colors = plt.get_cmap("tab10")
    for i, pop in enumerate(pop_names):
        plot_freqs = []
        plot_corrs = []

        for freq in frequencies:
            if freq in results[pop] and not np.isnan(results[pop][freq]["correlation"]):
                plot_freqs.append(freq)
                plot_corrs.append(results[pop][freq]["correlation"])

        if len(plot_freqs) == 0:
            continue

        plot_freqs = np.array(plot_freqs)
        plot_corrs = np.array(plot_corrs)
        color = colors(i)

        plt.plot(
            plot_freqs, plot_corrs, marker="o", label=pop, linewidth=2, markersize=6, color=color
        )

    # Formatting
    plt.xlabel("Frequency (Hz)", fontsize=12)
    plt.ylabel("Spike Rate-Power Correlation", fontsize=12)

    plt.title(
        "Spike Rate-LFP Power Correlation",
        fontsize=14,
    )
    plt.grid(True, alpha=0.3)
    plt.axhline(y=0, color="gray", linestyle="-", alpha=0.5)

    # Setup legend
    from matplotlib.lines import Line2D

    legend_elements = [
        Line2D([0], [0], color=colors(i), marker="o", linestyle="-", label=pop)
        for i, pop in enumerate(pop_names)
    ]
    plt.legend(handles=legend_elements, fontsize=10, loc="best")

    # Axis formatting
    if len(frequencies) > 10:
        plt.xticks(frequencies[::2])
    else:
        plt.xticks(frequencies)
    plt.xlim(frequencies[0], frequencies[-1])

    y_min, y_max = plt.ylim()
    plt.ylim(min(y_min, -0.1), max(y_max, 0.1))

    plt.tight_layout()
    return fig

LFP Module

bmtool.bmplot.lfp.plot_spectrogram(sxx_xarray, remove_aperiodic=None, log_power=False, plt_range=None, clr_freq_range=None, pad=0.03, ax=None, vmin=None, vmax=None)

Plot a power spectrogram with optional aperiodic removal and frequency-based coloring.

Parameters:

Name Type Description Default
sxx_xarray array - like

Spectrogram data as an xarray DataArray with PSD values.

required
remove_aperiodic optional

FOOOF model object for aperiodic subtraction. If None, raw spectrum is displayed.

None
log_power bool or str

If True or 'dB', convert power to log scale. Default is False.

False
plt_range tuple of float

Frequency range to display as (f_min, f_max). If None, displays full range.

None
clr_freq_range tuple of float

Frequency range to use for determining color limits. If None, uses full range.

None
pad float

Padding for colorbar. Default is 0.03.

0.03
ax Axes

Axes to plot on. If None, creates a new figure and axes.

None
vmin float

Minimum value for colorbar scaling. If None, computed from data.

None
vmax float

Maximum value for colorbar scaling. If None, computed from data.

None

Returns:

Type Description
Figure

The figure object containing the spectrogram.

Examples:

>>> fig = plot_spectrogram(
...     sxx_xarray, log_power='dB',
...     plt_range=(10, 100), clr_freq_range=(20, 50)
... )
Source code in bmtool/bmplot/lfp.py
 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
def plot_spectrogram(
    sxx_xarray: Any,
    remove_aperiodic: Optional[Any] = None,
    log_power: bool = False,
    plt_range: Optional[Tuple[float, float]] = None,
    clr_freq_range: Optional[Tuple[float, float]] = None,
    pad: float = 0.03,
    ax: Optional[plt.Axes] = None,
    vmin: Optional[float] = None,
    vmax: Optional[float] = None,
) -> Figure:
    """
    Plot a power spectrogram with optional aperiodic removal and frequency-based coloring.

    Parameters
    ----------
    sxx_xarray : array-like
        Spectrogram data as an xarray DataArray with PSD values.
    remove_aperiodic : optional
        FOOOF model object for aperiodic subtraction. If None, raw spectrum is displayed.
    log_power : bool or str, optional
        If True or 'dB', convert power to log scale. Default is False.
    plt_range : tuple of float, optional
        Frequency range to display as (f_min, f_max). If None, displays full range.
    clr_freq_range : tuple of float, optional
        Frequency range to use for determining color limits. If None, uses full range.
    pad : float, optional
        Padding for colorbar. Default is 0.03.
    ax : matplotlib.axes.Axes, optional
        Axes to plot on. If None, creates a new figure and axes.
    vmin : float, optional
        Minimum value for colorbar scaling. If None, computed from data.
    vmax : float, optional
        Maximum value for colorbar scaling. If None, computed from data.

    Returns
    -------
    matplotlib.figure.Figure
        The figure object containing the spectrogram.

    Examples
    --------
    >>> fig = plot_spectrogram(
    ...     sxx_xarray, log_power='dB',
    ...     plt_range=(10, 100), clr_freq_range=(20, 50)
    ... )
    """
    sxx = sxx_xarray.PSD.values.copy()
    t = sxx_xarray.time.values.copy()
    f = sxx_xarray.frequency.values.copy()

    cbar_label = "PSD" if remove_aperiodic is None else "PSD Residual"
    if log_power:
        with np.errstate(divide="ignore"):
            sxx = np.log10(sxx)
        cbar_label += " dB" if log_power == "dB" else " log(power)"

    if remove_aperiodic is not None:
        f1_idx = 0 if f[0] else 1
        ap_fit = gen_aperiodic(f[f1_idx:], remove_aperiodic.aperiodic_params)
        sxx[f1_idx:, :] -= (ap_fit if log_power else 10**ap_fit)[:, None]
        sxx[:f1_idx, :] = 0.0

    if log_power == "dB":
        sxx *= 10

    if ax is None:
        _, ax = plt.subplots(1, 1)
    plt_range = np.array(f[-1]) if plt_range is None else np.array(plt_range)
    if plt_range.size == 1:
        plt_range = [f[0 if f[0] else 1] if log_power else 0.0, plt_range.item()]
    f_idx = (f >= plt_range[0]) & (f <= plt_range[1])

    # Determine vmin and vmax: explicit parameters take precedence, then clr_freq_range, then None
    if vmin is None:
        if clr_freq_range is not None:
            c_idx = (f >= clr_freq_range[0]) & (f <= clr_freq_range[1])
            vmin = sxx[c_idx, :].min()

    if vmax is None:
        if clr_freq_range is not None:
            c_idx = (f >= clr_freq_range[0]) & (f <= clr_freq_range[1])
            vmax = sxx[c_idx, :].max()

    f = f[f_idx]
    pcm = ax.pcolormesh(t, f, sxx[f_idx, :], shading="gouraud", vmin=vmin, vmax=vmax, rasterized=True)
    if "cone_of_influence_frequency" in sxx_xarray:
        coif = sxx_xarray.cone_of_influence_frequency
        ax.plot(t, coif)
        ax.fill_between(t, coif, step="mid", alpha=0.2)
    ax.set_xlim(t[0], t[-1])
    # ax.set_xlim(t[0],0.2)
    ax.set_ylim(f[0], f[-1])
    plt.colorbar(mappable=pcm, ax=ax, label=cbar_label, pad=pad)
    ax.set_xlabel("Time (sec)")
    ax.set_ylabel("Frequency (Hz)")
    return ax.figure