Skip to content

freesurfer

FreeSurfer data.

Classes:

Functions:

FreeSurfer

FreeSurfer(freesurfer_home: str | None = None, subjects_dir: str | None = None, log_level: str = 'INFO')

Base class for FreeSurfer data.

Parameters:

  • freesurfer_home

    (str representing a path to a directory, default: None ) –

    Path corresponding to FREESURFER_HOME env var.

  • subjects_dir

    (str representing a path to a directory, default: None ) –

    Path corresponding to SUBJECTS_DIR env var.

  • log_level

    (str, default: 'INFO' ) –

    Logging level (e.g., "INFO", "DEBUG", "WARNING"). Default is "INFO".

Returns:

  • None

Methods:

  • check_recon_all

    Verify that the subject's FreeSurfer recon finished successfully.

  • gen_aparcaseg_plots

    Generate parcellation images (aparc & aseg) and return the path to the aparcaseg.png file.

  • gen_batch_reports

    Generate HTML reports with images for multiple subjects.

  • gen_group_report

    Generate a group report with outlier information for multiple subjects.

  • gen_html_report

    Generate html report with FreeSurfer images.

  • gen_surf_plots

    Generate pial, inflated, and sulcal images from various viewpoints.

  • gen_tlrc_data

    Generate inverse talairach data for report generation.

  • gen_tlrc_report

    Generate a before and after report of Talairach registration. (Will also run file generation if needed).

  • get_colormap

    Return the colormap for the FreeSurfer data.

  • get_subjects

    Return the subjects in the subjects directory.

Attributes:

Source code in src/pyfsviz/freesurfer.py
 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
def __init__(
    self,
    freesurfer_home: str | None = None,
    subjects_dir: str | None = None,
    log_level: str = "INFO",
):
    """Initialize the FreeSurfer data.

    Parameters
    ----------
    freesurfer_home : str representing a path to a directory
        Path corresponding to FREESURFER_HOME env var.
    subjects_dir : str representing a path to a directory
        Path corresponding to SUBJECTS_DIR env var.
    log_level : str
        Logging level (e.g., "INFO", "DEBUG", "WARNING").
        Default is "INFO".

    Returns
    -------
    None

    """
    # Set up logger
    logging.basicConfig(level=getattr(logging, log_level.upper()))
    self.logger = logging.getLogger(f"{__name__}.{self.__class__.__name__}")
    """Logger for the FreeSurfer class."""

    if freesurfer_home is None:
        self.freesurfer_home = Path(os.environ.get("FREESURFER_HOME") or "")
        """Path to the FreeSurfer home directory."""
    else:
        self.freesurfer_home = Path(freesurfer_home)
        """Path to the FreeSurfer home directory."""
    if not self.freesurfer_home.exists():
        raise FileNotFoundError(f"FREESURFER_HOME not found: {self.freesurfer_home}")
    if self.freesurfer_home is None:
        raise ValueError("FREESURFER_HOME must be set")

    if subjects_dir is None:
        self.subjects_dir = Path(os.environ.get("SUBJECTS_DIR") or "")
        """Path to the subjects directory."""
    else:
        self.subjects_dir = Path(subjects_dir)
        """Path to the subjects directory."""
    if not self.subjects_dir.exists():
        raise FileNotFoundError(f"SUBJECTS_DIR not found: {self.subjects_dir}")
    """Path to the subjects directory."""
    self._mni_nii = files("pyfsviz._internal") / "mni305.cor.nii.gz"
    """Path to the MNI template NIfTI file."""
    self._mni_mgz = files("pyfsviz._internal") / "mni305.cor.mgz"
    """Path to the MNI template MGH file."""

freesurfer_home instance-attribute

freesurfer_home = Path(get('FREESURFER_HOME') or '')

Path to the FreeSurfer home directory.

logger instance-attribute

logger = getLogger(f'{__name__}.{__name__}')

Logger for the FreeSurfer class.

subjects_dir instance-attribute

subjects_dir = Path(get('SUBJECTS_DIR') or '')

Path to the subjects directory.

check_recon_all

check_recon_all(subject: str) -> bool

