Skip to content

freesurfer

FreeSurfer data.

Classes:

Functions:

FreeSurfer

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

Base class for FreeSurfer data.

Parameters:

  • freesurfer_home

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

    Path corresponding to FREESURFER_HOME env var.

  • subjects_dir

    (str or ``Path`` 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 FreeSurfer subjects found in a directory.

  • resolve_groups

    Resolve group definitions to subject ID lists from FreeSurfer directories.

  • subject_summary

    Collect a compact individual-report summary from the subject tree.

Attributes:

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

    Parameters
    ----------
    freesurfer_home : str or ``Path`` representing a path to a directory
        Path corresponding to FREESURFER_HOME env var.
    subjects_dir : str or ``Path`` 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)

    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."""
    elif isinstance(subjects_dir, Path):
        self.subjects_dir = subjects_dir
        if not self.subjects_dir.exists():
            raise FileNotFoundError(f"SUBJECTS_DIR not found: {self.subjects_dir}")
        os.environ["SUBJECTS_DIR"] = str(subjects_dir)
        """Path to the subjects directory."""
    else:
        self.subjects_dir = Path(subjects_dir)
        if not self.subjects_dir.exists():
            raise FileNotFoundError(f"SUBJECTS_DIR not found: {self.subjects_dir}")
        os.environ["SUBJECTS_DIR"] = 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(os.environ.get('FREESURFER_HOME') or '')

Path to the FreeSurfer home directory.

logger instance-attribute

logger = logging.getLogger(f'{__name__}.{self.__class__.__name__}')

Logger for the FreeSurfer class.

subjects_dir instance-attribute

subjects_dir = Path(os.environ.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
505
506
507
508
509
510
511
512
513
514
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"

    if not recon_file:
        return False

    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",
... )
>>> images = fs_dir.gen_aparcaseg_plots("sub-001", "/opt/data/reports/sub-001")
Source code in src/pyfsviz/freesurfer.py
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
681
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
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",
    ... )
    >>> images = fs_dir.gen_aparcaseg_plots("sub-001", "/opt/data/reports/sub-001")
    """
    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.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, skip_existing: bool = False) -> 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.

  • skip_existing

    (bool, default: False ) –

    If True, skip subjects that already have an HTML report at {output_dir}/{subject}/{subject}.html. Incomplete subjects (images but no report) are still processed. Default is False.

Returns:

  • dict[str, Path | Exception]

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

Examples:

>>> from pyfsviz.freesurfer import FreeSurfer
>>> fs = FreeSurfer()
>>> results = fs.gen_batch_reports("reports/")
>>> 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
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
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,
    skip_existing: bool = False,
) -> 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.
    skip_existing : bool
        If True, skip subjects that already have an HTML report at
        ``{output_dir}/{subject}/{subject}.html``. Incomplete subjects
        (images but no report) are still processed. Default is False.

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

    Examples
    --------
    >>> from pyfsviz.freesurfer import FreeSurfer
    >>> fs = FreeSurfer()
    >>> results = fs.gen_batch_reports("reports/")
    >>> 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] = {}
    skipped = 0

    for i, subject in enumerate(subjects, 1):
        existing_html = output_dir / subject / f"{subject}.html"
        if skip_existing and existing_html.is_file():
            self.logger.info(
                f"[{i}/{len(subjects)}] Skipping {subject}: report already exists",
            )
            results[subject] = existing_html
            skipped += 1
            continue

        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 = _report_image_files(subject_output_dir)

            # 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)) - skipped
    failed = len(results) - successful - skipped
    self.logger.info("\nBatch report generation with images completed:")
    self.logger.info(f"  Successful: {successful}")
    self.logger.info(f"  Skipped: {skipped}")
    self.logger.info(f"  Failed: {failed}")

    return results

gen_group_report

