{ "cells": [ { "cell_type": "markdown", "id": "16027328", "metadata": {}, "source": [ "# How pyAFQ uses BIDS\n", "\n", "The pyAFQ API relies heavily on the\n", "[Brain Imaging Data Standard (BIDS)](https://bids-specification.readthedocs.io/en/stable/),\n", "a widely used standard for organizing and describing neuroimaging data. This\n", "means that the software assumes that its inputs are organized according to the\n", "BIDS specification and its outputs conform where possible with BIDS.\n", "\n", ":::{note}\n", "Derivatives of processing diffusion MRI are not currently fully\n", "described in the existing BIDS specification, but describing these\n", "is part of an ongoing effort. Wherever possible, we conform with\n", "the draft implementation of the BIDS DWI derivatives available\n", "[here](https://bids-specification.readthedocs.io/en/wip-derivatives/05-derivatives/05-diffusion-derivatives.html).\n", ":::\n", "\n", "In this example, we will explore the use of BIDS in pyAFQ and see\n", "how BIDS allows us to extend and provide flexibility to the users\n", "of the software." ] }, { "cell_type": "code", "execution_count": null, "id": "5560e9a8", "metadata": {}, "outputs": [], "source": [ "import os\n", "import os.path as op\n", "\n", "import AFQ.api.bundle_dict as abd\n", "from AFQ.api.group import GroupAFQ\n", "import AFQ.data.fetch as afd\n", "import AFQ.definitions.image as afm" ] }, { "cell_type": "markdown", "id": "9976bd69", "metadata": {}, "source": [ "To interact with and query BIDS datasets, we use\n", "[pyBIDS](https://bids-standard.github.io/pybids/), which we import here:" ] }, { "cell_type": "code", "execution_count": null, "id": "d19b265f", "metadata": {}, "outputs": [], "source": [ "import bids\n", "from bids.layout import BIDSLayout" ] }, { "cell_type": "markdown", "id": "2b8e077a", "metadata": {}, "source": [ "We start with some example data. The data we will use here is\n", "generated from the\n", "[Stanford HARDI dataset](https://purl.stanford.edu/ng782rw8378).\n", "The call below fetches\n", "this dataset and organized it within the `~/AFQ_data` folder in the BIDS\n", "format." ] }, { "cell_type": "code", "execution_count": null, "id": "85287500", "metadata": {}, "outputs": [], "source": [ "afd.organize_stanford_data(clear_previous_afq=\"all\")" ] }, { "cell_type": "markdown", "id": "d1894634", "metadata": {}, "source": [ "After doing that, we should have a folder that looks like this:\n", "\n", "| stanford_hardi\n", "| ├── dataset_description.json\n", "| └── derivatives\n", "| ├── freesurfer\n", "| │   ├── dataset_description.json\n", "| │   └── sub-01\n", "| │   └── ses-01\n", "| │   └── anat\n", "| │   ├── sub-01_ses-01_T1w.nii.gz\n", "| │   └── sub-01_ses-01_seg.nii.gz\n", "| └── vistasoft\n", "| ├── dataset_description.json\n", "| └── sub-01\n", "| └── ses-01\n", "| └── dwi\n", "| ├── sub-01_ses-01_dwi.bvals\n", "| ├── sub-01_ses-01_dwi.bvecs\n", "| └── sub-01_ses-01_dwi.nii.gz\n", "\n", "The top level directory (`stanford_hardi`) is our overall BIDS dataset folder.\n", "In many cases, this folder will include folders with raw data for each subject\n", "in the dataset. In this case, we do not include the raw data folders and only\n", "have the outputs of pipelines that were used to preprocess the data (e.g.,\n", "correct the data for subject motion, eddy currents, and so forth).\n", "In general, only the preprocessed diffusion data is required for pyAFQ to run.\n", "See the [\"Organizing your data\"](/howto/data) section of the\n", "documentation for more details.\n", "In this case, one folder contains derivative of the Freesurfer software and\n", "another folder contains the DWI data that has been preprocessed with the\n", "Vistasoft software.\n", "pyAFQ provides facilities to segment tractography results obtained\n", "using other software as well. For example, we often use\n", "[qsiprep](https://qsiprep.readthedocs.io/en/latest/) to preprocess\n", "our data and reconstruct tractographies with software such as\n", "[MRTRIX](https://www.mrtrix.org/). Here, we will demonstrate how to use\n", "these reconstructions in the pyAFQ segmentation and tractometry pipeline\n", "We fetch this data and add it as a separate pipeline\n", "The following code will download a previously-created tractography and\n", "organize it by adding it to the BIDS dataset folder and renaming them to be\n", "BIDS-compliant (e.g., `sub-01_ses_01_dwi_tractography.trk`)." ] }, { "cell_type": "code", "execution_count": null, "id": "7efdf877", "metadata": {}, "outputs": [], "source": [ "afd.fetch_stanford_hardi_tractography()\n", "\n", "bids_path = op.join(op.expanduser('~'), 'AFQ_data', 'stanford_hardi')\n", "tractography_path = op.join(bids_path, 'derivatives', 'my_tractography')\n", "sub_path = op.join(tractography_path, 'sub-01', 'ses-01', 'dwi')\n", "\n", "seg_file = op.join(afd.afq_home, \"stanford_hardi\", \"derivatives\",\n", " \"freesurfer\", \"sub-01\", \"ses-01\", \"anat\",\n", " \"sub-01_ses-01_seg.nii.gz\")\n", "pve = afm.PVEImages(\n", " afm.LabelledImageFile(\n", " path=seg_file,\n", " inclusive_labels=[0]),\n", " afm.LabelledImageFile(\n", " path=seg_file,\n", " exclusive_labels=[0, 1, 2], combine=\"and\"),\n", " afm.LabelledImageFile(\n", " path=seg_file,\n", " inclusive_labels=[1, 2]))\n", "\n", "os.makedirs(sub_path, exist_ok=True)\n", "os.rename(\n", " op.join(\n", " op.expanduser('~'),\n", " 'AFQ_data',\n", " 'stanford_hardi_tractography',\n", " 'full_segmented_cleaned_tractography.trk'),\n", " op.join(\n", " sub_path,\n", " 'sub-01_ses-01-dwi_tractography.trk'))\n", "\n", "afd.to_bids_description(\n", " tractography_path,\n", " **{\"Name\": \"my_tractography\",\n", " \"PipelineDescription\": {\"Name\": \"my_tractography\"},\n", " \"GeneratedBy\": [{\"Name\": \"my_tractography\"}]})" ] }, { "cell_type": "markdown", "id": "24064172", "metadata": {}, "source": [ "After we do that, our dataset folder should look like this:\n", "\n", "| stanford_hardi\n", "| ├── dataset_description.json\n", "| └── derivatives\n", "| ├── freesurfer\n", "| │   ├── dataset_description.json\n", "| │   └── sub-01\n", "| │   └── ses-01\n", "| │   └── anat\n", "| │   ├── sub-01_ses-01_T1w.nii.gz\n", "| │   └── sub-01_ses-01_seg.nii.gz\n", "| ├── my_tractography\n", "| | ├── dataset_description.json\n", "| │   └── sub-01\n", "| │   └── ses-01\n", "| │   └── dwi\n", "| │   └── sub-01_ses-01-dwi_tractography.trk\n", "| └── vistasoft\n", "| ├── dataset_description.json\n", "| └── sub-01\n", "| └── ses-01\n", "| └── dwi\n", "| ├── sub-01_ses-01_dwi.bvals\n", "| ├── sub-01_ses-01_dwi.bvecs\n", "| └── sub-01_ses-01_dwi.nii.gz\n", "\n", "To explore the layout of these derivatives, we will initialize a\n", "`BIDSLayout` class instance to help us see what is in this dataset" ] }, { "cell_type": "code", "execution_count": null, "id": "498e03d7", "metadata": {}, "outputs": [], "source": [ "layout = bids.BIDSLayout(bids_path, derivatives=True)" ] }, { "cell_type": "markdown", "id": "5ed71f15", "metadata": {}, "source": [ "Because there is no raw data in this BIDS layout (only derivatives),\n", "pybids will report that there are no subjects and sessions:" ] }, { "cell_type": "code", "execution_count": null, "id": "cc8f4053", "metadata": {}, "outputs": [], "source": [ "print(layout)" ] }, { "cell_type": "markdown", "id": "88e21efa", "metadata": {}, "source": [ "But a query on the derivatives will reveal the different derivatives that\n", "are stored here:" ] }, { "cell_type": "code", "execution_count": null, "id": "36354c3f", "metadata": {}, "outputs": [], "source": [ "print(layout.derivatives)" ] }, { "cell_type": "markdown", "id": "dba44530", "metadata": {}, "source": [ "We can use a `bids.BIDSValidator` object to make sure that the\n", "files within our data set are BIDS-compliant. For example, we can\n", "extract the tractography derivatives part of our layout using:" ] }, { "cell_type": "code", "execution_count": null, "id": "a040de5c", "metadata": {}, "outputs": [], "source": [ "my_tractography = layout.derivatives[\"my_tractography\"]" ] }, { "cell_type": "markdown", "id": "19554c26", "metadata": {}, "source": [ "This variable is also a BIDS layout object. This object has a `get`\n", "method, which allows us to query and find specific items within the\n", "layout. For example, we can ask for files that have a suffix consistent\n", "with tractography results:" ] }, { "cell_type": "code", "execution_count": null, "id": "d7cd742b", "metadata": {}, "outputs": [], "source": [ "tractography_files = my_tractography.get(suffix='tractography')" ] }, { "cell_type": "markdown", "id": "c4211f28", "metadata": {}, "source": [ "Or ask for files that have a `.trk` extension:" ] }, { "cell_type": "code", "execution_count": null, "id": "9d1281df", "metadata": {}, "outputs": [], "source": [ "tractography_files = my_tractography.get(extension='.trk')" ] }, { "cell_type": "markdown", "id": "8f43ec13", "metadata": {}, "source": [ "In this case, both of these would produce the same result." ] }, { "cell_type": "code", "execution_count": null, "id": "54df0f9e", "metadata": {}, "outputs": [], "source": [ "tractography_file = tractography_files[0]\n", "print(tractography_file)" ] }, { "cell_type": "markdown", "id": "090571f7", "metadata": {}, "source": [ "We can also get some more structured information about this file:" ] }, { "cell_type": "code", "execution_count": null, "id": "bfc9a4b7", "metadata": {}, "outputs": [], "source": [ "print(tractography_file.get_entities())" ] }, { "cell_type": "markdown", "id": "70c6c37c", "metadata": {}, "source": [ "We can use a `bids.BIDSValidator` class instance to validate that\n", "this file is compliant with the specification. Note that the validator\n", "requires that the filename be provided relative to the root of the BIDS\n", "dataset, so we have to split the string that contains the full path\n", "of the tractography to extract only the part that is relative to the\n", "root of the entire BIDS `layout` object:" ] }, { "cell_type": "code", "execution_count": null, "id": "f16608e5", "metadata": {}, "outputs": [], "source": [ "tractography_full_path = tractography_file.path\n", "tractography_relative_path = tractography_full_path.split(layout.root)[-1]\n", "\n", "validator = bids.BIDSValidator()\n", "print(validator.is_bids(tractography_relative_path))" ] }, { "cell_type": "markdown", "id": "a434612b", "metadata": {}, "source": [ "Next, we specify the information we need to define the bundles that we are\n", "interested in segmenting. In this case, we are going to use a list of\n", "bundle names for the bundle info. These names refer to bundles for\n", "which we already have clear definitions of the information\n", "needed to segment them (e.g., waypoint ROIs and probability maps).\n", "For an example that includes custom definition of bundle info, see the\n", "[plot_callosal_tract_profile example](http://tractometry.org/pyAFQ/auto_examples/plot_callosal_tract_profile.html)." ] }, { "cell_type": "code", "execution_count": null, "id": "effd0076", "metadata": {}, "outputs": [], "source": [ "bundle_info = abd.default_bd()[\n", " \"Left Inferior Longitudinal\",\n", " \"Right Inferior Longitudinal\",\n", " \"Left Arcuate\",\n", " \"Right Arcuate\",\n", " \"Left Corticospinal\",\n", " \"Right Corticospinal\"]" ] }, { "cell_type": "markdown", "id": "cd635d3f", "metadata": {}, "source": [ "Now, we can define our GroupAFQ object, pointing to the derivatives of the\n", "`'my_tractography'` pipeline as inputs. This is done by setting the\n", "`import_tract` key-word argument. We pass the\n", "`bundle_info` defined above. We also point to the preprocessed\n", "data that is in a `'dmriprep'` pipeline. Note that the pipeline name\n", "is not necessarily the name of the folder it is in; the pipeline name is\n", "defined in each pipeline's `dataset_description.json`. These data were\n", "preprocessed with 'vistasoft', so this is the pipeline we'll point to\n", "If we were using `'qsiprep'`, this is where we would pass that\n", "string instead. If we did that, AFQ would look for a derivatives\n", "folder called `'stanford_hardi/derivatives/qsiprep'` and find the\n", "preprocessed DWI data within it. Finally, to speed things up\n", "a bit, we also sub-sample the provided tractography. This is\n", "done by defining the segmentation_params dictionary input.\n", "To sub-sample to 10,000 streamlines, we define\n", "`'nb_streamlines' = 10000`." ] }, { "cell_type": "code", "execution_count": null, "id": "bd7c09ae", "metadata": {}, "outputs": [], "source": [ "my_afq = GroupAFQ(\n", " bids_path,\n", " dwi_preproc_pipeline='vistasoft',\n", " t1_preproc_pipeline='freesurfer',\n", " bundle_info=bundle_info,\n", " import_tract={\n", " \"suffix\": \"tractography\",\n", " \"scope\": \"my_tractography\"\n", " },\n", " pve=pve,\n", " segmentation_params={'nb_streamlines': 10000})" ] }, { "cell_type": "markdown", "id": "0a264e56", "metadata": {}, "source": [ "Finally, to run the segmentation and extract tract profiles, we call\n", "The `export_all` method. This creates all of the derivative outputs of\n", "AFQ within the 'stanford_hardi/derivatives/afq' folder." ] }, { "cell_type": "code", "execution_count": null, "id": "6ba50717", "metadata": {}, "outputs": [], "source": [ "my_afq.export_all()" ] }, { "cell_type": "markdown", "id": "32c8e56c", "metadata": {}, "source": [ "A few common issues that can hinder BIDS from working properly are:\n", "\n", "1. Faulty `dataset_description.json` file. You need to make sure that the\n", " file contains the right names for the pipeline. See above for an example\n", " of that.\n", "2. File naming convention doesn't uniquely identify file with bids filters." ] }, { "cell_type": "code", "execution_count": null, "id": "4cfd5814", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ff64e3d1", "metadata": {}, "source": [ "The outputs of AFQ are also BIDS compatible. Here we demonstrate how\n", "to load the afq entities and show all files with the key-value pair\n", "desc-bundles" ] }, { "cell_type": "code", "execution_count": null, "id": "ff056842", "metadata": {}, "outputs": [], "source": [ "layout = BIDSLayout(bids_path)\n", "layout.add_derivatives(\n", " f'{bids_path}/derivatives/afq',\n", " config=['bids', 'derivatives'])\n", "print(layout.get(desc=\"bundles\", return_type=\"filename\"))" ] }, { "cell_type": "markdown", "id": "2c745b64", "metadata": {}, "source": [ ":::{only} html\n", "{download}`Download as Jupyter Notebook `\n", ":::" ] } ], "metadata": { "file_format": "mystnb", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "pygments_lexer": "ipython3" }, "mystnb": { "execution_mode": "off" } }, "nbformat": 4, "nbformat_minor": 5 }