Verify that the subject's FreeSurfer recon finished successfully.

Source code in src/pyfsviz/freesurfer.py
127
128
129
130
131
132
133
def check_recon_all(self, subject: str) -> bool:
    """Verify that the subject's FreeSurfer recon finished successfully."""
    recon_file = self.subjects_dir / subject / "scripts" / "recon-all.log"

    with open(recon_file, encoding="utf-8") as f:
        line = f.readlines()[-1]
        return "finished without error" in line

gen_aparcaseg_plots

gen_aparcaseg_plots(subject: str, output_dir: str) -> Path

Generate parcellation images (aparc & aseg) and return the path to the aparcaseg.png file.

Parameters:

  • subject

    (str) –

    Subject ID.

  • output_dir

    (str) –

    Path to output directory.

Returns:

  • Path ( Path ) –

    Path to the aparcaseg.png file.

Examples:

>>> from pyfsviz.freesurfer import FreeSurfer
>>> fs_dir = FreeSurfer(
...     freesurfer_home="/opt/freesurfer",
...     subjects_dir="/opt/data",
...     subject="sub-001",
... )
>>> images = fs_dir.gen_aparcaseg_plots(
...     "sub-001", Path("/opt/data/sub-001/mri/transforms")
... )
Source code in src/pyfsviz/freesurfer.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def gen_aparcaseg_plots(self, subject: str, output_dir: str) -> Path:
    """Generate parcellation images (aparc & aseg) and return the path to the aparcaseg.png file.

    Parameters
    ----------
    subject : str
        Subject ID.
    output_dir : str
        Path to output directory.

    Returns
    -------
    Path:
        Path to the aparcaseg.png file.

    Examples
    --------
    >>> from pyfsviz.freesurfer import FreeSurfer
    >>> fs_dir = FreeSurfer(
    ...     freesurfer_home="/opt/freesurfer",
    ...     subjects_dir="/opt/data",
    ...     subject="sub-001",
    ... )
    >>> images = fs_dir.gen_aparcaseg_plots(
    ...     "sub-001", Path("/opt/data/sub-001/mri/transforms")
    ... )
    """
    fsqc.run_fsqc(
        subjects_dir=str(self.subjects_dir),
        output_dir=output_dir,
        subjects=[subject],
        screenshots=True,
        screenshots_overlay="aparc+aseg.mgz",
        screenshots_views=[
            "x=-40",
            "x=-30",
            "x=-20",
            "x=-10",
            "x=0",
            "x=10",
            "x=20",
            "x=30",
            "x=40",
            "y=-40",
            "y=-30",
            "y=-20",
            "y=-10",
            "y=0",
            "y=10",
            "y=20",
            "y=30",
            "y=40",
            "z=-40",
            "z=-30",
            "z=-20",
            "z=-10",
            "z=0",
            "z=10",
            "z=20",
            "z=30",
            "z=40",
        ],
        screenshots_layout=["3", "9"],
        no_group=True,
    )

    # Clean up/move files
    shutil.move(f"{output_dir}/screenshots/{subject}/{subject}.png", f"{output_dir}/aparcaseg.png")
    shutil.move(f"{output_dir}/metrics/{subject}/metrics.csv", f"{output_dir}/metrics.csv")
    shutil.rmtree(f"{output_dir}/screenshots")
    shutil.rmtree(f"{output_dir}/status")
    shutil.rmtree(f"{output_dir}/metrics")

    return Path(f"{output_dir}/aparcaseg.png")

gen_batch_reports

gen_batch_reports(output_dir: str | Path, subjects: list[str] | None = None, template: str | None = None, *, gen_images: bool = True, skip_failed: bool = True) -> dict[str, Path | Exception]

Generate HTML reports with images for multiple subjects.

This method first generates all required images (TLRC, aparc+aseg, surfaces) and then creates HTML reports for each subject.

