Forward model of rat electroencephalogram: influence of inhomogeneous and anisotropic skull.
The 2 matches
- [1] § Methods › Sensing electrodes and modelling of neural activity of the brain ↔ plot_summary_figure.py, lines 1–45 · score 0.54 · head model, dipole orientation, inhomogeneity, anisotropy
- [2] § Methods › Leadfield comparisons on a volumetric grid ↔ plot_summary_figure.py, lines 1–45 · score 0.51 · head model, dipole orientations, vector, Leadfield
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 321 lines · 13 KB · no license · 2 matches
- """
- Step 2 of 2 — Generate the leadfield contrast summary figure.
- Prerequisites
- -------------
- 1. Install dependencies:
- pip install -r requirements.txt
- 2. Run compute_metrics.py first (or use the pre-computed files in data/).
- Usage
- -----
- python plot_summary_figure.py
- Output
- ------
- lf_summary_figure.png (filename controlled by config.OUTPUT_FILE)
- What the figure shows
- ---------------------
- Each row corresponds to one leadfield contrast (L0 vs L1, L0 vs L4, L1 vs L4).
- Within each row there are two sub-rows:
- • Top sub-row — XY / XZ / YZ projection maps of the normalised Euclidean
- distance between the two leadfield models, overlaid with
- arrows indicating the dipole orientation that maximises that
- distance (max-contrast direction).
- • Bottom sub-row — scatter plots of each spatial coordinate (X, Y, Z) against
- the corresponding component of the unit max-contrast
- direction vector.
- Level codes
- -----------
- L0 — homogeneous head model
- L1 — inhomogeneous head model
- L4 — anisotropic head model
- """
- import sys
- import os
- from pathlib import Path
- import numpy as np
- import matplotlib
- import matplotlib.pyplot as plt
- import matplotlib.gridspec as gridspec
- from scipy.interpolate import griddata
- # ── locate config / data relative to this script ─────────────────────────────
- _HERE = Path(os.path.abspath(__file__)).parent
- sys.path.insert(0, str(_HERE))
- import config as cfg
- DATA_DIR = _HERE / cfg.OUTPUT_PATH
- # Contrasts to include, in display order.
- # Each entry is (forward_level, inverse_level) — must match the .npz filenames.
- CONTRASTS = cfg.LEADFIELD_CONTRASTS
- # ─────────────────────────────────────────────────────────────────────────────
- # Helper: 2-D projection with optional interpolation
- # ─────────────────────────────────────────────────────────────────────────────
- def _aggregate_projection(dip_pos, values, axis, agg_func='mean', interpolate=True):
- """
- Collapse a 3-D scatter of (dipole positions, scalar values) onto a 2-D plane
- by removing one axis and aggregating duplicate positions.
- Parameters
- ----------
- dip_pos : (N, 3) array of dipole positions [mm]
- values : (N,) scalar value per dipole
- axis : int axis to project out (0=x, 1=y, 2=z)
- agg_func : str 'mean', 'min', or 'max'
- interpolate: bool fill missing grid cells with linear interpolation
- Returns
- -------
- coords_0, coords_1 : 1-D arrays with unique coordinates on the two kept axes
- projection : (len(coords_0), len(coords_1)) aggregated grid
- """
- axes = [0, 1, 2]
- axes.remove(axis)
- coords_0 = np.unique(dip_pos[:, axes[0]])
- coords_1 = np.unique(dip_pos[:, axes[1]])
- X_grid, Y_grid = np.meshgrid(coords_0, coords_1, indexing='ij')
- projection = np.full(X_grid.shape, np.nan)
- agg = {'mean': np.mean, 'max': np.max, 'min': np.min}[agg_func]
- for i, c0 in enumerate(coords_0):
- for j, c1 in enumerate(coords_1):
- mask = (dip_pos[:, axes[0]] == c0) & (dip_pos[:, axes[1]] == c1)
- if np.any(mask):
- projection[i, j] = agg(values[mask])
- if interpolate:
- valid = ~np.isnan(projection)
- if np.any(valid) and np.any(~valid):
- pts = np.column_stack([X_grid[valid], Y_grid[valid]])
- vals_v = projection[valid]
- pts_all = np.column_stack([X_grid.ravel(), Y_grid.ravel()])
- projection = griddata(pts, vals_v, pts_all, method='linear').reshape(X_grid.shape)
- return coords_0, coords_1, projection
- # ─────────────────────────────────────────────────────────────────────────────
- # Main figure
- # ─────────────────────────────────────────────────────────────────────────────
- def plot_summary_figure(dip_pos, all_metrics, elec_pos, contrasts, clim_euclid, output_file):
- """
- Build and save the leadfield-contrast summary figure.
- Parameters
- ----------
- dip_pos : (nDip, 3) decimated dipole positions [mm]
- all_metrics : dict {(level_a, level_b): (corr, euclid, rel_diff, mc_vecs)}
- elec_pos : (nElec, 3) electrode positions [mm]
- contrasts : list of (level_a, level_b) pairs
- clim_euclid : (vmin, vmax) or None for auto colour limits
- output_file : Path where to write the figure
- """
- n = len(contrasts)
- h_comb = cfg.MEGA_FIGURE_H_COMBINED
- h_scat = cfg.MEGA_FIGURE_H_SCATTER
- h_ratios = [val for _ in range(n) for val in (h_comb, h_scat)]
- fig_w = cfg.FIGSIZE_PROJECTION[0]
- fig_h = n * (h_comb + h_scat)
- fig = plt.figure(figsize=(fig_w, fig_h))
- gs = gridspec.GridSpec(
- 2 * n, 3,
- height_ratios=h_ratios,
- hspace=cfg.MEGA_FIGURE_HSPACE,
- wspace=0.35,
- figure=fig,
- )
- vmin, vmax = clim_euclid if clim_euclid is not None else (None, None)
- contour_lvls = (
- np.linspace(vmin, vmax, cfg.CONTOUR_LEVELS)
- if vmin is not None and vmax is not None
- else cfg.CONTOUR_LEVELS
- )
- coord_labels = ['X [mm]', 'Y [mm]', 'Z [mm]']
- comp_labels = ['X', 'Y', 'Z']
- scatter_colors = ['tab:red', 'tab:blue', 'tab:green']
- # (horiz_axis, vert_axis, xlabel, ylabel)
- proj_specs = [
- (0, 1, 'X [mm]', 'Y [mm]'),
- (0, 2, 'X [mm]', 'Z [mm]'),
- (1, 2, 'Y [mm]', 'Z [mm]'),
- ]
- last_cf = None
- for row_idx, (level_a, level_b) in enumerate(contrasts):
- _, euclid, _, mc_vecs = all_metrics[(level_a, level_b)]
- # Scale arrows so the longest arrow = QUIVER_SCALE_LF_CONTRAST [mm]
- mags = np.linalg.norm(mc_vecs, axis=1)
- max_mag = np.nanmax(mags) if np.nanmax(mags) > 1e-12 else 1.0
- scaled = mc_vecs / max_mag * cfg.QUIVER_SCALE_LF_CONTRAST
- # 2-D projections of normalised Euclidean distance
- Xp, Yp, XY = _aggregate_projection(dip_pos, euclid, 2, cfg.AGG_FUNC)
- Xp, Zp, XZ = _aggregate_projection(dip_pos, euclid, 1, cfg.AGG_FUNC)
- Yp, Zp, YZ = _aggregate_projection(dip_pos, euclid, 0, cfg.AGG_FUNC)
- proj_grids = [
- (Xp, Yp, XY),
- (Xp, Zp, XZ),
- (Yp, Zp, YZ),
- ]
- combined_row = 2 * row_idx
- scatter_row = 2 * row_idx + 1
- panel_label = chr(ord('A') + row_idx)
- # ── Top sub-row: contourf + quiver ────────────────────────────────────
- for col, ((xi, yi, xlabel, ylabel), (cx, cy, cgrid)) in enumerate(
- zip(proj_specs, proj_grids)):
- ax = fig.add_subplot(gs[combined_row, col])
- if col == 0:
- ax.text(
- -0.18, 1.0, panel_label,
- transform=ax.transAxes,
- fontsize=cfg.FONTSIZE_TITLE + 2,
- fontweight='bold',
- va='top', ha='right', clip_on=False,
- )
- cf = ax.contourf(
- cx, cy, cgrid.T,
- levels=contour_lvls,
- cmap=cfg.COLORMAP_LF_EUCLIDEAN,
- vmin=vmin, vmax=vmax,
- )
- ax.quiver(
- dip_pos[:, xi], dip_pos[:, yi],
- scaled[:, xi], scaled[:, yi],
- color='black', scale=1, scale_units='xy',
- width=0.003, alpha=0.7,
- )
- ax.scatter(
- elec_pos[:, xi], elec_pos[:, yi],
- c='b', s=30, zorder=5,
- label='Electrodes' if col == 0 else None,
- )
- ax.grid(True, alpha=0.3)
- ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
- ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
- ax.set_aspect('equal')
- ax.set_xlabel(xlabel, fontsize=cfg.FONTSIZE_AXIS_LABEL)
- if col == 0:
- ax.set_ylabel(
- f'L{level_a} vs L{level_b}\n{ylabel}',
- fontsize=cfg.FONTSIZE_AXIS_LABEL,
- )
- ax.legend(fontsize=7, markerscale=1.2)
- else:
- ax.set_ylabel(ylabel, fontsize=cfg.FONTSIZE_AXIS_LABEL)
- ax.tick_params(labelsize=cfg.FONTSIZE_TICK_LABEL)
- last_cf = cf
- # ── Bottom sub-row: coordinate vs direction component scatter ─────────
- norms = np.linalg.norm(mc_vecs, axis=1)
- valid = norms > 1e-12
- directions = np.full_like(mc_vecs, np.nan)
- directions[valid] = mc_vecs[valid] / norms[valid, np.newaxis]
- for col in range(3):
- ax = fig.add_subplot(gs[scatter_row, col])
- coord_vals = dip_pos[:, col]
- ax.scatter(
- coord_vals[valid], directions[valid, col],
- c=scatter_colors[col], s=cfg.SCATTER_MARKER_SIZE, alpha=0.25,
- )
- ax.set_xlabel(coord_labels[col], fontsize=cfg.FONTSIZE_AXIS_LABEL)
- ax.set_ylabel(f'dir {comp_labels[col]}', fontsize=cfg.FONTSIZE_AXIS_LABEL)
- ax.set_ylim(-1.05, 1.05)
- ax.axhline(0, color='gray', linewidth=0.8, linestyle='--')
- ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
- ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2f'))
- ax.grid(True, alpha=0.3)
- ax.tick_params(labelsize=cfg.FONTSIZE_TICK_LABEL)
- # ── Shared horizontal colorbar ────────────────────────────────────────────
- if cfg.SHOW_COLORBAR and last_cf is not None:
- fig.subplots_adjust(bottom=0.06)
- cbar_ax = fig.add_axes([0.1, 0.02, 0.8, 0.008])
- cbar = fig.colorbar(last_cf, cax=cbar_ax, orientation='horizontal')
- cbar.set_label('LF Normalised Euclidean', fontsize=cfg.FONTSIZE_COLORBAR_LABEL)
- if vmin is not None and vmax is not None:
- cbar.set_ticks(np.arange(vmin, vmax + 0.01, 0.1))
- cbar.ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
- cbar.ax.tick_params(labelsize=cfg.FONTSIZE_TICK_LABEL)
- plt.savefig(output_file, dpi=cfg.IMAGE_DPI, bbox_inches='tight')
- plt.close()
- print(f"Saved: {output_file}")
- # ─────────────────────────────────────────────────────────────────────────────
- # Entry point
- # ─────────────────────────────────────────────────────────────────────────────
- def main():
- matplotlib.rcParams.update({
- 'axes.labelsize': cfg.FONTSIZE_AXIS_LABEL,
- 'xtick.labelsize': cfg.FONTSIZE_TICK_LABEL,
- 'ytick.labelsize': cfg.FONTSIZE_TICK_LABEL,
- 'axes.titlesize': cfg.FONTSIZE_TITLE,
- 'legend.fontsize': cfg.FONTSIZE_LEGEND,
- })
- print("Loading pre-computed data from:", DATA_DIR)
- dip_pos = np.load(DATA_DIR / 'dipole_positions.npy')
- elec_pos = np.load(DATA_DIR / 'electrode_positions.npy')
- print(f" dipole_positions: {dip_pos.shape}")
- print(f" electrode_positions: {elec_pos.shape}")
- all_metrics = {}
- for (la, lb) in CONTRASTS:
- fname = DATA_DIR / f'metrics_L{la}vsL{lb}.npz'
- if not fname.exists():
- raise FileNotFoundError(
- f"Missing data file: {fname}\n"
- "Run compute_metrics.py first (see README.md)."
- )
- d = np.load(fname)
- all_metrics[(la, lb)] = (
- d['correlations'],
- d['euclidean_dists'],
- d['rel_diffs'],
- d['max_contrast_vecs'],
- )
- print(f" metrics_L{la}vsL{lb}.npz "
- f"(euclid mean={np.nanmean(d['euclidean_dists']):.4f})")
- clim = cfg.CLIM_LF_EUCLIDEAN
- if clim is None:
- all_euclid = np.concatenate([all_metrics[k][1] for k in all_metrics])
- clim = (float(np.nanmin(all_euclid)), float(np.nanmax(all_euclid)))
- print(f" Auto colour limits: {clim}")
- else:
- print(f" Colour limits (from config): {clim}")
- output_file = _HERE / cfg.OUTPUT_FILE
- plot_summary_figure(dip_pos, all_metrics, elec_pos, CONTRASTS, clim, output_file)
- if __name__ == '__main__':
- main()
plot_summary_figure.py at commit f780e22, no license · at the source
Overview
- Faculty of Electrical Engineering and Communication, Brno University of Technology, Brno, 61600 Czech Republic
- National Institute of Mental Health, Klecany, 250 67 Czech Republic
- Faculty of Chemistry, Brno University of Technology, Brno, 61200 Czech Republic
- Nencki Institute of Experimental Biology of Polish Academy of Sciences, 02-093 Warsaw, Poland
- Third Faculty of Medicine, Charles University, Prague, 10000 Czech Republic
Abstract
The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.
Repository
Its files are read in the Code ↔ Paper reader above, with 2 matches between paragraphs and lines of code.
VlastaKoudelka/skull-leadfield
f780e223dff6faadc53f209d3b4fba61698481f9, 11 June 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
4 files
- compute_metrics.py, Python, 356 lines
- config.py, Python, 70 lines
- plot_summary_figure.py, Python, 321 lines, 2 matches
- README.md, Text, 103 lines
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 3 scripts, each with its path and the digest of its content;
- 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
Datasets cited
- zenodo:17975304, at Zenodo; found in “Data availability”
Code and data availability statement
The paper has a code and data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:
- it points to a dataset: Zenodo 17975304
- it points to the authors' code: VlastaKoudelka/
skull-leadfield - it says that the data are available on request
Read it in the paper: doi.org/10.1038/s41598-026-58885-1.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 8 authors, 3 keywords, 8 MeSH terms, 1 funder, 52 references.
Cite
This paper
Kuratko, D., Koudelka, V., Vejmola, C., Dusek, F., Kucera, F., Wójcik, D. K., Palenicek, T., & Lacik, J. (2026). Forward model of rat electroencephalogram: influence of inhomogeneous and anisotropic skull. Scientific reports, 16(1), 28626. https://
BibTeX
@article{kuratko2026forw
author = {Kuratko, David and Koudelka, Vlastimil and Vejmola, Cestmir and Dusek, Filip and Kucera, Frantisek and Wójcik, Daniel K and Palenicek, Tomas and Lacik, Jaroslav},
title = {{Forward model of rat electroencephalogram: influence of inhomogeneous and anisotropic skull}},
journal = {Scientific reports},
year = {2026},
month = jun,
volume = {16},
number = {1},
pages = {28626},
publisher = {Nature Publishing Group},
issn = {2045-2322},
doi = {10.1038/
url = {https://
pmid = {42331932},
pmcid = {PMC13575132}
}
RIS
TY - JOUR
AU - Kuratko, David
AU - Koudelka, Vlastimil
AU - Vejmola, Cestmir
AU - Dusek, Filip
AU - Kucera, Frantisek
AU - Wójcik, Daniel K
AU - Palenicek, Tomas
AU - Lacik, Jaroslav
TI - Forward model of rat electroencephalogram: influence of inhomogeneous and anisotropic skull
T2 - Scientific reports
J2 - Sci Rep
PY - 2026
DA - 2026/
VL - 16
IS - 1
SP - 28626
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1038/
"type": "article-journal",
"title": "Forward model of rat electroencephalogram: influence of inhomogeneous and anisotropic skull",
"container-title": "Scientific reports",
"author": [
{
"family": "Kuratko",
"given": "David"
},
{
"family": "Koudelka",
"given": "Vlastimil"
},
{
"family": "Vejmola",
"given": "Cestmir"
},
{
"family": "Dusek",
"given": "Filip"
},
{
"family": "Kucera",
"given": "Frantisek"
},
{
"family": "Wójcik",
"given": "Daniel K"
},
{
"family": "Palenicek",
"given": "Tomas"
},
{
"family": "Lacik",
"given": "Jaroslav"
}
],
"container-title-short":
"volume": "16",
"issue": "1",
"page": "28626",
"DOI": "10.1038/
"PMID": "42331932",
"PMCID": "PMC13575132",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
22
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.7554/elife.108408 [code]
- Frequency and laminar profile of feature-specific visual activity revealed by interleaved EEG-fMRI.Journal: eLifeIn common: pandas, SciPy, Matplotlib, 1 other tool, EEG, 2 references
- [2] doi:10.1038/s41467-026-75837-5 [code]
- A hierarchical framework for cortical and subcortical gray-matter parcellation across rodents, primates, and humans.Journal: Nature communicationsIn common: pandas, SciPy, Matplotlib, 1 other tool, rat, 1 reference
- [3] doi:10.1371/journal.pcbi.1014304 [code]
- Linking reduced prefrontal microcircuit inhibition in schizophrenia to EEG biomarkers in silico.Journal: PLoS computational biologyIn common: pandas, SciPy, Matplotlib, 1 other tool, EEG, 1 reference
- [4] doi:10.1371/journal.pone.0351872 [code]
- Decoding visual object recognition from EEG signals.Journal: PloS oneIn common: pandas, SciPy, Matplotlib, 1 other tool, EEG, 1 reference
- [5] doi:10.1371/journal.pcbi.1014434 [code]
- Non-invasive mapping of the temporal processing hierarchy in the human visual cortex.Journal: PLoS computational biologyIn common: Matplotlib, NumPy, 2 references
- [6] doi:10.1126/sciadv.aed6417 [code]
- Intrinsic timing, not temporal prediction, underlies ramping dynamics in visual and parietal cortex during passive behavior.Journal: Science advancesIn common: pandas, SciPy, Matplotlib, 1 other tool, 1 reference
- [7] doi:10.1007/s00234-026-04103-8 [code]
- Enhanced detection of subtle cortical abnormalities in focal epilepsy using 7 T MRI surface-based models and graph neural networks.Journal: NeuroradiologyIn common: pandas, SciPy, Matplotlib, 1 other tool, EEG, 1 reference
- [8] doi:10.1117/1.nph.12.2.025011 [code]
- NIRSTORM: a Brainstorm extension dedicated to functional near-infrared spectroscopy data analysis, advanced 3D reconstructions, and optimal probe designJournal: n/aIn common: Matplotlib, NumPy, EEG, 2 references
- [9] doi:10.1093/sleep/zsag168 [code]
- Deltas' and spindles' cross-area synchronization and ripple subtypes.Journal: SleepIn common: SciPy, Matplotlib, NumPy, rat, EEG, 1 reference
- [10] doi:10.7554/elife.107088 [code]
- Development of auditory and spontaneous movement responses to music over the first postnatal year.Journal: eLifeIn common: pandas, SciPy, Matplotlib, 1 other tool, EEG, 1 reference
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 3 scripts, and 2 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:89ed346937c43c48…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