gen_group_report(output_dir: str | Path, subjects: list[str] | None = None, groups: _GroupDefinition | 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.

  • groups

    (_GroupDefinition | None, default: None ) –

    Optional group definitions for between-group box plots. Each group can be a list of subject IDs or a FreeSurfer directory to scan:

    • ["control", "patient"] scans subjects_dir/control and subjects_dir/patient
    • {"control": None, "patient": None} same as above
    • {"control": "/path/to/control_cohort"} scans an explicit path
    • {"control": ["sub-001"]} uses explicit subject IDs
  • 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
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
def gen_group_report(
    self,
    output_dir: str | Path,
    subjects: list[str] | None = None,
    groups: _GroupDefinition | 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.
    groups : _GroupDefinition | None
        Optional group definitions for between-group box plots. Each group
        can be a list of subject IDs or a FreeSurfer directory to scan:

        - ``["control", "patient"]`` scans ``subjects_dir/control`` and
          ``subjects_dir/patient``
        - ``{"control": None, "patient": None}`` same as above
        - ``{"control": "/path/to/control_cohort"}`` scans an explicit path
        - ``{"control": ["sub-001"]}`` uses explicit subject IDs
    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)

    group_search_dirs: dict[str, Path] | None = None
    resolved_groups: dict[str, list[str]] | None = None
    if groups is not None:
        if subjects is not None:
            self.logger.warning(
                "Both subjects and groups were provided; using subjects from groups",
            )
        group_search_dirs = self._group_search_dirs(groups)
        resolved_groups = self.resolve_groups(groups)
        subjects = [subject for group_subjects in resolved_groups.values() for subject in group_subjects]
    elif subjects is None or len(subjects) < 1:
        subjects = self.get_subjects()

    self.logger.info(f"Generating group report for {len(subjects)} subjects...")
    if resolved_groups:
        for group_name, group_subjects in resolved_groups.items():
            self.logger.info(
                f"  Group {group_name}: {len(group_subjects)} subject(s)",
            )
    self.logger.info(f"Output directory: {output_dir}")

    stats_files = self._collect_group_stats_files(
        output_dir,
        subjects,
        resolved_groups,
        group_search_dirs,
    )

    # Generate plots
    metric_figures = gen_metric_plots(stats_files)
    comparison_figures = gen_group_comparison_plots(stats_files, resolved_groups) if resolved_groups else []
    comparison_plots = _plot_sections(
        comparison_figures,
        prefix="cmp",
        include_plotlyjs_first=bool(comparison_figures),
    )
    plot_sections = _plot_sections(
        metric_figures,
        prefix="plots",
        include_plotlyjs_first=not comparison_figures,
    )
    plot_htmls = [html for section in plot_sections for html in section["plots"]]

    quality_summary = check_metrics(stats_files, sd_threshold=sd_threshold)
    quality_sections = _quality_summary_sections(quality_summary)
    outlier_subjects = summarize_outlier_subjects(quality_summary)

    # Prepare template config
    if template is None:
        template = str(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),
        "groups": resolved_groups,
        "quality_summary": quality_summary,
        "quality_sections": quality_sections,
        "outlier_subjects": outlier_subjects,
        "plots": plot_htmls,
        "plot_sections": plot_sections,
        "comparison_plots": comparison_plots,
        "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",
... )
>>> report = fs_dir.gen_html_report("sub-001", "/opt/data/reports")
Source code in src/pyfsviz/freesurfer.py
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
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",
    ... )
    >>> report = fs_dir.gen_html_report("sub-001", "/opt/data/reports")
    """
    if template is None:
        template = str(files("pyfsviz._internal.html") / "individual.html")
    if img_list is None:
        img_list = _report_image_files(self.subjects_dir / subject)

    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)
        elif "aparc_legend" in img.stem:
            continue
        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)

    summary = self.subject_summary(subject)
    summary["generated_at"] = datetime.datetime.now(tz=datetime.timezone.utc).strftime(
        "%Y-%m-%d, %H:%M",
    )

    _config = {
        "timestamp": summary["generated_at"],
        "subject": subject,
        "summary": summary,
        "tlrc": tlrc,
        "aseg": aseg,
        "surf": surf,
    }

    # 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",
... )
>>> images = fs_dir.gen_surf_plots("sub-001", "/opt/data/reports/sub-001")
Source code in src/pyfsviz/freesurfer.py
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
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",
    ... )
    >>> images = fs_dir.gen_surf_plots("sub-001", "/opt/data/reports/sub-001")
    """
    surf_dir = f"{self.subjects_dir}/{subject}/surf"
    label_dir = f"{self.subjects_dir}/{subject}/label"
    generated: list[Path] = []

    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"
        cmap_info = _aparc_surf_cmap(Path(annot))
        if cmap_info is None:
            cmap: colors.Colormap = self.get_colormap()
            vmin: float | None = None
            vmax: float | None = None
        else:
            cmap, n_colors = cmap_info
            vmin, vmax = 0.0, float(n_colors)

        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"})
            for view, row, col in _SURF_VIEWS:
                plotting.plot_surf_roi(
                    surf,
                    annot,
                    hemi=val,
                    view=view,
                    bg_map=sulc,
                    bg_on_data=True,
                    darkness=1,
                    cmap=cmap,
                    vmin=vmin,
                    vmax=vmax,
                    axes=axs[row, col],
                    figure=fig,
                    colorbar=False,
                )

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

    return sorted(generated)

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",
... )
>>> fs_dir.gen_tlrc_data("sub-001", "/opt/data/sub-001/mri/transforms")
Source code in src/pyfsviz/freesurfer.py
546
547
548
549
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
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",
    ... )
    >>> fs_dir.gen_tlrc_data("sub-001", "/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",
... )
>>> report = fs_dir.gen_tlrc_report("sub-001", "/opt/data/reports/sub-001")
Source code in src/pyfsviz/freesurfer.py
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
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",
    ... )
    >>> report = fs_dir.gen_tlrc_report("sub-001", "/opt/data/reports/sub-001")
    """
    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
309
310
311
def get_colormap(self) -> colors.ListedColormap:
    """Return the colormap for the FreeSurfer data."""
    return get_freesurfer_colormap(self.freesurfer_home)

get_subjects

get_subjects(search_dir: str | Path | None = None) -> list[str]

Return FreeSurfer subjects found in a directory.

Parameters:

  • search_dir

    (str | Path | None, default: None ) –

    Directory to scan for subject folders. Defaults to self.subjects_dir.

Returns:

  • list[str]

    Subject IDs with a completed talairach transform.

Source code in src/pyfsviz/freesurfer.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def get_subjects(self, search_dir: str | Path | None = None) -> list[str]:
    """Return FreeSurfer subjects found in a directory.

    Parameters
    ----------
    search_dir
        Directory to scan for subject folders. Defaults to ``self.subjects_dir``.

    Returns
    -------
    list[str]
        Subject IDs with a completed talairach transform.
    """
    base = self.subjects_dir if search_dir is None else Path(search_dir)
    if not base.exists():
        msg = f"Subject search directory not found: {base}"
        raise FileNotFoundError(msg)

    return sorted(
        subject.name
        for subject in base.iterdir()
        if subject.is_dir() and (subject / "mri" / "transforms" / "talairach.lta").exists()
    )

resolve_groups

resolve_groups(groups: _GroupDefinition) -> dict[str, list[str]]

Resolve group definitions to subject ID lists from FreeSurfer directories.

Each group can be defined as:

  • A list of subject IDs (explicit membership)
  • None or omitted value: scan subjects_dir / group_name
  • A path string or Path: scan that directory for subject folders

Parameters:

  • groups

    (_GroupDefinition) –

    Group names mapped to subject lists or directories, or a list of subdirectory names under subjects_dir.

Returns:

  • dict[str, list[str]]

    Mapping of group names to discovered subject IDs.

Source code in src/pyfsviz/freesurfer.py
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
def resolve_groups(self, groups: _GroupDefinition) -> dict[str, list[str]]:
    """Resolve group definitions to subject ID lists from FreeSurfer directories.

    Each group can be defined as:

    - A list of subject IDs (explicit membership)
    - ``None`` or omitted value: scan ``subjects_dir / group_name``
    - A path string or ``Path``: scan that directory for subject folders

    Parameters
    ----------
    groups
        Group names mapped to subject lists or directories, or a list of
        subdirectory names under ``subjects_dir``.

    Returns
    -------
    dict[str, list[str]]
        Mapping of group names to discovered subject IDs.
    """
    resolved: dict[str, list[str]] = {}
    group_items: list[tuple[str, _GroupSpec]] = (
        [(name, None) for name in groups] if isinstance(groups, list) else list(groups.items())
    )

    for group_name, group_spec in group_items:
        if isinstance(group_spec, list):
            resolved[group_name] = group_spec
            continue

        if group_spec is None or group_spec == "":
            search_dir = self.subjects_dir / group_name
        else:
            search_path = Path(group_spec)
            search_dir = search_path if search_path.is_absolute() else self.subjects_dir / search_path

        subjects = self.get_subjects(search_dir)
        if not subjects:
            self.logger.warning(
                f"No FreeSurfer subjects found for group '{group_name}' in {search_dir}",
            )
        resolved[group_name] = subjects

    return resolved

subject_summary

subject_summary(subject: str) -> dict[str, Any]

Collect a compact individual-report summary from the subject tree.

Parameters:

  • subject

    (str) –

    Subject ID.

Returns:

  • dict[str, Any]

    Fields for the individual HTML summary card.

Source code in src/pyfsviz/freesurfer.py
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
def subject_summary(
    self,
    subject: str,
) -> dict[str, Any]:
    """Collect a compact individual-report summary from the subject tree.

    Parameters
    ----------
    subject : str
        Subject ID.

    Returns
    -------
    dict[str, Any]
        Fields for the individual HTML summary card.
    """
    recon_info = self._get_recon_info(subject)
    tlrc_info = self._check_talairach(subject)

    return {
        "subject": subject,
        "recon_status": "finished without error" if self.check_recon_all(subject) else "recon failed",
        "runtime": _format_runtime(float(recon_info["runtime"])),
        "fs_version": recon_info["version"],
        "command": recon_info["command"],
        "talairach_afd": tlrc_info["afd"],
        "talairach_qa": tlrc_info["qa"],
        "talairach_zscore": tlrc_info["z-score"],
    }

get_freesurfer_colormap

get_freesurfer_colormap(freesurfer_home: Path | str) -> ListedColormap

Generate matplotlib colormap from FreeSurfer LUT.

Code from: https://github.com/Deep-MI/fsqc/blob/stable/fsqc/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
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def get_freesurfer_colormap(freesurfer_home: Path | str) -> colors.ListedColormap:
    """Generate matplotlib colormap from FreeSurfer LUT.

    Code from:
    https://github.com/Deep-MI/fsqc/blob/stable/fsqc/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,
        names=range(8),  # FS8+ adds col for tissue class, so allow extra cols when reading in
        skipinitialspace=True,
        skip_blank_lines=True,
    )
    lut = lut.iloc[:, :6].dropna(subset=[0, 2, 3, 4, 5])
    lut = np.array(lut)

    lut_tab = np.array(lut[:, (2, 3, 4, 5)].astype(float) / 255, dtype="float32")
    lut_tab[:, 3] = 1

    return colors.ListedColormap(lut_tab)