Parameters:

  • output_dir

    (str or Path) –

    Directory where HTML reports will be saved.

  • subjects

    (list[str] or None, default: None ) –

    List of subject IDs to process. If None, processes all subjects in the subjects directory.

  • template

    (str or None, default: None ) –

    HTML template to use. Default is local individual.html.

  • gen_images

    (bool, default: True ) –

    Generate images for each subject. Default is True.

  • skip_failed

    (bool, default: True ) –

    If True, continues processing other subjects if one fails. If False, raises exception on first failure.

Returns:

  • dict[str, Path | Exception]

    Dictionary mapping subject IDs to either the generated HTML file path or the exception that occurred during processing.

Examples:

>>> from pyfsviz.freesurfer import FreeSurfer
>>> fs = FreeSurfer()
>>> results = fs.gen_batch_reports("reports/", log_level="INFO")
>>> for subject, result in results.items():
...     if isinstance(result, Path):
...         print(f"Generated report for {subject}: {result}")
...     else:
...         print(f"Failed to generate report for {subject}: {result}")
Source code in src/pyfsviz/freesurfer.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
def gen_batch_reports(
    self,
    output_dir: str | Path,
    subjects: list[str] | None = None,
    template: str | None = None,
    *,
    gen_images: bool = True,
    skip_failed: bool = True,
) -> dict[str, Path | Exception]:
    """Generate HTML reports with images for multiple subjects.

    This method first generates all required images (TLRC, aparc+aseg, surfaces)
    and then creates HTML reports for each subject.

    Parameters
    ----------
    output_dir : str or Path
        Directory where HTML reports will be saved.
    subjects : list[str] or None
        List of subject IDs to process. If None, processes all subjects
        in the subjects directory.
    template : str or None
        HTML template to use. Default is local individual.html.
    gen_images : bool
        Generate images for each subject. Default is True.
    skip_failed : bool
        If True, continues processing other subjects if one fails.
        If False, raises exception on first failure.

    Returns
    -------
    dict[str, Path | Exception]
        Dictionary mapping subject IDs to either the generated HTML file
        path or the exception that occurred during processing.

    Examples
    --------
    >>> from pyfsviz.freesurfer import FreeSurfer
    >>> fs = FreeSurfer()
    >>> results = fs.gen_batch_reports("reports/", log_level="INFO")
    >>> for subject, result in results.items():
    ...     if isinstance(result, Path):
    ...         print(f"Generated report for {subject}: {result}")
    ...     else:
    ...         print(f"Failed to generate report for {subject}: {result}")
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    if subjects is None:
        subjects = self.get_subjects()

    self.logger.info(f"Generating reports with images for {len(subjects)} subjects...")
    self.logger.info(f"Output directory: {output_dir}")

    results: dict[str, Path | Exception] = {}

    for i, subject in enumerate(subjects, 1):
        self.logger.info(f"[{i}/{len(subjects)}] Processing subject: {subject}")

        try:
            # Check if recon-all completed successfully
            if not self.check_recon_all(subject):
                self.logger.warning(f"Subject {subject} recon-all did not complete successfully")

            # Create subject-specific output directory for images
            subject_output_dir = output_dir / subject
            subject_output_dir.mkdir(parents=True, exist_ok=True)

            # Generate images
            self.logger.info(f"  Generating images for {subject}...")

            img_list = []
            if gen_images:
                # Generate TLRC data and report
                # Use a temporary subdirectory for intermediate files
                temp_tlrc_dir = subject_output_dir / "tlrc_temp"
                temp_tlrc_dir.mkdir(exist_ok=True)

                self.gen_tlrc_data(subject, str(temp_tlrc_dir))
                tlrc = Path(self.gen_tlrc_report(subject, str(temp_tlrc_dir)))

                # Move tlrc.svg to subject directory
                if tlrc.exists():
                    new_tlrc_path = subject_output_dir / "tlrc.svg"
                    tlrc.rename(new_tlrc_path)
                    img_list.append(new_tlrc_path)
                else:
                    img_list.append(tlrc)

                # Clean up intermediate files
                shutil.rmtree(temp_tlrc_dir, ignore_errors=True)

                # Generate aparc+aseg plots - save directly to subject directory
                aparcaseg = self.gen_aparcaseg_plots(subject, str(subject_output_dir))
                img_list.append(aparcaseg)

                # Generate surface plots - save directly to subject directory
                surf = self.gen_surf_plots(subject, str(subject_output_dir))
                img_list.extend(surf)
            else:
                img_list = list(subject_output_dir.glob("**/*.{png,svg}"))

            # Generate HTML report using all generated images
            html_file = self.gen_html_report(
                subject=subject,
                output_dir=str(output_dir),
                img_list=img_list,
                template=template,
            )

            results[subject] = html_file

            self.logger.info(f"  ✓ Generated report with images: {html_file}")

        except Exception as e:
            error_msg = f"Failed to generate report with images for {subject}: {e!s}"
            results[subject] = e

            self.logger.error(f"  ✗ {error_msg}")  # noqa: TRY400

            if not skip_failed:
                raise e  # noqa: TRY201 # pylint: disable=try-except-raise

    successful = sum(1 for result in results.values() if isinstance(result, Path))
    failed = len(results) - successful
    self.logger.info("\nBatch report generation with images completed:")
    self.logger.info(f"  Successful: {successful}")
    self.logger.info(f"  Failed: {failed}")

    return results

gen_group_report

gen_group_report(output_dir: str | Path, subjects: list[str] | None = None, template: str | None = None, sd_threshold: float = 3.0) -> Path

Generate a group report with outlier information for multiple subjects.

Parameters:

  • output_dir

    (str or Path) –

    Directory where HTML report will be saved.

  • subjects

    (list[str] | None, default: None ) –

    List of subject IDs to process. If None, processes all subjects in the subjects directory.

  • template

    (str | None, default: None ) –

    HTML template to use. Default is local group.html.

  • sd_threshold

    (float, default: 3.0 ) –

    Standard deviation threshold for outlier detection. Default is 3.0.

Returns:

  • Path ( Path ) –

    Path to html file.

Source code in src/pyfsviz/freesurfer.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def gen_group_report(
    self,
    output_dir: str | Path,
    subjects: list[str] | None = None,
    template: str | None = None,
    sd_threshold: float = 3.0,
) -> Path:
    """Generate a group report with outlier information for multiple subjects.

    Parameters
    ----------
    output_dir : str or Path
        Directory where HTML report will be saved.
    subjects : list[str] | None
        List of subject IDs to process. If None, processes all subjects
        in the subjects directory.
    template : str | None
        HTML template to use. Default is local group.html.
    sd_threshold : float
        Standard deviation threshold for outlier detection. Default is 3.0.

    Returns
    -------
    Path:
        Path to html file.
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    if subjects is None:
        subjects = self.get_subjects()

    self.logger.info(f"Generating group report for {len(subjects)} subjects...")
    self.logger.info(f"Output directory: {output_dir}")

    # Get stats files
    stats = get_stats(subjects, str(output_dir))

    # Collect all stats files (aparc might be a list)
    stats_files: list[Path] = []
    aseg_value = stats.get("aseg")
    if isinstance(aseg_value, Path):
        stats_files.append(aseg_value)
    aparc_value = stats.get("aparc")
    if isinstance(aparc_value, list):
        stats_files.extend(aparc_value)
    elif isinstance(aparc_value, Path):
        stats_files.append(aparc_value)

    # Generate plots
    plots = gen_metric_plots(stats_files)

    # Convert Plotly figures to HTML strings
    plot_htmls = []
    for fig in plots:
        plot_htmls.append(fig.to_html(full_html=False, include_plotlyjs=True))

    # Check for outliers
    quality_summary = check_metrics(stats_files, sd_threshold=sd_threshold)

    # Prepare template config
    if template is None:
        template = files("pyfsviz._internal.html") / "group.html"

    _config = {
        "timestamp": datetime.datetime.now(tz=datetime.timezone.utc).strftime("%Y-%m-%d, %H:%M"),
        "subjects": subjects,
        "num_subjects": len(subjects),
        "quality_summary": quality_summary,
        "plots": plot_htmls,
        "sd_threshold": sd_threshold,
    }

    # Generate HTML file
    html_file = output_dir / "group_report.html"
    tpl = Template(str(template))
    tpl.generate_conf(_config, str(html_file))

    self.logger.info(f"✓ Generated group report: {html_file}")
    return html_file

gen_html_report

gen_html_report(subject: str, output_dir: str, img_list: list[Path] | None = None, template: str | None = None) -> Path

Generate html report with FreeSurfer images.

Parameters:

  • subject

    (str) –

    Subject ID.

  • output_dir

    (str) –

    HTML file name

  • img_list

    (list[Path] | None, default: None ) –

    List of image paths (PNG format).

  • template

    (str | None, default: None ) –

    HTML template to use. Default is local freesurfer.html.

Returns:

  • Path ( Path ) –

    Path to html file.

Examples:

>>> from pyfsviz.freesurfer import FreeSurfer
>>> fs_dir = FreeSurfer(
...     freesurfer_home="/opt/freesurfer",
...     subjects_dir="/opt/data",
...     subject="sub-001",
... )
>>> report = fs_dir.gen_html_report(out_name="sub-001.html", output_dir=".")
Source code in src/pyfsviz/freesurfer.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
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
def gen_html_report(
    self,
    subject: str,
    output_dir: str,
    img_list: list[Path] | None = None,
    template: str | None = None,
) -> Path:
    """Generate html report with FreeSurfer images.

    Parameters
    ----------
    subject : str
        Subject ID.
    output_dir : str
        HTML file name
    img_list : list[Path] | None
        List of image paths (PNG format).
    template : str | None
        HTML template to use. Default is local freesurfer.html.

    Returns
    -------
    Path:
        Path to html file.

    Examples
    --------
    >>> from pyfsviz.freesurfer import FreeSurfer
    >>> fs_dir = FreeSurfer(
    ...     freesurfer_home="/opt/freesurfer",
    ...     subjects_dir="/opt/data",
    ...     subject="sub-001",
    ... )
    >>> report = fs_dir.gen_html_report(out_name="sub-001.html", output_dir=".")
    """
    if template is None:
        template = files("pyfsviz._internal.html") / "individual.html"
    if img_list is None:
        img_list = list((self.subjects_dir / subject).glob("**/*.{png,svg}"))

    tlrc = []
    aseg = []
    surf = []

    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    # Subject-specific directory
    subject_dir = output_path / subject
    subject_dir.mkdir(parents=True, exist_ok=True)

    for img in img_list:
        if "tlrc" in img.name and img.suffix == ".svg":
            # Read SVG content directly for embedding
            with open(img, encoding="utf-8") as f:
                svg_content = f.read()
            tlrc.append(svg_content)
        # Images are already in the subject directory, just reference by filename
        elif "aparcaseg" in img.name:
            aseg.append(img.name)
        else:
            labels = {
                "lh_pial": "LH Pial",
                "rh_pial": "RH Pial",
                "lh_infl": "LH Inflated",
                "rh_infl": "RH Inflated",
                "lh_white": "LH White Matter",
                "rh_white": "RH White Matter",
            }
            surface_type = img.stem
            surf_tuple = (labels.get(surface_type, surface_type), img.name)
            surf.append(surf_tuple)

    # Read metrics.csv if it exists
    metrics = None
    metrics_csv_path = output_path / "metrics.csv"
    if metrics_csv_path.exists():
        try:
            df = pd.read_csv(metrics_csv_path)
            # Filter for current subject if subject column exists
            if "subject" in df.columns:
                subject_data = df[df["subject"] == subject]
                if not subject_data.empty:
                    metrics = subject_data.iloc[0].to_dict()
            # If no subject column, assume single row
            elif len(df) > 0:
                metrics = df.iloc[0].to_dict()
            # Replace NaN values with None for proper Jinja2 handling
            if metrics:
                metrics = {k: (None if pd.isna(v) else v) for k, v in metrics.items()}
        except (pd.errors.EmptyDataError, pd.errors.ParserError, UnicodeDecodeError, PermissionError, OSError) as e:
            self.logger.warning(f"Could not read metrics.csv: {e}")

    _config = {
        "timestamp": datetime.datetime.now(tz=datetime.timezone.utc).strftime("%Y-%m-%d, %H:%M"),
        "subject": subject,
        "tlrc": tlrc,
        "aseg": aseg,
        "surf": surf,
        "metrics": metrics,
    }

    # Save HTML file in subject directory
    html_file = subject_dir / f"{subject}.html"
    tpl = Template(str(template))
    tpl.generate_conf(_config, str(html_file))

    return html_file

