Skip to content

RadoslavJochman/Bachelor-Thesis-Code-Spontaneous-Map-Inference

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

87 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spontaneous Activity Analysis Toolkit

Decoding orientation preference maps from spontaneous activity in human V1, and asking whether sleep does it better than wakefulness.

Code for my bachelor thesis, Decoding functional representations from population activity in V1 recorded during sleep (Charles University, Faculty of Science, 2025; supervisor Mgr. Ján Antolík, Ph.D.). 📄 Read the thesis


The question

Neurons in the primary visual cortex are tuned to edge orientation, and neurons with similar preferences cluster together into orientation preference (OP) maps. Knowing that layout matters for cortical visual prostheses: stimulating electrodes without regard to the underlying functional organisation produces percepts that are hard to interpret.

The problem is that every standard method for mapping V1, whether optical imaging, two photon, or fMRI, requires showing the subject a visual stimulus. For a blind person, the population prostheses are built for, that is exactly what is unavailable.

Spontaneous activity offers a way out: cortex left to itself spontaneously falls into patterns that resemble its OP map, so the map can in principle be read out with no stimulus at all (Kenet et al., 2003). But awake spontaneous activity is noisy, constantly perturbed by sensory input and ongoing cognition. During sleep, sensory input is gated off. Does that make the intrinsic functional structure easier to decode?

What was found

Yes, clearly. Using intracortical recordings from a blind human participant (96 channel Utah array in V1/V2), OP maps were decoded from negative LFP deflections via PCA and scored by how reproducibly the same map came back from different slices of the same recording.

best mean RMSE SEM
sleep 0.15 rad 0.015
awake 0.34 rad 0.060

Sleep derived maps were more than twice as consistent, and stayed flat over increasing temporal separation, where awake maps drifted and varied unpredictably across recordings. The result holds both on all electrodes and on a quality filtered subset.

This is a stimulus free route to functional cortical mapping, the kind of thing a visual prosthesis for a blind patient would need, since there is no stimulus to map with.


📚 Features

  • Load and preprocess raw LFP or spike recordings (.nix, .ns5, .ns6)
  • Create ArrayAnalysis objects representing electrode array data
  • Compute spontaneous maps (OP map approximations) via PCA projection
  • Evaluate stability of maps across:
    • Bin size
    • Time
    • Data segments
    • Different thresholds
  • Compute RMSE distances between maps, using circular distance to respect the π periodicity of orientation
  • Visualize:
    • Spontaneous activity maps
    • RMSE heatmaps and boxplots
    • Success rates related to functional vs spatial distances
  • Filter good channels based on SNR, presence ratio, firing rates

🧠 Method

  1. nLFP extraction: band-pass 1–150 Hz, downsample to 1 kHz, notch out line noise, common average referencing. Negative deflections past a per channel threshold (T = μ + t·σ) are detected as events and binned into fixed windows.
  2. Cross correlation: correlation between binned nLFP frames for every electrode pair.
  3. PCA projection: correlation maps are interpolated (for fitting only), projected onto a plane spanned by a pair of principal components, and the projected coordinates are read out as orientation labels.
  4. Alignment and scoring: maps are defined only up to a global phase shift, so each is circularly aligned to a reference before RMSE is computed.

A grid search over 450 combinations (threshold × bin size × PC pair) identified the best parameters separately for each condition. Short bins (0.1–0.6 s) and low index PC pairs were consistently best; threshold −3 was consistently worst.


🗂 Project Structure

File Purpose
array_analysis.py Main ArrayAnalysis class (core data structure).
analysis.py Functions for frame extraction, map calculation, PCA analysis.
helper.py Utility functions for map alignment, RMSE computation, preprocessing, etc.
preprocessing.py Raw LFP and spike preprocessing.
plotting.py Visualizations with plotnine.
Various main_*.py scripts Command line interfaces for major analysis tasks (bin size stability, RMSE calculations, plotting).

