### Get Started with Quality Metrics Pipeline Source: https://github.com/julie-fabre/bombcell/wiki/Important-changes-log Refer to the example script `bc_qualityMetrics_pipeline.m` to begin using the new module for computing ephys parameters and classifying units. ```matlab bc_qualityMetrics_pipeline.m ``` -------------------------------- ### Install Bombcell via MATLAB Source: https://context7.com/julie-fabre/bombcell/llms.txt Setup steps for adding dependencies to the MATLAB path and compiling the MEX file for fast ACGs. ```matlab % Clone the repository and dependencies: % - bombcell: https://github.com/Julie-Fabre/bombcell % - npy-matlab: https://github.com/kwikteam/npy-matlab % - prettify-matlab: https://github.com/Julie-Fabre/prettify_matlab % Add to MATLAB path addpath(genpath('path/to/bombcell')) addpath(genpath('path/to/npy-matlab')) % Compile MEX file for fast ACGs (optional, for ephys properties) cd('bombcell/+bc/+ep/+helpers') mex -O CCGHeart.c ``` -------------------------------- ### Install Bombcell Development Version Source: https://github.com/julie-fabre/bombcell/wiki/Installation Commands to clone the repository and install the development version in editable mode. ```bash conda create -n bombcell python=3.11 conda activate bombcell git clone https://github.com/Julie-Fabre/bombcell.git cd bombcell/py_bombcell pip install uv uv pip install -e . ``` -------------------------------- ### Install Bombcell via Python Source: https://context7.com/julie-fabre/bombcell/llms.txt Commands to set up a conda environment and install the package using pip or from source. ```bash # Create a conda environment conda create -n bombcell python=3.11 conda activate bombcell # Install bombcell via pip with uv (faster) pip install uv uv pip install bombcell # Or install the development version git clone https://github.com/Julie-Fabre/bombcell.git cd bombcell/py_bombcell uv pip install -e . ``` -------------------------------- ### Install Bombcell via Python Source: https://github.com/julie-fabre/bombcell/wiki/Installation Commands to create a conda environment and install the stable version of Bombcell using uv. ```bash conda create -n bombcell python=3.11 conda activate bombcell pip install uv uv pip install bombcell # you could do `pip install .`, but uv is much quicker! ``` -------------------------------- ### Install Bombcell via CLI Source: https://github.com/julie-fabre/bombcell/blob/main/README.md Commands to set up a Conda environment and install the Bombcell package. ```bash # Create a conda environment conda create -n bombcell python=3.11 conda activate bombcell # Install bombcell pip install uv uv pip install bombcell # you could do `pip install .`, but uv is much quicker! ``` ```bash # Create a conda environment conda create -n bombcell python=3.11 conda activate bombcell # Clone latest bombcell repository from github git clone https://github.com/Julie-Fabre/bombcell.git cd bombcell/py_bombcell # Install bombcell pip install uv uv pip install -e . ``` -------------------------------- ### Install Development Version of Bombcell Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/README.md Installs the development version of Bombcell from a git repository, enabling local modifications. ```bash conda create -n bombcell python=3.11 conda activate bombcell git clone https://github.com/Julie-Fabre/bombcell.git cd bombcell/pyBombCell pip install uv uv pip install -e . ``` -------------------------------- ### Get default bombcell parameters Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_other_recording_software.ipynb Initialize default analysis parameters, optionally providing raw and meta file paths for Neuropixels probes. ```python ## For Neuropixels probes, provide raw and meta files ## Leave 'None' if no raw data. Ideally, your raw data is common-average-referenced and # the channels are temporally aligned to each other (this can be done with CatGT) raw_file_path = None # CHANGE to e.g. "/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0_bc_decompressed.imec0.ap.bin" # ks_dir meta_file_path = None # CHANGE to e.g. "/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0.imec0.ap.meta" ## Get default parameters - we will see later in the notebook how to assess and fine-tune these param = bc.get_default_parameters(ks_dir, raw_file=raw_file_path, meta_file=meta_file_path, kilosort_version=4) print("Bombcell parameters:") pprint(param) ``` -------------------------------- ### Get BombCell Version Source: https://github.com/julie-fabre/bombcell/wiki/Publishing-your-results Print the installed version of the BombCell library. This is useful for ensuring reproducibility and documenting the analysis environment. ```python import bombcell print(bombcell.__version__) ``` -------------------------------- ### Pipeline Console Output Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_other_recording_software.ipynb Example console output during the execution of the BombCell pipeline. ```text Output: 🚀 Starting BombCell quality metrics pipeline... 📁 Processing data from: toy_data Results will be saved to: toy_data/bombcell Loading ephys data... Loaded ephys data: 15 units, 94,565 spikes ⚙️ Computing quality metrics for 15 units... (Progress bar will appear below) ``` ```text Result: Computing bombcell quality metrics: 0%| | 0/15 units ``` ```text Output: Saving GUI visualization data... GUI visualization data saved to: toy_data/bombcell/for_GUI/gui_data.pkl Generated spatial decay fits: 15/15 units Generated amplitude fits: 11/15 units 🏷️ Classifying units (good/MUA/noise/non-soma)... Generating summary plots... ``` ```text Result:
``` ```text Result:
``` ```text Result:
``` ```text Result:
``` ```text Result:
``` ```text Output: Saving results... 📁 Saving TSV files to Kilosort directory: toy_data All expected metrics were successfully saved. ``` -------------------------------- ### Get UnitMatch Optimized Parameters Source: https://context7.com/julie-fabre/bombcell/llms.txt Retrieves parameters optimized for UnitMatch, a spike sorting algorithm. Ensure kilosort_path, raw_file, and meta_file are correctly specified. ```python kilosort_path = '/path/to/session1/kilosort' raw_file = '/path/to/session1/raw_data.ap.bin' meta_file = '/path/to/session1/raw_data.ap.meta' param = bc.get_unit_match_parameters( kilosort_path=kilosort_path, raw_file=raw_file, meta_file=meta_file, kilosort_version=4 ) ``` -------------------------------- ### Install Latest Stable Bombcell Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/README.md Installs the latest stable version of Bombcell using conda and pip with uv for faster package management. ```bash conda create -n bombcell python=3.11 conda activate bombcell pip install uv uv pip install bombcell ``` -------------------------------- ### Get Default Bombcell Parameters Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Retrieves the default parameters for the Bombcell pipeline. These parameters can be fine-tuned later. Ensure ks_dir, raw_file_path, meta_file_path, and kilosort_version are correctly set. ```python param = bc.get_default_parameters(ks_dir, raw_file=raw_file_path, meta_file=meta_file_path, kilosort_version=4) print("Bombcell parameters:") pprint(param) ``` -------------------------------- ### Get Default Bombcell Parameters Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_spikeGLX.ipynb Retrieves the default parameters for Bombcell analysis. These parameters can be fine-tuned later. Requires specifying the Kilosort directory and raw/meta file paths. ```python param = bc.get_default_parameters(ks_dir, raw_file=raw_file_path, meta_file=meta_file_path, kilosort_version=4) ``` -------------------------------- ### Launch the MATLAB GUI Source: https://github.com/julie-fabre/bombcell/wiki/Guide-to-bombcell's-GUI Initialize the synced unit quality GUI using the provided electrophysiological data and parameters. ```matlab bc.viz.unitQualityGUI_synced(memMapData, ephysData, qMetrics, param, probeLocation, unitType, plotRaw) ``` -------------------------------- ### Launch minimal GUI Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Initializes the minimal GUI for visual inspection of unit data and metrics. ```python # Launch minimal GUI. # Ideally, take a look at your units for a few datasets so you can get an idea of which ``` -------------------------------- ### Set up ephys properties demonstration Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Initializes the directory paths for processing Kilosort data. ```python # Use the real dataset for ephys properties demonstration ks_dir = "toy_data" save_path = Path(ks_dir) / "bombcell" print(f"Using kilosort directory: {ks_dir}") ``` -------------------------------- ### Basic Python Bombcell Workflow Source: https://github.com/julie-fabre/bombcell/wiki/Overview-of-quality-metrics-and-options Sets up parameters, runs bombcell analysis, and launches the GUI. Ensure paths for kilosort output, raw data, and meta files are correctly specified. ```python import bombcell as bc # 1. Set up parameters param = bc.get_default_parameters( kilosort_path='/path/to/kilosort/output', raw_file='/path/to/raw_data.ap.bin', # optional: for raw waveform extraction meta_file='/path/to/raw_data.ap.meta', # optional: for gain/sampling rate kilosort_version=4 # 4 for KS4, else for earlier versions ) # 2. Run bombcell (extracts waveforms, computes metrics, classifies units) quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir='/path/to/kilosort/output', save_path='/path/to/save/results', param=param ) # 3. Explore results with the GUI bc.unit_quality_gui( kilosort_path='/path/to/kilosort/output', save_path='/path/to/save/results' ) ``` -------------------------------- ### Launch Phy GUI Source: https://github.com/julie-fabre/bombcell/wiki/Compatibility-with-phy Launch the Phy template GUI with your Kilosort parameters file to view Bombcell quality metrics. ```bash phy template-gui /path/to/kilosort/params.py ``` -------------------------------- ### Launch UnitMatch GUI in Python Source: https://github.com/julie-fabre/bombcell/wiki/Running-BombCell-and-UnitMatch Opens the interactive GUI for manual curation of matched units. ```python # Launch UnitMatch GUI for manual curation um.launch_gui(session_paths, prob_matrix, clus_info) ``` -------------------------------- ### Configure Raw Data Parameters Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_other_recording_software.ipynb Set up the raw file path and ephys recording parameters before running the pipeline. ```python raw_file_path = "" # CHANGE .bin, .dat... # Get default parameters - we will see later in the notebook how to assess and fine-tune these gain_to_uV = 0 # CHANGE to the scaling factor needed to convert your raw data to microvolts param = bc.get_default_parameters(ks_dir, raw_file=raw_file_path, meta_file=meta_file_path, gain_to_uV=gain_to_uV) # Raw data parameters: !WARNING! if you modify any of these after having already run bombcell, you # will need to set 'reextractRaw' to true to update the raw waveforms param["ephys_sampling_rate"] = 30000 # CHANGE param["nChannels"] = 385 # CHANGE to the TOTAL number of recorded channels (including any sync channels). param["nSyncChannels"] = 1 # CHANGE to the number of recorded sync channels. Usually 1 or 0 param["reextractRaw"] = 0 # if bombcell has already been run (with some incorrect ephys settings), whether to # re-extract the raw waveforms with the updated seetings ``` -------------------------------- ### Run Quality Metrics and Ephys Properties in Python Source: https://github.com/julie-fabre/bombcell/wiki/Classifying-cell-types Initializes parameters and computes quality metrics and electrophysiological properties for units. ```python import bombcell as bc from bombcell.ephys_properties import run_all_ephys_properties kilosort_path = '/path/to/kilosort/output' save_path = '/path/to/save/results' # Run quality metrics param = bc.get_default_parameters(kilosort_path, raw_file, meta_file) quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir=kilosort_path, save_path=save_path, param=param ) # Run ephys properties ephys_properties, ephys_param = run_all_ephys_properties( kilosort_path, param=param, save_path=save_path ) ``` -------------------------------- ### Customize Waveform-based Thresholds Source: https://context7.com/julie-fabre/bombcell/llms.txt Adjusts waveform-based thresholds for noise classification. For example, `maxNPeaks` can be increased for complex spikes in regions like the cerebellum. ```python param["maxNPeaks"] = 2 # Increase for complex spikes (cerebellum) param["maxNTroughs"] = 1 param["minWvDuration"] = 100 # µs param["maxWvDuration"] = 1150 # µs param["maxWvBaselineFraction"] = 0.3 ``` -------------------------------- ### Launch Interactive Unit Exploration GUI Source: https://context7.com/julie-fabre/bombcell/llms.txt Launch a GUI to browse units and manually classify them. Manual classifications are saved to CSV files. ```python import bombcell as bc # Option 1: Quick launch from paths (loads everything automatically) gui = bc.unit_quality_gui( ks_dir='/path/to/kilosort/output', save_path='/path/to/bombcell/output' ) # Option 2: Launch after running bombcell with existing data quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir=kilosort_path, save_path=save_path, param=param ) gui = bc.unit_quality_gui( ks_dir=kilosort_path, quality_metrics=quality_metrics, unit_types=unit_type, param=param, save_path=save_path ) # Manual classification system # Use GUI buttons to classify units as: Noise, Good, MUA, or Non-somatic # Classifications are auto-saved to: # - manual_unit_classifications.csv # - manual_vs_bombcell_classifications.csv # Compare manual vs automatic classifications bc.compare_manual_vs_bombcell('/path/to/bombcell/output') # Outputs: concordance statistics, confusion matrix, parameter suggestions ``` ```matlab % MATLAB: Launch synced GUI windows % First load data and run metrics, then: unitQualityGuiHandle = bc.viz.unitQualityGUI_synced(memMapData, ephysData, ... qMetric, forGUI, rawWaveforms, param, probeLocation, unitType, loadRawTraces); % Keyboard shortcuts: % ← / → : Previous / Next unit % g : Next good unit % m : Next multi-unit % n : Next noise unit % a : Next non-somatic unit % u : Go to specific unit ``` -------------------------------- ### Get Quality Unit Types After Parameter Update Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_test.ipynb After updating classification parameters, use this function to re-evaluate and obtain the quality unit types based on the new thresholds. ```python unit_type, unit_type_string = bc.qm.get_quality_unit_type( param, quality_metrics ) ``` -------------------------------- ### Initialize BombCell Unit Quality GUI Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Initializes the GUI for unit quality analysis. Requires paths to kilosort data and save location, along with quality metrics, unit types, and parameters. ```python gui = bc.unit_quality_gui( ks_dir=ks_dir, quality_metrics=quality_metrics, unit_types=unit_type, param=param, save_path=save_path, ) ``` -------------------------------- ### Initialize bombcell environment Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_methods_generation.ipynb Load autoreload extension and import the bombcell package. ```python %load_ext autoreload %autoreload 2 import bombcell as bc from pathlib import Path ``` -------------------------------- ### Specify Raw and Meta File Paths Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Defines the file paths for raw electrophysiology data and its associated metadata. Leave as 'None' if raw data is not available or not needed for the current analysis step. Assumes raw data is common-average-referenced and temporally aligned. ```python ## Provide raw and meta files ## Leave 'None' if no raw data. Ideally, your raw data is common-average-referenced and # the channels are temporally aligned to each other (this can be done with CatGT) raw_file_path = None # "/home/jf5479/cup/Julie/from_Yunchang/20250411_4423_antibody_maze_C1/CatGT_out/catgt_20250411_4423_C1_g0/20250411_4423_C1_g0_imec0/20250411_4423_C1_g0_tcat.imec0.ap.bin" #None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0_bc_decompressed.imec0.ap.bin" # ks_dir meta_file_path = None # "/home/jf5479/cup/Julie/from_Yunchang/20250411_4423_antibody_maze_C1/CatGT_out/catgt_20250411_4423_C1_g0/20250411_4423_C1_g0_imec0/20250411_4423_C1_g0_tcat.imec0.ap.meta" #None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0_bc_decompressed.imec0.ap.bin"None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0.imec0.ap.meta" ``` -------------------------------- ### Add Bombcell to Python Path (Optional) Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Conditionally adds the bombcell directory to the Python path if the package is not installed via pip. This is useful when working with the development version directly from the repository. ```python # Optional # # Add bombcell to Python path if NOT installed with pip # # If notebook is running in bombcell repo: # demo_dir = Path(os.getcwd()) # pyBombCell_dir = demo_dir.parent # # Else: # # pyBombCell_dir = "path/to/bombcell/repository/root" # sys.path.append(str(pyBombCell_dir)) ``` -------------------------------- ### Create and format quality metrics DataFrame Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Initializes a DataFrame from quality metrics and inserts a unit type column at the beginning. ```python quality_metrics_table = pd.DataFrame(quality_metrics) quality_metrics_table.insert(0, 'Bombcell_unit_type', unit_type_string) quality_metrics_table ``` -------------------------------- ### Configure BombCell parameters Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_methods_generation.ipynb Initialize analysis parameters by loading existing results or setting defaults for a new Kilosort directory. Customize specific metrics like refractory period thresholds and drift computation as needed. ```python # Option A: Load saved parameters from a previous BombCell run # save_path = Path("/path/to/your/kilosort_dir/bombcell") # param, quality_metrics, _ = bc.load_bc_results(save_path) # Option B: Use parameters you've configured in this session ks_dir = "/tmp/placeholder" # Replace with your kilosort directory param = bc.get_default_parameters(ks_dir, kilosort_version=4) # Customize parameters as you would for your analysis param["tauR_valuesMin"] = 0.5 / 1000 param["tauR_valuesMax"] = 5 / 1000 param["tauR_valuesStep"] = 0.5 / 1000 param["computeDrift"] = True param["computeDistanceMetrics"] = False param["computeTimeChunks"] = True param["maxRPVviolations"] = 0.1 param["minAmplitude"] = 50 ``` -------------------------------- ### Launch Bombcell GUI Source: https://github.com/julie-fabre/bombcell/wiki/Guide-to-bombcell's-GUI Initialize the interactive unit quality GUI using various data loading methods. ```python import bombcell as bc # Option 1: Quick launch from kilosort path (auto-loads everything) gui = bc.unit_quality_gui(ks_dir='/path/to/kilosort/output', save_path='/path/to/bombcell/output') # Option 2: After running bombcell quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell(ks_dir, save_path, param) gui = bc.unit_quality_gui(ks_dir, quality_metrics=quality_metrics, unit_types=unit_type, param=param, save_path=save_path) # Option 3: With pre-computed data for faster loading gui_data = bc.precompute_gui_data(ephys_data, quality_metrics, param, save_path) gui = bc.InteractiveUnitQualityGUI(ephys_data, quality_metrics, param=param, gui_data=gui_data, save_path=save_path) ``` -------------------------------- ### Configure Data Directories Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Sets the input directory for Kilosort data and the output directory for Bombcell processing. Ensure 'ks_dir' points to your actual data location. ```python # Replace with your kilosort directory ks_dir = "toy_data" # Set bombcell's output directory save_path = Path(ks_dir) / "bombcell" print(f"Using kilosort directory: {ks_dir}") ``` -------------------------------- ### Launch Minimal GUI for Data Inspection Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_spikeGLX.ipynb Launches a minimal GUI for visual inspection of neural data and quality metrics. This is useful for exploring units across different datasets. ```python # Launch minimal GUI. # Ideally, take a look at your units for a few datasets so you can get an idea of which ``` -------------------------------- ### Specify Raw and Meta File Paths Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_open_ephys.ipynb Defines the file paths for raw electrophysiology data and its corresponding metadata. These files are crucial for the quality metrics analysis. Leave as 'None' if not applicable. ```python ## Provide raw and meta files ## Leave 'None' if no raw data. Ideally, your raw data is common-average-referenced and # the channels are temporally aligned to each other (this can be done with CatGT) raw_file_path = "/media/jf5479/5deca505-bbd3-4bef-8951-7b6189e3c708/Hajime/Hajime_NPX-20251201T183410Z-1-001/Hajime_NPX/continuous_Hajime.dat" #None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0_bc_decompressed.imec0.ap.bin" # ks_dir meta_file_path = "/media/jf5479/5deca505-bbd3-4bef-8951-7b6189e3c708/Hajime/Hajime_NPX-20251201T183410Z-1-001/Hajime_NPX/structure.oebin" #None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0_bc_decompressed.imec0.ap.bin"None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0.imec0.ap.meta" ``` -------------------------------- ### Define raw and meta file paths Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_test.ipynb Specify paths to the raw binary and metadata files for Neuropixels probes. ```python ## For Neuropixels probes, provide raw and meta files ## Leave 'None' if no raw data. Ideally, your raw data is common-average-referenced and # the channels are temporally aligned to each other (this can be done with CatGT) raw_file_path = "/home/jf5479/cup/Julie/from_Yunchang/20250411_4423_antibody_maze_C1/CatGT_out/catgt_20250411_4423_C1_g0/20250411_4423_C1_g0_imec0/20250411_4423_C1_g0_tcat.imec0.ap.bin" #None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0_bc_decompressed.imec0.ap.bin" # ks_dir meta_file_path = "/home/jf5479/cup/Julie/from_Yunchang/20250411_4423_antibody_maze_C1/CatGT_out/catgt_20250411_4423_C1_g0/20250411_4423_C1_g0_imec0/20250411_4423_C1_g0_tcat.imec0.ap.meta" #None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0_bc_decompressed.imec0.ap.bin"None#"/home/julie/Dropbox/Example datatsets/JF093_2023-03-09_site1/site1/2023-03-09_JF093_g0_t0.imec0.ap.meta" ``` -------------------------------- ### Load Saved Results in Python Source: https://context7.com/julie-fabre/bombcell/llms.txt Import utility for loading previously computed quality metrics. ```python import bombcell as bc from bombcell.loading_utils import load_saved_metrics ``` -------------------------------- ### Configure Parameter Function for Non-Standard Software Source: https://github.com/julie-fabre/bombcell/wiki/Important-changes-log When using software other than spikeGLX or OpenEphys, set ephysMetaDir to '' and gain_to_uV to your specific value (e.g., 0.195 for Intan data). ```matlab param = bc_qualityParamValues(ephysMetaDir, rawFile, ephysKilosortPath, gain_to_uV); ``` ```matlab ephysMetaDir = ''; ``` ```matlab gain_to_uV = 0.195; ``` -------------------------------- ### Configure Paths for Analysis Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_open_ephys.ipynb Sets the directory for Kilosort output and the desired output directory for bombcell analysis. Ensure these paths are correctly set for your data. ```python # Replace with your kilosort directory ks_dir = "/media/jf5479/5deca505-bbd3-4bef-8951-7b6189e3c708/Hajime/Hajime_NPX-20251201T183410Z-1-001/Hajime_NPX/" # Set bombcell's output directory save_path = Path(ks_dir) / "bombcell" print(f"Using kilosort directory: {ks_dir}") ``` -------------------------------- ### Run Quality Metrics in Python Source: https://context7.com/julie-fabre/bombcell/llms.txt Main workflow for computing quality metrics and classifying units using the Python API. ```python import bombcell as bc # Set up paths kilosort_path = '/path/to/kilosort/output' raw_file = '/path/to/raw_data.ap.bin' meta_file = '/path/to/raw_data.ap.meta' save_path = '/path/to/save/results' # Get default parameters (adjust for KS2/3 by setting kilosort_version=2) param = bc.get_default_parameters( kilosort_path=kilosort_path, raw_file=raw_file, meta_file=meta_file, kilosort_version=4 ) # Optional: customize thresholds for your brain region param["minAmplitude"] = 30 # µV - tune based on your data param["maxRPVviolations"] = 0.1 # 10% refractory period violations max param["minPresenceRatio"] = 0.7 # Present in 70% of recording param["plotGlobal"] = True # Generate summary plots # Run bombcell - extracts waveforms, computes metrics, classifies units quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir=kilosort_path, save_path=save_path, param=param ) # Access results print(f"Total units: {len(unit_type)}") print(f"Good units: {sum(unit_type_string == 'GOOD')}") print(f"MUA units: {sum(unit_type_string == 'MUA')}") print(f"Noise units: {sum(unit_type_string == 'NOISE')}") print(f"Non-somatic units: {sum(unit_type_string == 'NON-SOMA')}") # Access individual quality metrics print(f"\nFraction RPV violations: {quality_metrics['fractionRPVs_estimatedTauR'][:5]}") print(f"Raw amplitudes (µV): {quality_metrics['rawAmplitude'][:5]}") print(f"Waveform durations (µs): {quality_metrics['waveformDuration_peakTrough'][:5]}") ``` -------------------------------- ### Apply Suggested Parameter Changes Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_toy_data.ipynb Demonstrates how to apply suggested parameter changes for BombCell based on classification analysis. This involves loading parameters, updating them, and re-running BombCell. ```python # Example: param['minNumSpikes'] = 75 ``` -------------------------------- ### Export methods and bibliography with save_methods_text Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_methods_generation.ipynb Use this function to generate a .txt file containing methods and references, along with a corresponding .bib file. Optionally include quality metrics to append a unit count summary to the output. ```python # Save methods text (.txt) and BibTeX (.bib) to disk # save_dir = Path("/path/to/your/output") # bc.save_methods_text(param, save_dir / "bombcell_methods.txt") # # This creates: # # bombcell_methods.txt - methods paragraph + formatted references # # bombcell_methods.bib - BibTeX entries for your bibliography # If you also have quality_metrics loaded, pass them in for a unit count summary: # bc.save_methods_text(param, save_dir / "bombcell_methods.txt", quality_metrics=quality_metrics) ``` -------------------------------- ### BombCell GUI Output and Initialization Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_other_recording_software.ipynb Displays the output messages from loading GUI data, including auto-loaded data and successful loading confirmation. It also lists available data types and classification statistics. ```text Loaded GUI data from: toy_data/bombcell/for_GUI/gui_data.pkl 🚀 Auto-loaded GUI data from: toy_data/bombcell/for_GUI/gui_data.pkl GUI data loaded successfully! Data types available: ['peak_locations', 'trough_locations', 'peak_loc_for_duration', 'trough_loc_for_duration', 'peak_trough_labels', 'duration_lines', 'spatial_decay_fits', 'amplitude_fits', 'channel_arrangements', 'waveform_scaling', 'acg_data', 'per_bin_metrics'] Peak/trough detection: 15 units Spatial decay fits: 15 units Amplitude fits: 11 units Total units: 15 📝 Initialized manual classification system (no previous classifications found) 🚀 Auto-advance enabled: will automatically go to next unit after classification ``` -------------------------------- ### Set Kilosort and output directories Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_test.ipynb Define the path to the Kilosort output directory and the location for bombcell results. ```python # Replace with your kilosort directory ks_dir = "/home/jf5479/cup/Julie/from_Yunchang/20250411_4423_antibody_maze_C1/CatGT_out/catgt_20250411_4423_C1_g0/20250411_4423_C1_g0_imec0/imec0_ks4" # Set bombcell's output directory save_path = Path(ks_dir) / "bombcell" print(f"Using kilosort directory: {ks_dir}") ``` -------------------------------- ### Load and Filter Quality Metrics Source: https://context7.com/julie-fabre/bombcell/llms.txt Load saved metrics from a previous run and filter units based on amplitude thresholds. ```python # Load saved metrics from previous run param, quality_metrics = load_saved_metrics('/path/to/bombcell/output') # Access all quality metrics as a dictionary print(quality_metrics.keys()) # dict_keys(['nPeaks', 'nTroughs', 'waveformDuration_peakTrough', # 'spatialDecaySlope', 'fractionRPVs_estimatedTauR', # 'percentageSpikesMissing_gaussian', 'presenceRatio', # 'rawAmplitude', 'signalToNoiseRatio', ...]) # Filter to good units only good_mask = quality_metrics['rawAmplitude'] > param['minAmplitude'] print(f"Units with amplitude > {param['minAmplitude']} µV: {sum(good_mask)}") ``` ```matlab % MATLAB: Load saved metrics [param, qMetric] = bc.load.loadSavedMetrics(savePath); % Access metrics disp(fieldnames(qMetric)); goodUnits = qMetric.rawAmplitude > param.minAmplitude; fprintf('Units with amplitude > %d µV: %d\n', param.minAmplitude, sum(goodUnits)); ``` -------------------------------- ### Enable Phy Integration in Python Source: https://github.com/julie-fabre/bombcell/wiki/Compatibility-with-phy Enable saving quality metrics as TSV files and unit classifications for Phy. These parameters are enabled by default. ```python # These are enabled by default param["saveAsTSV"] = True # Save quality metrics as TSV files param["unit_type_for_phy"] = True # Save unit classifications for Phy ``` -------------------------------- ### Generate Methods Text with Different Citation Styles Source: https://github.com/julie-fabre/bombcell/wiki/Publishing-your-results Demonstrates generating methods text with either author-year inline citations or numbered citations. Ensure 'param' is loaded. ```python # Author-year style: (Fabre et al., 2023) generate_methods_text(param, citation_style="inline") ``` ```python # Numbered style: [1], [2], [3] generate_methods_text(param, citation_style="numbered") ``` -------------------------------- ### Generate methods text with default parameters Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_methods_generation.ipynb Retrieve default parameters to generate methods text without requiring external data. ```python # Get default parameters (no data needed) param = bc.get_default_parameters("/tmp/placeholder") ``` -------------------------------- ### MATLAB Unit Quality GUI Source: https://github.com/julie-fabre/bombcell/wiki/Overview-of-quality-metrics-and-options Initializes and displays the synced unit quality GUI in MATLAB. This function requires various data structures and parameters from the preceding analysis steps. ```matlab unitQualityGuiHandle = bc.viz.unitQualityGUI_synced(memMapData, ephysData, qMetric, forGUI, ... rawWaveforms, param, probeLocation, unitType, loadRawTraces) ``` -------------------------------- ### Run Quality Metrics in MATLAB Source: https://context7.com/julie-fabre/bombcell/llms.txt Main workflow for computing quality metrics and classifying units using the MATLAB API. ```matlab % Set up paths ephysKilosortPath = '/path/to/kilosort/output'; ephysRawPath = '/path/to/raw_data.ap.bin'; ephysMetaPath = '/path/to/raw_data.ap.meta'; savePath = '/path/to/save/results'; % Load ephys data from Kilosort output [spikeTimes_samples, spikeTemplates, templateWaveforms, templateAmplitudes, ... pcFeatures, pcFeatureIdx, channelPositions] = bc.load.loadEphysData(ephysKilosortPath); % Get default parameters (reads metadata from .meta file) param = bc.qm.qualityParamValues(ephysMetaPath, ephysRawPath, ephysKilosortPath); % Customize thresholds param.minAmplitude = 30; % µV param.maxRPVviolations = 0.1; % 10% param.plotGlobal = 1; % Generate summary plots % Run all quality metrics and classify units [qMetric, unitType] = bc.qm.runAllQualityMetrics(param, spikeTimes_samples, ... spikeTemplates, templateWaveforms, templateAmplitudes, pcFeatures, ... pcFeatureIdx, channelPositions, savePath); % Access results fprintf('Total units: %d\n', length(unitType)); fprintf('Good units: %d\n', sum(unitType == 1)); fprintf('MUA units: %d\n', sum(unitType == 2)); fprintf('Noise units: %d\n', sum(unitType == 0)); % Access individual metrics disp(qMetric.fractionRPVs_estimatedTauR(1:5)); disp(qMetric.rawAmplitude(1:5)); ``` -------------------------------- ### Save Methods Text to File Source: https://github.com/julie-fabre/bombcell/wiki/Publishing-your-results Save the generated methods text to a .txt file and corresponding .bib file for references. Requires specifying the output file path. ```python save_methods_text(param, '/path/to/methods_section.txt', quality_metrics) ``` -------------------------------- ### Run BombCell with UnitMatch-optimized parameters in Python Source: https://github.com/julie-fabre/bombcell/wiki/Running-BombCell-and-UnitMatch Configures BombCell for UnitMatch compatibility using get_unit_match_parameters and executes the quality metrics pipeline. ```python import bombcell as bc # For each recording session: kilosort_path = '/path/to/session1/kilosort' raw_file = '/path/to/session1/raw_data.ap.bin' meta_file = '/path/to/session1/raw_data.ap.meta' # Get UnitMatch-optimized parameters param = bc.get_unit_match_parameters( kilosort_path=kilosort_path, raw_file=raw_file, meta_file=meta_file, kilosort_version=4 ) # Run BombCell quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir=kilosort_path, save_path=kilosort_path, # Save in Kilosort folder for UnitMatch param=param ) ``` -------------------------------- ### Run UnitMatch in MATLAB Source: https://github.com/julie-fabre/bombcell/wiki/Running-BombCell-and-UnitMatch Executes the UnitMatch algorithm across multiple Kilosort session directories. ```matlab % Set up paths for all sessions KilosortPaths = { 'path/to/session1/kilosort'; 'path/to/session2/kilosort'; 'path/to/session3/kilosort' }; % Get default parameters UMparam = DefaultParametersUnitMatch; UMparam.KSDir = KilosortPaths; % Run UnitMatch [UniqueIDConversion, MatchTable] = UnitMatch(UMparam); ``` -------------------------------- ### Run UnitMatch cross-session tracking in Python Source: https://github.com/julie-fabre/bombcell/wiki/Running-BombCell-and-UnitMatch Loads waveforms from BombCell outputs and performs unit matching across multiple sessions. ```python import UnitMatchPy as um import numpy as np # Define paths to all sessions session_paths = [ '/path/to/session1/kilosort', '/path/to/session2/kilosort', '/path/to/session3/kilosort', ] # Load waveforms from BombCell outputs waveforms = [] for path in session_paths: raw_waveforms = np.load(f'{path}/RawWaveforms/templates._bc_rawWaveforms.npy') waveforms.append(raw_waveforms) # Set up UnitMatch parameters param = um.get_default_param() param['kilosort_dirs'] = session_paths # Load cluster info clus_info = um.load_cluster_info(session_paths) # Load channel positions channel_pos = um.load_channel_positions(session_paths) # Extract waveform parameters waveform_array = np.concatenate(waveforms, axis=0) extracted_props = um.extract_parameters(waveform_array, channel_pos, clus_info, param) # Calculate matching scores session_switch = um.get_session_switch(clus_info) within_session = um.get_within_session(clus_info) total_score, candidate_pairs, scores, predictors = um.extract_metric_scores( extracted_props, session_switch, within_session, param ) # Run probability model prob_matrix = um.run_probability_model(total_score, candidate_pairs, param) # Assign unique IDs to matched units unique_ids = um.assign_unique_id(prob_matrix, clus_info, param) ``` -------------------------------- ### Customize Presence and Spike Count Thresholds Source: https://context7.com/julie-fabre/bombcell/llms.txt Sets thresholds for spike presence ratio and minimum number of spikes. `presenceRatioBinSize` defines the time window in seconds for calculating the presence ratio. ```python # Presence and spike count param["minPresenceRatio"] = 0.7 # Present in 70% of recording param["minNumSpikes"] = 300 # Minimum total spikes param["presenceRatioBinSize"] = 60 # Seconds per bin ``` -------------------------------- ### Enable Phy Integration Source: https://context7.com/julie-fabre/bombcell/llms.txt Configures Bombcell to save quality metrics as TSV files for seamless integration with Phy. This is enabled by default. ```python import bombcell as bc # Enable Phy integration (on by default) param = bc.get_default_parameters(kilosort_path) param["saveAsTSV"] = True # Save metrics as TSV files param["unit_type_for_phy"] = True # Save unit classifications ``` -------------------------------- ### Run Bombcell with Phy Integration Source: https://context7.com/julie-fabre/bombcell/llms.txt Runs Bombcell with Phy integration enabled, saving quality metrics and unit classifications as TSV files in the Kilosort directory. ```python # Run bombcell quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir=kilosort_path, save_path=save_path, param=param ) ``` -------------------------------- ### Print Default Bombcell Parameters Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_spikeGLX.ipynb Prints the retrieved default Bombcell parameters for review. This is useful for understanding the default settings before customization. ```python print("Bombcell parameters:") pprint(param) ``` -------------------------------- ### Run BombCell in MATLAB Source: https://github.com/julie-fabre/bombcell/wiki/Running-BombCell-and-UnitMatch Configures quality parameters and executes the BombCell pipeline for MATLAB users. ```matlab % Set paths ephysKilosortPath = 'path/to/kilosort'; ephysRawPath = 'path/to/raw.ap.bin'; ephysMetaPath = 'path/to/raw.ap.meta'; % Get parameters optimized for UnitMatch param = bc.qm.qualityParamValues(ephysMetaPath, ephysRawPath, ephysKilosortPath); param.nRawSpikesToExtract = 1000; % Extract more spikes for UnitMatch param.saveMultipleRaw = true; % Save individual raw waveforms % Load ephys data [spikeTimes_samples, spikeTemplates, templateWaveforms, templateAmplitudes, ... pcFeatures, pcFeatureIdx, channelPositions] = bc.load.loadEphysData(ephysKilosortPath); % Run BombCell [qMetric, unitType] = bc.qm.runAllQualityMetrics(param, spikeTimes_samples, ... spikeTemplates, templateWaveforms, templateAmplitudes, pcFeatures, ... pcFeatureIdx, channelPositions, ephysKilosortPath); ``` -------------------------------- ### Configure Bombcell Analysis Parameters Source: https://context7.com/julie-fabre/bombcell/llms.txt Set optional metrics and classification thresholds for the Bombcell analysis pipeline. ```python # Distance metrics (optional, slow) param["computeDistanceMetrics"] = False param["isoDmin"] = 20 param["lratioMax"] = 0.3 # Drift metrics (optional, slow) param["computeDrift"] = False param["maxDrift"] = 100 # µm # Non-somatic classification param["minTroughToPeak2Ratio_nonSomatic"] = 5 param["maxMainPeakToTroughRatio_nonSomatic"] = 0.8 param["splitGoodAndMua_NonSomatic"] = False # Set True for separate non-soma good/MUA ``` -------------------------------- ### Apply parameter suggestions in Python Source: https://github.com/julie-fabre/bombcell/wiki/Guide-to-bombcell's-GUI Update parameters based on analysis results and re-run the BombCell pipeline to improve classification accuracy. ```python import bombcell as bc # Load existing parameters param, quality_metrics, _ = bc.load_bc_results(save_path) # Apply suggestions (example) param['maxRPVviolations'] = 0.05 param['minAmplitude'] = 30 # Re-run bombcell with updated parameters quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir, save_path, param ) # Compare again to see improvement bc.compare_manual_vs_bombcell(save_path) ``` -------------------------------- ### Enable Phy Integration in MATLAB Source: https://github.com/julie-fabre/bombcell/wiki/Compatibility-with-phy Enable saving quality metrics as TSV files for Phy integration in MATLAB. This setting is enabled by default. ```matlab param.saveAsTSV = 1; ``` -------------------------------- ### Customize Amplitude and SNR Thresholds Source: https://context7.com/julie-fabre/bombcell/llms.txt Sets thresholds for raw amplitude and signal-to-noise ratio. These values are highly dataset-dependent and should be tuned accordingly. ```python # Amplitude and SNR thresholds - TUNE THESE FOR YOUR DATA param["minAmplitude"] = 40 # µV - varies significantly by brain region param["minSNR"] = 5 ``` -------------------------------- ### Perform detailed analysis with Python Source: https://github.com/julie-fabre/bombcell/wiki/Guide-to-bombcell's-GUI Use individual analysis functions to load classifications, compare manual labels against BombCell results, and extract specific metrics. ```python from bombcell import ( load_manual_classifications, analyze_classification_concordance, suggest_parameter_adjustments, analyze_manual_vs_bombcell ) # Load manual classifications manual_df = load_manual_classifications(save_path) # Full analysis with all results results = analyze_manual_vs_bombcell(save_path, quality_metrics_df, param) # Access individual components confusion_matrix = results['confusion_matrix'] suggestions = results['parameter_suggestions'] stats = results['concordance_stats'] ``` -------------------------------- ### Define data paths Source: https://github.com/julie-fabre/bombcell/blob/main/py_bombcell/demos/BC_demo_other_recording_software.ipynb Set the directory path for Kilosort data and the output directory for bombcell results. ```python # Replace with your kilosort directory ks_dir = "toy_data" # CHANGE to where your kilosorted data lives # Set bombcell's output directory save_path = Path(ks_dir) / "bombcell" print(f"Using kilosort directory: {ks_dir}") ``` -------------------------------- ### Bombcell Analysis Workflow Source: https://github.com/julie-fabre/bombcell/wiki/Guide-to-bombcell's-ephys-properties Standard pipeline for processing electrophysiological data, including quality metrics, filtering, property calculation, and classification. ```python import bombcell as bc from bombcell.ephys_properties import run_all_ephys_properties from bombcell.classification import classify_and_plot_brain_region # 1. Run quality metrics first param = bc.get_default_parameters(kilosort_path, raw_file, meta_file) quality_metrics, param, unit_type, unit_type_string = bc.run_bombcell( ks_dir=kilosort_path, save_path=save_path, param=param ) # 2. Filter to good units only (optional but recommended) good_mask = unit_type_string == 'GOOD' good_unit_ids = param['unique_templates'][good_mask] # 3. Run ephys properties ephys_properties, ephys_param = run_all_ephys_properties( kilosort_path, param=param, save_path=save_path ) # 4. Classify cell types (if you know the brain region) cell_types = classify_and_plot_brain_region( ephys_properties, ephys_param, brain_region='striatum' # or 'cortex' ) # 5. Print summary print(f"Classified {len(cell_types)} units") for ct in set(cell_types): n = cell_types.count(ct) print(f" {ct}: {n} ({100*n/len(cell_types):.1f}%)") ``` -------------------------------- ### Reinstall Bombcell via Python Source: https://github.com/julie-fabre/bombcell/wiki/Installation Commands to uninstall and reinstall the stable version of Bombcell. ```bash pip uninstall bombcell uv pip install bombcell ```