gen_surf_plots

gen_surf_plots(subject: str, output_dir: str) -> list[Path]

Generate pial, inflated, and sulcal images from various viewpoints.

Parameters:

  • output_dir

    (str) –

    Surface plot output directory.

Returns:

  • list[Path]:

    List of generated PNG images

Examples:

>>> from pyfsviz.freesurfer import FreeSurfer
>>> fs_dir = FreeSurfer(
...     freesurfer_home="/opt/freesurfer",
...     subjects_dir="/opt/data",
...     subject="sub-001",
... )
>>> images = fs_dir.gen_surf_plots("sub-001", Path("/opt/data/sub-001/surf"))
Source code in src/pyfsviz/freesurfer.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def gen_surf_plots(self, subject: str, output_dir: str) -> list[Path]:
    """Generate pial, inflated, and sulcal images from various viewpoints.

    Parameters
    ----------
    output_dir : str
        Surface plot output directory.

    Returns
    -------
    list[Path]:
        List of generated PNG images

    Examples
    --------
    >>> from pyfsviz.freesurfer import FreeSurfer
    >>> fs_dir = FreeSurfer(
    ...     freesurfer_home="/opt/freesurfer",
    ...     subjects_dir="/opt/data",
    ...     subject="sub-001",
    ... )
    >>> images = fs_dir.gen_surf_plots("sub-001", Path("/opt/data/sub-001/surf"))
    """
    surf_dir = f"{self.subjects_dir}/{subject}/surf"
    label_dir = f"{self.subjects_dir}/{subject}/label"
    cmap = self.get_colormap()

    hemis = {"lh": "left", "rh": "right"}
    for key, val in hemis.items():
        pial = f"{surf_dir}/{key}.pial"
        inflated = f"{surf_dir}/{key}.inflated"
        sulc = f"{surf_dir}/{key}.sulc"
        white = f"{surf_dir}/{key}.white"
        annot = f"{label_dir}/{key}.aparc.annot"

        label_files = {pial: "pial", inflated: "infl", white: "white"}

        for surf, label in label_files.items():
            fig, axs = plt.subplots(2, 3, subplot_kw={"projection": "3d"})
            plotting.plot_surf_roi(
                surf,
                annot,
                hemi=val,
                view="lateral",
                bg_map=sulc,
                bg_on_data=True,
                darkness=1,
                cmap=cmap,
                axes=axs[0, 0],
                figure=fig,
                colorbar=False,
            )
            plotting.plot_surf_roi(
                surf,
                annot,
                hemi=val,
                view="medial",
                bg_map=sulc,
                bg_on_data=True,
                darkness=1,
                cmap=cmap,
                axes=axs[0, 1],
                figure=fig,
                colorbar=False,
            )
            plotting.plot_surf_roi(
                surf,
                annot,
                hemi=val,
                view="dorsal",
                bg_map=sulc,
                bg_on_data=True,
                darkness=1,
                cmap=cmap,
                axes=axs[0, 2],
                figure=fig,
                colorbar=False,
            )
            plotting.plot_surf_roi(
                surf,
                annot,
                hemi=val,
                view="ventral",
                bg_map=sulc,
                bg_on_data=True,
                darkness=1,
                cmap=cmap,
                axes=axs[1, 0],
                figure=fig,
                colorbar=False,
            )
            plotting.plot_surf_roi(
                surf,
                annot,
                hemi=val,
                view="anterior",
                bg_map=sulc,
                bg_on_data=True,
                darkness=1,
                cmap=cmap,
                axes=axs[1, 1],
                figure=fig,
                colorbar=False,
            )
            plotting.plot_surf_roi(
                surf,
                annot,
                hemi=val,
                view="posterior",
                bg_map=sulc,
                bg_on_data=True,
                darkness=1,
                cmap=cmap,
                axes=axs[1, 2],
                figure=fig,
                colorbar=False,
            )

            plt.savefig(f"{output_dir}/{key}_{label}.png", dpi=300, format="png")
            plt.close()

    return sorted(Path(output_dir).glob("*.png"))