📜 Key Pipelines (CLI Scripts)

Script What it does
main_generate_good_channels.py Filters and saves good quality electrodes.
main_generate_arr_obj.py Creates a pickled ArrayAnalysis object from input data.
main_bin_size_stability.py Analyzes spontaneous map stability across different bin sizes.
main_temporal_stability.py Splits sessions into time segments and checks map stability.
main_params_analysis.py Full parameter sweep (bin size, segment splitting) across recordings.
main_generate_rmse_dist_param.py Computes RMSE between samples and a fixed reference across PC pairs.
main_generate_rmse_dist_2samples_param.py Computes RMSE between corresponding sample pairs.
main_generate_rmse_dist_in_time.py RMSE evolution across time separated recordings.
main_plot_average_heatmap_param.py Plots averaged RMSE heatmaps.
main_plot_heatmap_param.py Plots RMSE heatmaps.
main_plot_mean_rmse_by_time.py Visualizes RMSE evolution across time.
main_plot_spontaneous_map.py Plots spontaneous maps aligned to a reference.
main_plot_success_rate.py Visualizes success rate in a discrimination task vs spatial/functional distances.
concat_dataframes.py Combines multiple CSV RMSE results into a single file.

🛠 Requirements

Python 3.8+. Install with:

pip install -r requirements.txt

Main libraries: numpy, pandas, scipy, neo, elephant, quantities, scikit-learn, plotnine, matplotlib, pyyaml.

Reading raw Blackrock files uses blackrock_utilities, which is included in this repository (see note under License).


🚀 Example Usage

Generate Good Channels:

python main_generate_good_channels.py --spikes_dir data/ --snr 5 --presence_ratio 0.95 --result_path results/good_channels.csv

Bin Size Stability:

python main_bin_size_stability.py --analysis_params_dir configs/analysis.yaml --params_dir configs/data.yaml --data_dir data/ --result_dir results/bin_stability

Compute RMSE between samples and reference:

python main_generate_rmse_dist_param.py --data_location results/bin_stability/ --ref_obj_path results/reference.pkl --PCs 1,2,3,4 --sample_name Subject1 --result_dir results/rmse

Plot RMSE heatmap:

python main_plot_heatmap_param.py --data_location results/rmse/Subject1.csv --result_dir figures/ --result_name heatmap_subject1.png

Limitations

The participant is blind, so no stimulus evoked ground truth OP map exists to validate against; map quality is assessed indirectly, through reproducibility. Sleep data is a single ~60 minute session, while awake data is spread over three months, which confounds state with recording gap; the analysis mitigates this by comparing only segments within each recording. Extending to macaque data, where ground truth maps do exist, is the obvious next validation step.

Data

This repository contains code and aggregated results only, not the raw recordings.

References

The premise that spontaneous cortical activity contains structured, decodable orientation representations comes from:

Kenet, T., Bibitchkov, D., Tsodyks, M., Grinvald, A., & Arieli, A. (2003). Spontaneously emerging cortical representations of visual attributes. Nature, 425(6961), 954–956. https://doi.org/10.1038/nature02078

That work showed, in anaesthetised cats via voltage sensitive dye imaging, that ongoing activity repeatedly visits states resembling single orientation maps. This project asks whether the same intrinsic structure can be recovered in a blind human, from LFP recordings during sleep, where no visual stimulus is available to build a reference map from.

License

This project is released under the MIT License (see LICENSE).

Third party code: blackrock_utilities/ contains file reading utilities from Blackrock Neurotech, included here for convenience. It is authored by Blackrock Microsystems and is not covered by this repository's MIT License; its use is subject to Blackrock's own terms.

Author

Radoslav Jochman, rdjchmn@gmail.com

About

Code for my BSc thesis: decoding orientation preference maps from spontaneous activity in human V1. Compares sleep against wakefulness and finds sleep-derived maps markedly more stable — a stimulus-free route to functional cortical mapping for visual prostheses.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages