{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1979279f",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import brainmass\n",
    "import brainstate\n",
    "import brainunit as u\n",
    "import jax\n",
    "import jax.numpy as jnp\n",
    "import numpy as np\n",
    "brainstate.environ.set(dt=0.1 * u.ms)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e3849e3",
   "metadata": {},
   "source": [
    "# FAQ and Troubleshooting\n",
    "\n",
    "Frequently asked questions and solutions to common problems.\n",
    "\n",
    "## Installation Issues\n",
    "\n",
    "**Q: ImportError: cannot import 'brainstate'**\n",
    "\n",
    "A: Ensure brainstate is installed and up to date:\n",
    "\n",
    "```bash\n",
    "pip install --upgrade brainstate>=0.2.9\n",
    "```\n",
    "\n",
    "**Q: JAX not detecting GPU**\n",
    "\n",
    "A: Check CUDA installation and reinstall JAX with CUDA support:\n",
    "\n",
    "```bash\n",
    "pip install --upgrade jax[cuda12_pip] -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html\n",
    "```\n",
    "\n",
    "**Q: ModuleNotFoundError for brainunit**\n",
    "\n",
    "A: Install or update brainunit:\n",
    "\n",
    "```bash\n",
    "pip install --upgrade brainunit\n",
    "```\n",
    "\n",
    "## Usage Questions\n",
    "\n",
    "**Q: Which model should I use for fMRI?**\n",
    "\n",
    "A: Use {class}`WongWangStep` or {class}`WilsonCowanStep`. They have slow synaptic dynamics suitable for BOLD timescales. See {doc}`howto/choose_a_model`.\n",
    "\n",
    "**Q: How do I fit parameters to my data?**\n",
    "\n",
    "A: See {doc}`tutorials/06_fitting_with_gradients` for complete workflow. Use Nevergrad for gradient-free or JAX+Optax for gradient-based optimization.\n",
    "\n",
    "**Q: Can I use custom connectivity matrices?**\n",
    "\n",
    "A: Yes! Load your structural connectivity (DTI) as a numpy/JAX array and pass to {class}`DiffusiveCoupling` or {class}`AdditiveCoupling`.\n",
    "\n",
    "**Q: How do I add noise to models?**\n",
    "\n",
    "A: Assign a noise object to model attributes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f97e514",
   "metadata": {},
   "outputs": [],
   "source": [
    "model.noise = brainmass.OUProcess(in_size=10, sigma=0.5, tau=20)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d247453",
   "metadata": {},
   "source": [
    "## Performance Issues\n",
    "\n",
    "**Q: Simulations are slow**\n",
    "\n",
    "A: Solutions:\n",
    "\n",
    "- Use JIT compilation: Wrap simulation in `@jax.jit`\n",
    "- Use simpler models (Hopf vs Jansen-Rit)\n",
    "- Reduce number of time steps\n",
    "- Enable GPU if available\n",
    "\n",
    "**Q: Out of memory errors**\n",
    "\n",
    "A: Solutions:\n",
    "\n",
    "- Reduce batch size\n",
    "- Downsample time series before analysis\n",
    "- Use CPU for very large networks\n",
    "- Set `XLA_PYTHON_CLIENT_PREALLOCATE=false`\n",
    "\n",
    "**Q: Gradients are NaN**\n",
    "\n",
    "A: Causes and fixes:\n",
    "\n",
    "- Clip gradients: `jnp.clip(grads, -1, 1)`\n",
    "- Reduce learning rate\n",
    "- Check for division by zero\n",
    "- Normalize loss function\n",
    "\n",
    "## Model Behavior\n",
    "\n",
    "**Q: Network activity explodes**\n",
    "\n",
    "A: Solutions:\n",
    "\n",
    "- Reduce coupling strength `k`\n",
    "- Normalize connectivity matrix\n",
    "- Add noise for stability\n",
    "- Check parameter ranges\n",
    "\n",
    "**Q: No synchronization in network**\n",
    "\n",
    "A: Solutions:\n",
    "\n",
    "- Increase coupling strength\n",
    "- Check connectivity (any isolated nodes?)\n",
    "- Run longer simulation\n",
    "- Verify diffusive vs additive coupling\n",
    "\n",
    "**Q: BOLD signal doesn't stabilize**\n",
    "\n",
    "A: Solutions:\n",
    "\n",
    "- Run longer simulation (>60s)\n",
    "- Check hemodynamic parameters\n",
    "- Discard initial transient (~20s)\n",
    "\n",
    "## Unit Errors\n",
    "\n",
    "**Q: DimensionMismatch error**\n",
    "\n",
    "A: Ensure compatible units:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61c75072",
   "metadata": {},
   "outputs": [],
   "source": [
    "# WRONG:\n",
    "time_ms = 10 * u.ms\n",
    "rate_Hz = 5 * u.Hz\n",
    "result = time_ms + rate_Hz  # Error!\n",
    "\n",
    "# CORRECT:\n",
    "result = time_ms * rate_Hz  # Dimensionless"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8599f569",
   "metadata": {},
   "source": [
    "**Q: Lost units after JAX operations**\n",
    "\n",
    "A: Some JAX functions strip units. Reattach:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6db7ae2",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_with_units = 10 * u.ms\n",
    "y = jnp.exp(x_with_units.magnitude)  # Convert to magnitude\n",
    "y_with_units = y * u.dimensionless   # Reattach appropriate unit"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c5729ad",
   "metadata": {},
   "source": [
    "**Q: How to convert units?**\n",
    "\n",
    "A:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c0b7e08",
   "metadata": {},
   "outputs": [],
   "source": [
    "tau_ms = 10 * u.ms\n",
    "tau_s = tau_ms.to(u.second)  # 0.01 s"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a249922d",
   "metadata": {},
   "source": [
    "## Data and Modeling\n",
    "\n",
    "**Q: Where can I get structural connectivity data?**\n",
    "\n",
    "A: Sources:\n",
    "\n",
    "- Human Connectome Project\n",
    "- OpenNeuro\n",
    "- Lab collaborations\n",
    "- Synthetic networks for testing\n",
    "\n",
    "**Q: What atlases are commonly used?**\n",
    "\n",
    "A: Common choices:\n",
    "\n",
    "- AAL (90/116 regions)\n",
    "- Desikan-Killiany (68 regions)\n",
    "- Schaefer (100-1000 parcels)\n",
    "- Destrieux (148 regions)\n",
    "\n",
    "**Q: How to compute functional connectivity?**\n",
    "\n",
    "A:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e33dc93f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pearson correlation\n",
    "FC = jnp.corrcoef(bold_timeseries.T)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c96572d",
   "metadata": {},
   "source": [
    "**Q: How to validate my model?**\n",
    "\n",
    "A: Compare:\n",
    "\n",
    "- Simulated vs empirical FC\n",
    "- Power spectra\n",
    "- Phase locking value\n",
    "- Dynamic FC\n",
    "\n",
    "## Common Errors\n",
    "\n",
    "**Error: \"Hidden state not initialized\"**\n",
    "\n",
    "Fix: Call `model.init_all_states()` before `model.update()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3db443f",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = brainmass.HopfStep(in_size=10)\n",
    "model.init_all_states()  # Required!\n",
    "model.update()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6ca7894",
   "metadata": {},
   "source": [
    "**Error: \"Shape mismatch in coupling\"**\n",
    "\n",
    "Fix: Ensure connectivity matrix matches node dimensions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02816c09",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 90\n",
    "nodes = brainmass.HopfStep(in_size=N)\n",
    "W = jnp.ones((N, N))  # Must be (N, N)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c213d080",
   "metadata": {},
   "source": [
    "**Error: \"Module 'brainmass' has no attribute 'X'\"**\n",
    "\n",
    "Fix: Check spelling or see {doc}`reference/index` for available models.\n",
    "\n",
    "## Advanced Topics\n",
    "\n",
    "**Q: Can I use brainmass with TensorFlow/PyTorch?**\n",
    "\n",
    "A: No, brainmass is built on JAX. For interoperability, convert arrays manually, but most functionality requires JAX.\n",
    "\n",
    "**Q: How to implement custom models?**\n",
    "\n",
    "A: See {doc}`developer/creating_models` for detailed guide.\n",
    "\n",
    "**Q: Can I use different models for different regions?**\n",
    "\n",
    "A: Yes! Create separate model instances and manually couple them. See {doc}`tutorials/04_building_a_network`.\n",
    "\n",
    "**Q: How to parallelize simulations?**\n",
    "\n",
    "A: Use JAX's `vmap` for batching or `pmap` for multi-device:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bdbb595",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Batch dimension\n",
    "model.init_all_states(batch_size=32)\n",
    "\n",
    "# Or vmap over parameter sets\n",
    "vmap_simulate = jax.vmap(simulate_fn, in_axes=(0, None))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a32dadd6",
   "metadata": {},
   "source": [
    "## Getting Help\n",
    "\n",
    "If your question isn't answered here:\n",
    "\n",
    "1. **Search Documentation:** Use search box (top-right)\n",
    "2. **Check Examples:** {doc}`gallery/index`\n",
    "3. **GitHub Issues:** Report bugs at [github.com/chaobrain/brainmass/issues](https://github.com/chaobrain/brainmass/issues)\n",
    "4. **Discussions:** Ask questions at GitHub Discussions\n",
    "5. **Email:** Contact maintainers for urgent issues\n",
    "\n",
    "## See Also\n",
    "\n",
    "- {doc}`tutorials/index` - Tutorials for common tasks\n",
    "- {doc}`reference/index` - Complete API reference\n",
    "- {doc}`gallery/index` - Working examples\n",
    "- {doc}`developer/index` - For contributors"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