gen_tlrc_data

gen_tlrc_data(subject: str, output_dir: str) -> None

Generate inverse talairach data for report generation.

Parameters:

  • output_dir

    (str) –

    Path for intermediate file output.

Examples:

>>> from pyfsviz.freesurfer import FreeSurfer
>>> fs_dir = FreeSurfer(
...     freesurfer_home="/opt/freesurfer",
...     subjects_dir="/opt/data",
...     subject="sub-001",
... )
>>> fs_dir.gen_tlrc_data("sub-001", Path("/opt/data/sub-001/mri/transforms"))
Source code in src/pyfsviz/freesurfer.py
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
def gen_tlrc_data(self, subject: str, output_dir: str) -> None:
    """Generate inverse talairach data for report generation.

    Parameters
    ----------
    output_dir : str
        Path for intermediate file output.

    Examples
    --------
    >>> from pyfsviz.freesurfer import FreeSurfer
    >>> fs_dir = FreeSurfer(
    ...     freesurfer_home="/opt/freesurfer",
    ...     subjects_dir="/opt/data",
    ...     subject="sub-001",
    ... )
    >>> fs_dir.gen_tlrc_data("sub-001", Path("/opt/data/sub-001/mri/transforms"))
    """
    # get inverse transform
    lta_file = self.subjects_dir / subject / "mri" / "transforms" / "talairach.xfm.lta"
    xfm = np.genfromtxt(lta_file, skip_header=5, max_rows=4)
    inverse_xfm = np.linalg.inv(xfm)
    np.savetxt(
        f"{output_dir}/inv.xfm",
        inverse_xfm,
        fmt="%0.8f",
        delimiter=" ",
        newline="\n",
        encoding="utf-8",
    )

    # convert subject original T1 to nifti (for FSL)
    convert = MRIConvert(
        in_file=self.subjects_dir / subject / "mri" / "orig.mgz",
        out_file=f"{output_dir}/orig.nii.gz",
        out_type="niigz",
    )
    convert.run()

    # use FSL to convert template file to subject original space
    flirt = FLIRT(
        in_file=self._mni_nii,
        reference=f"{output_dir}/orig.nii.gz",
        out_file=f"{output_dir}/mni2orig.nii.gz",
        in_matrix_file=f"{output_dir}/inv.xfm",
        apply_xfm=True,
        out_matrix_file=f"{output_dir}/out.mat",
    )
    flirt.run()

