Analysis API Reference
This page provides API reference documentation for the Analysis module.
The Analysis module provides tools for processing and analyzing simulation results from BMTK models, including spike data and LFP/ECP data.
Spikes
The spikes
module provides functions for loading and analyzing spike data from simulations.
bmtool.analysis.spikes.load_spikes_to_df(spike_file, network_name, sort=True, config=None, groupby='pop_name')
Load spike data from an HDF5 file into a pandas DataFrame.
Args: spike_file (str): Path to the HDF5 file containing spike data. network_name (str): The name of the network within the HDF5 file from which to load spike data. sort (bool, optional): Whether to sort the DataFrame by 'timestamps'. Defaults to True. config (str, optional): Will label the cell type of each spike. groupby (str or list of str, optional): The column(s) to group by. Defaults to 'pop_name'.
Returns: pd.DataFrame: A pandas DataFrame containing 'node_ids' and 'timestamps' columns from the spike data.
Example: df = load_spikes_to_df("spikes.h5", "cortex")
Source code in bmtool/analysis/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 |
|
bmtool.analysis.spikes.compute_firing_rate_stats(df, groupby='pop_name', start_time=None, stop_time=None)
Computes the firing rates of individual nodes and the mean and standard deviation of firing rates per group.
Args: df (pd.DataFrame): Dataframe containing spike timestamps and node IDs. groupby (str or list of str, optional): Column(s) to group by (e.g., 'pop_name' or ['pop_name', 'layer']). start_time (float, optional): Start time for the analysis window. Defaults to the minimum timestamp in the data. stop_time (float, optional): Stop time for the analysis window. Defaults to the maximum timestamp in the data.
Returns:
Tuple[pd.DataFrame, pd.DataFrame]:
- The first DataFrame (pop_stats
) contains the mean and standard deviation of firing rates per group.
- The second DataFrame (individual_stats
) contains the firing rate of each individual node.
Source code in bmtool/analysis/spikes.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 |
|
bmtool.analysis.spikes._pop_spike_rate(spike_times, time=None, time_points=None, frequeny=False)
Calculate the spike count or frequency histogram over specified time intervals.
Args:
spike_times (Union[np.ndarray, list]): Array or list of spike times in milliseconds.
time (Optional[Tuple[float, float, float]], optional): Tuple specifying (start, stop, step) in milliseconds.
Used to create evenly spaced time points if time_points
is not provided. Default is None.
time_points (Optional[Union[np.ndarray, list]], optional): Array or list of specific time points for binning.
If provided, time
is ignored. Default is None.
frequeny (bool, optional): If True, returns spike frequency in Hz; otherwise, returns spike count. Default is False.
Returns:
np.ndarray: Array of spike counts or frequencies, depending on the frequeny
flag.
Raises:
ValueError: If both time
and time_points
are None.
Source code in bmtool/analysis/spikes.py
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 |
|
bmtool.analysis.spikes.get_population_spike_rate(spikes, fs=400.0, t_start=0, t_stop=None, config=None, network_name=None, save=False, save_path=None, normalize=False)
Calculate the population spike rate for each population in the given spike data, with an option to normalize.
Args:
spikes (pd.DataFrame): A DataFrame containing spike data with columns 'pop_name', 'timestamps', and 'node_ids'.
fs (float, optional): Sampling frequency in Hz, which determines the time bin size for calculating the spike rate. Default is 400.
t_start (float, optional): Start time (in milliseconds) for spike rate calculation. Default is 0.
t_stop (Optional[float], optional): Stop time (in milliseconds) for spike rate calculation. If None, defaults to the maximum timestamp in the data.
config (Optional[str], optional): Path to a configuration file containing node information, used to determine the correct number of nodes per population.
If None, node count is estimated from unique node spikes. Default is None.
network_name (Optional[str], optional): Name of the network used in the configuration file, allowing selection of nodes for that network.
Required if config
is provided. Default is None.
save (bool, optional): Whether to save the calculated population spike rate to a file. Default is False.
save_path (Optional[str], optional): Directory path where the file should be saved if save
is True. If save
is True and save_path
is None, a ValueError is raised.
normalize (bool, optional): Whether to normalize the spike rates for each population to a range of [0, 1]. Default is False.
Returns:
Dict[str, np.ndarray]: A dictionary where keys are population names, and values are arrays representing the spike rate over time for each population.
If normalize
is True, each population's spike rate is scaled to [0, 1].
Raises:
ValueError: If save
is True but save_path
is not provided.
Notes:
- If config
is None, the function assumes all cells in each population have fired at least once; otherwise, the node count may be inaccurate.
- If normalization is enabled, each population's spike rate is scaled using Min-Max normalization based on its own minimum and maximum values.
Source code in bmtool/analysis/spikes.py
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 |
|
LFP/ECP Analysis
The lfp
module provides tools for analyzing local field potentials (LFP) and extracellular potentials (ECP).
bmtool.analysis.lfp.load_ecp_to_xarray(ecp_file, demean=False)
Load ECP data from an HDF5 file (BMTK sim) into an xarray DataArray.
Parameters:
ecp_file : str Path to the HDF5 file containing ECP data. demean : bool, optional If True, the mean of the data will be subtracted (default is False).
Returns:
xr.DataArray An xarray DataArray containing the ECP data, with time as one dimension and channel_id as another.
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.ecp_to_lfp(ecp_data, cutoff=250, fs=10000, downsample_freq=1000)
Apply a low-pass Butterworth filter to an xarray DataArray and optionally downsample. This filters out the high end frequencies turning the ECP into a LFP
Parameters:
ecp_data : xr.DataArray The input data array containing LFP data with time as one dimension. cutoff : float The cutoff frequency for the low-pass filter in Hz (default is 250Hz). fs : float, optional The sampling frequency of the data (default is 10000 Hz). downsample_freq : float, optional The frequency to downsample to (default is 1000 Hz).
Returns:
xr.DataArray The filtered (and possibly downsampled) data as an xarray DataArray.
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.slice_time_series(data, time_ranges)
Slice the xarray DataArray based on provided time ranges. Can be used to get LFP during certain stimulus times
Parameters:
data : xr.DataArray The input xarray DataArray containing time-series data. time_ranges : tuple or list of tuples One or more tuples representing the (start, stop) time points for slicing. For example: (start, stop) or [(start1, stop1), (start2, stop2)]
Returns:
xr.DataArray A new xarray DataArray containing the concatenated slices.
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.fit_fooof(f, pxx, aperiodic_mode='fixed', dB_threshold=3.0, max_n_peaks=10, freq_range=None, peak_width_limits=None, report=False, plot=False, plt_log=False, plt_range=None, figsize=None, title=None)
Fit a FOOOF model to power spectral density data.
Parameters:
f : array-like Frequencies corresponding to the power spectral density data. pxx : array-like Power spectral density data to fit. aperiodic_mode : str, optional The mode for fitting aperiodic components ('fixed' or 'knee', default is 'fixed'). dB_threshold : float, optional Minimum peak height in dB (default is 3). max_n_peaks : int, optional Maximum number of peaks to fit (default is 10). freq_range : tuple, optional Frequency range to fit (default is None, which uses the full range). peak_width_limits : tuple, optional Limits on the width of peaks (default is None). report : bool, optional If True, will print fitting results (default is False). plot : bool, optional If True, will plot the fitting results (default is False). plt_log : bool, optional If True, use a logarithmic scale for the y-axis in plots (default is False). plt_range : tuple, optional Range for plotting (default is None). figsize : tuple, optional Size of the figure (default is None). title : str, optional Title for the plot (default is None).
Returns:
tuple A tuple containing the fitting results and the FOOOF model object.
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.generate_resd_from_fooof(fooof_model)
Generate residuals from a fitted FOOOF model.
Parameters:
fooof_model : FOOOF A fitted FOOOF model object.
Returns:
tuple A tuple containing the residual power spectral density and the aperiodic fit.
Source code in bmtool/analysis/lfp.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
|
bmtool.analysis.lfp.calculate_SNR(fooof_model, freq_band)
Calculate the signal-to-noise ratio (SNR) from a fitted FOOOF model.
Parameters:
fooof_model : FOOOF A fitted FOOOF model object. freq_band : tuple Frequency band (min, max) for SNR calculation.
Returns:
float The calculated SNR for the specified frequency band.
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.wavelet_filter(x, freq, fs, bandwidth=1.0, axis=-1)
Compute the Continuous Wavelet Transform (CWT) for a specified frequency using a complex Morlet wavelet.
Source code in bmtool/analysis/lfp.py
279 280 281 282 283 284 285 286 |
|
bmtool.analysis.lfp.butter_bandpass_filter(data, lowcut, highcut, fs, order=5, axis=-1)
Apply a Butterworth bandpass filter to the input data.
Source code in bmtool/analysis/lfp.py
289 290 291 292 293 294 295 |
|
bmtool.analysis.lfp.calculate_signal_signal_plv(x1, x2, fs, freq_of_interest=None, method='wavelet', lowcut=None, highcut=None, bandwidth=2.0)
Calculate Phase Locking Value (PLV) between two signals using wavelet or Hilbert method.
Parameters: - x1, x2: Input signals (1D arrays, same length) - fs: Sampling frequency - freq_of_interest: Desired frequency for wavelet PLV calculation - method: 'wavelet' or 'hilbert' to choose the PLV calculation method - lowcut, highcut: Cutoff frequencies for the Hilbert method - bandwidth: Bandwidth parameter for the wavelet
Returns: - plv: Phase Locking Value (1D array)
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.calculate_spike_lfp_plv(spike_times=None, lfp_signal=None, spike_fs=None, lfp_fs=None, method='hilbert', freq_of_interest=None, lowcut=None, highcut=None, bandwidth=2.0)
Calculate spike-lfp phase locking value Based on https://www.sciencedirect.com/science/article/pii/S1053811910000959
Parameters: - spike_times: Array of spike times - lfp_signal: Local field potential time series - spike_fs: Sampling frequency in Hz of the spike times only needed if spikes times and lfp has different fs - lfp_fs : Sampling frequency in Hz of the LFP - method: 'wavelet' or 'hilbert' to choose the phase extraction method - freq_of_interest: Desired frequency for wavelet phase extraction - lowcut, highcut: Cutoff frequencies for bandpass filtering (Hilbert method) - bandwidth: Bandwidth parameter for the wavelet
Returns: - ppc1: Phase-Phase Coupling value - spike_phases: Phases at spike times
Source code in bmtool/analysis/lfp.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 |
|
bmtool.analysis.lfp.calculate_ppc(spike_times=None, lfp_signal=None, spike_fs=None, lfp_fs=None, method='hilbert', freq_of_interest=None, lowcut=None, highcut=None, bandwidth=2.0, ppc_method='numpy')
Calculate Pairwise Phase Consistency (PPC) between spike times and LFP signal. Based on https://www.sciencedirect.com/science/article/pii/S1053811910000959
Parameters: - spike_times: Array of spike times - lfp_signal: Local field potential time series - spike_fs: Sampling frequency in Hz of the spike times only needed if spikes times and lfp has different fs - lfp_fs: Sampling frequency in Hz of the LFP - method: 'wavelet' or 'hilbert' to choose the phase extraction method - freq_of_interest: Desired frequency for wavelet phase extraction - lowcut, highcut: Cutoff frequencies for bandpass filtering (Hilbert method) - bandwidth: Bandwidth parameter for the wavelet - ppc_method: which algo to use for PPC calculate can be numpy, numba or gpu
Returns: - ppc: Pairwise Phase Consistency value
Source code in bmtool/analysis/lfp.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
|
bmtool.analysis.lfp.calculate_ppc2(spike_times=None, lfp_signal=None, spike_fs=None, lfp_fs=None, method='hilbert', freq_of_interest=None, lowcut=None, highcut=None, bandwidth=2.0)
-----------------------------------------------------------------------------
PPC2 Calculation (Vinck et al., 2010)
-----------------------------------------------------------------------------
Equation(Original):
PPC = (2 / (n * (n - 1))) * sum(cos(φ_i - φ_j) for all i < j)
Optimized Formula (Algebraically Equivalent):
PPC = (|sum(e^(i*φ_j))|^2 - n) / (n * (n - 1))
-----------------------------------------------------------------------------
Parameters: - spike_times: Array of spike times - lfp_signal: Local field potential time series - spike_fs: Sampling frequency in Hz of the spike times only needed if spikes times and lfp has different fs - lfp_fs: Sampling frequency in Hz of the LFP - method: 'wavelet' or 'hilbert' to choose the phase extraction method - freq_of_interest: Desired frequency for wavelet phase extraction - lowcut, highcut: Cutoff frequencies for bandpass filtering (Hilbert method) - bandwidth: Bandwidth parameter for the wavelet
Returns: - ppc2: Pairwise Phase Consistency 2 value - spike_phases: Phases at spike times
Source code in bmtool/analysis/lfp.py
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 |
|
bmtool.analysis.lfp.cwt_spectrogram(x, fs, nNotes=6, nOctaves=np.inf, freq_range=(0, np.inf), bandwidth=1.0, axis=-1, detrend=False, normalize=False)
Calculate spectrogram using continuous wavelet transform
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.cwt_spectrogram_xarray(x, fs, time=None, axis=-1, downsample_fs=None, channel_coords=None, **cwt_kwargs)
Calculate spectrogram using continuous wavelet transform and return an xarray.Dataset x: input array fs: sampling frequency (Hz) axis: dimension index of time axis in x downsample_fs: downsample to the frequency if specified channel_coords: dictionary of {coordinate name: index} for channels cwt_kwargs: keyword arguments for cwt_spectrogram()
Source code in bmtool/analysis/lfp.py
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 |
|
bmtool.analysis.lfp.plot_spectrogram(sxx_xarray, remove_aperiodic=None, log_power=False, plt_range=None, clr_freq_range=None, pad=0.03, ax=None)
Plot spectrogram. Determine color limits using value in frequency band clr_freq_range
Source code in bmtool/analysis/lfp.py
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 |
|