{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5b5830b0",
   "metadata": {},
   "source": [
    "# How to add new bundles into pyAFQ (SLF 1/2/3 Example)\n",
    "\n",
    "pyAFQ is designed to be customizable and extensible. This example shows how you\n",
    "can customize it to define a new bundle based on a definition of waypoint and\n",
    "endpoint ROIs of your design.\n",
    "\n",
    "In this case, we add sub-bundles of the superior longitudinal fasciculus,\n",
    "based on work by [Sami et al. 2024](https://doi.org/10.1007/s00429-024-02775-7)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04b459fc-a700-41c2-b8da-84f8dc8f2527",
   "metadata": {},
   "outputs": [],
   "source": [
    "from paths import afq_home"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2946e7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os.path as op\n",
    "import plotly\n",
    "import numpy as np\n",
    "from IPython.display import Image\n",
    "\n",
    "from AFQ.api.group import GroupAFQ\n",
    "import AFQ.api.bundle_dict as abd\n",
    "import AFQ.data.fetch as afd\n",
    "from AFQ.definitions.image import ImageFile, RoiImage\n",
    "np.random.seed(1234)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60531c9d",
   "metadata": {},
   "source": [
    "## Get dMRI data\n",
    "\n",
    "We will analyze twelve subjects from the Healthy Brain Network Processed Open\n",
    "Diffusion Derivatives dataset (HBN-POD2) [](https://doi.org/10.1038/s41597-022-01695-7). \n",
    "\n",
    "The data gets organized into a BIDS-compatible format.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5722ce2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "_, study_dir = afd.fetch_hbn_preproc(['NDARAA948VFH'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67ac80bf",
   "metadata": {},
   "source": [
    "## Define custom `BundleDict` object\n",
    "\n",
    "We define the bundles with include/exclude ROIs and specific cleaning parameters.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe8f9eee",
   "metadata": {},
   "outputs": [],
   "source": [
    "template_dir = op.join(afq_home, 'SLF_ROIs')\n",
    "templates_afq = afd.read_templates(as_img=False)\n",
    "\n",
    "# You can provide paths to the ROIs in the \"include\" and \"exclude\" keys of the bundle definition\n",
    "bundles = abd.BundleDict({\n",
    "    \"L_SLF1\": {\n",
    "        \"include\": [template_dir + '/SFgL.nii.gz', template_dir + '/PaL.nii.gz'],\n",
    "        \"exclude\": [templates_afq['SLFt_roi2_L']],\n",
    "        \"cross_midline\": False,\n",
    "        \"mahal\": {\"clean_rounds\": 20, \"length_threshold\": 4, \"distance_threshold\": 2}\n",
    "    }\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43cfe3a4",
   "metadata": {},
   "source": [
    "## Define GroupAFQ object\n",
    "\n",
    "We configure the AFQ pipeline with predefined parameters and start the process.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7de15b27",
   "metadata": {},
   "outputs": [],
   "source": [
    "brain_mask_definition = ImageFile(\n",
    "    suffix=\"mask\",\n",
    "    filters={'desc': 'brain', 'space': 'T1w', 'scope': 'qsiprep'}\n",
    ")\n",
    "\n",
    "my_afq = GroupAFQ(\n",
    "    bids_path=study_dir,\n",
    "    preproc_pipeline=\"qsiprep\",\n",
    "    participant_labels=[\"NDARAA948VFH\"],\n",
    "    output_dir=op.join(study_dir, \"derivatives\", \"afq_slf\"),\n",
    "    brain_mask_definition=brain_mask_definition,\n",
    "    tracking_params={\"n_seeds\": 4, \"directions\": \"prob\", \"odf_model\": \"CSD\", \"seed_mask\": RoiImage()},\n",
    "    segmentation_params={\"parallel_segmentation\": {\"engine\": \"serial\"}},\n",
    "    bundle_info=bundles\n",
    ")\n",
    "\n",
    "my_afq.export(\"profiles\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6fa991dc",
   "metadata": {},
   "source": [
    "## Visualize a montage\n",
    "\n",
    "We create montage visualizations of the SLF bundles.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13f82991",
   "metadata": {},
   "outputs": [],
   "source": [
    "montage = my_afq.group_montage(\"L_SLF1\", (3, 4), \"Sagittal\", \"left\", slice_pos=0.5)\n",
    "Image(filename=montage[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df9eb39c",
   "metadata": {},
   "source": [
    "## Interactive bundle visualization\n",
    "\n",
    "We export individual bundle figures as interactive HTML files.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a85f865",
   "metadata": {},
   "outputs": [],
   "source": [
    "bundle_html = my_afq.export(\"all_bundles_figure\")\n",
    "plotly.io.show(bundle_html[\"NDARAA948VFH\"][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a841ed20",
   "metadata": {},
   "source": [
    "## References\n",
    "\n",
    "- Richie-Halford A, Cieslak M, Ai L, et al. An analysis-ready and quality\n",
    "  controlled resource for pediatric brain white-matter research. Scientific\n",
    "  Data. 2022.\n",
    "  [](https://doi.org/10.1038/s41597-022-01695-7)\n",
    "\n",
    "- Cieslak M, Cook PA, He X, et al. QSIPrep: an integrative platform for\n",
    "  preprocessing and reconstructing diffusion MRI data. Nat Methods. 2021.\n",
    "  [](https://doi.org/10.1038/s41592-021-01185-5).\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