gen_tlrc_report

gen_tlrc_report(subject: str, output_dir: str, tlrc_dir: str | None = None, *, gen_data: bool = True) -> Path

Generate a before and after report of Talairach registration. (Will also run file generation if needed).

Parameters:

  • subject

    (str) –

    Subject ID.

  • output_dir

    (str) –

    Path to SVG output.

  • gen_data

    (bool, default: True ) –

    Generate inverse Talairach data, by default True

  • tlrc_dir

    (str | None, default: None ) –

    Path to output of gen_tlrc_data. Default is the subject's mri/transforms directory.

Returns:

  • Path ( Path ) –

    SVG file generated from the niworkflows SimpleBeforeAfterRPT

Examples:

>>> from pyfsviz.freesurfer import FreeSurfer
>>> fs_dir = FreeSurfer(
...     freesurfer_home="/opt/freesurfer",
...     subjects_dir="/opt/data",
...     subject="sub-001",
... )
>>> report = fs_dir.gen_tlrc_report(
...     "sub-001", Path("/opt/data/sub-001/mri/transforms")
... )
Source code in src/pyfsviz/freesurfer.py
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
def gen_tlrc_report(
    self,
    subject: str,
    output_dir: str,
    tlrc_dir: str | None = None,
    *,
    gen_data: bool = True,
) -> Path:
    """Generate a before and after report of Talairach registration. (Will also run file generation if needed).

    Parameters
    ----------
    subject : str
        Subject ID.
    output_dir : str
        Path to SVG output.
    gen_data : bool
        Generate inverse Talairach data, by default True
    tlrc_dir : str | None
        Path to output of `gen_tlrc_data`. Default is the subject's mri/transforms directory.

    Returns
    -------
    Path:
        SVG file generated from the niworkflows SimpleBeforeAfterRPT

    Examples
    --------
    >>> from pyfsviz.freesurfer import FreeSurfer
    >>> fs_dir = FreeSurfer(
    ...     freesurfer_home="/opt/freesurfer",
    ...     subjects_dir="/opt/data",
    ...     subject="sub-001",
    ... )
    >>> report = fs_dir.gen_tlrc_report(
    ...     "sub-001", Path("/opt/data/sub-001/mri/transforms")
    ... )
    """
    if tlrc_dir is None:
        tlrc_dir = f"{self.subjects_dir}/{subject}/mri/transforms"

    mri_dir = f"{self.subjects_dir}/{subject}/mri"

    if gen_data:
        self.gen_tlrc_data(subject, tlrc_dir)

    # use white matter segmentation to compare registrations
    report = SimpleBeforeAfterRPT(
        before=f"{mri_dir}/orig.mgz",
        after=f"{tlrc_dir}/mni2orig.nii.gz",
        wm_seg=f"{mri_dir}/wm.mgz",
        before_label="Subject Orig",
        after_label="Template",
        out_report=f"{output_dir}/tlrc.svg",
    )
    result = report.run()
    return result.outputs.out_report

get_colormap

get_colormap() -> ListedColormap

Return the colormap for the FreeSurfer data.

Source code in src/pyfsviz/freesurfer.py
115
116
117
def get_colormap(self) -> colors.ListedColormap:
    """Return the colormap for the FreeSurfer data."""
    return get_freesurfer_colormap(self.freesurfer_home)

get_subjects

get_subjects() -> list[str]

Return the subjects in the subjects directory.

Source code in src/pyfsviz/freesurfer.py
119
120
121
122
123
124
125
def get_subjects(self) -> list[str]:
    """Return the subjects in the subjects directory."""
    return [
        subject.name
        for subject in self.subjects_dir.iterdir()
        if subject.is_dir() and (subject / "mri" / "transforms" / "talairach.lta").exists()
    ]

get_freesurfer_colormap

get_freesurfer_colormap(freesurfer_home: Path | str) -> ListedColormap

Generate matplotlib colormap from FreeSurfer LUT.

Code from: https://github.com/Deep-MI/qatools-python/blob/freesurfer-module-releases/qatoolspython/createScreenshots.py

Parameters:

  • freesurfer_home

    (path or str representing a path to a directory) –

    Path corresponding to FREESURFER_HOME env var.

Returns:

  • colormap ( ListedColormap ) –

    A matplotlib compatible FreeSurfer colormap.

Source code in src/pyfsviz/freesurfer.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def get_freesurfer_colormap(freesurfer_home: Path | str) -> colors.ListedColormap:
    """Generate matplotlib colormap from FreeSurfer LUT.

    Code from:
    https://github.com/Deep-MI/qatools-python/blob/freesurfer-module-releases/qatoolspython/createScreenshots.py

    Parameters
    ----------
    freesurfer_home : path or str representing a path to a directory
        Path corresponding to FREESURFER_HOME env var.

    Returns
    -------
    colormap : matplotlib.colors.ListedColormap
        A matplotlib compatible FreeSurfer colormap.

    """
    freesurfer_home = Path(freesurfer_home) if isinstance(freesurfer_home, str) else freesurfer_home
    lut = pd.read_csv(
        freesurfer_home / "FreeSurferColorLUT.txt",
        sep=r"\s+",
        comment="#",
        header=None,
        skipinitialspace=True,
        skip_blank_lines=True,
    )
    lut = np.array(lut)
    lut_tab = np.array(lut[:, (2, 3, 4, 5)] / 255, dtype="float32")
    lut_tab[:, 3] = 1

    return colors.ListedColormap(lut_tab)