{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c25bc5eb",
   "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": "7aebad12",
   "metadata": {},
   "source": [
    "# Architecture\n",
    "\n",
    "Overview of `brainmass` package structure and design.\n",
    "\n",
    "## Package Structure\n",
    "\n",
    "```text\n",
    "brainmass/\n",
    "├── __init__.py          # Public API exports\n",
    "├── _fhn.py              # FitzHugh-Nagumo model\n",
    "├── _hopf.py             # Hopf oscillator\n",
    "├── _jansen_rit.py       # Jansen-Rit model\n",
    "├── _wilson_cowan.py     # Wilson-Cowan model\n",
    "├── _wong_wang.py        # Wong-Wang model\n",
    "├── _vdp.py              # Van der Pol oscillator\n",
    "├── _sl.py               # Stuart-Landau oscillator\n",
    "├── qif.py               # Montbrio-Pazo-Roxin (mean-field) model\n",
    "├── _linear.py           # Threshold-linear model\n",
    "├── _kuramoto.py         # Kuramoto network\n",
    "├── _xy_model.py         # XY oscillator base class\n",
    "├── _noise.py            # Noise processes\n",
    "├── _coupling.py         # Coupling mechanisms\n",
    "├── _forward_model.py    # BOLD, EEG, MEG models\n",
    "├── _horn.py             # HORN models\n",
    "├── _utils.py            # Utility functions\n",
    "└── _typing.py           # Type aliases\n",
    "```\n",
    "\n",
    "## Design Principles\n",
    "\n",
    "1. **Consistency:** All models follow same API pattern\n",
    "2. **Modularity:** Components can be mixed and matched\n",
    "3. **Unit Safety:** Use brainunit for dimensional analysis\n",
    "4. **JAX First:** Designed for JIT compilation and autodiff\n",
    "5. **Simplicity:** Clear, readable code over cleverness\n",
    "\n",
    "## Dependencies\n",
    "\n",
    "**Core:**\n",
    "\n",
    "- `brainstate`: State management for dynamical systems\n",
    "- `brainunit`: Unit-aware computations\n",
    "- `braintools`: Transforms and utilities\n",
    "- `jax`: Numerical computing backend\n",
    "\n",
    "**Rationale:**\n",
    "\n",
    "- Separates concerns (state, units, computation)\n",
    "- Reusable across BrainX ecosystem\n",
    "- Leverages JAX for performance\n",
    "\n",
    "## Model Base Classes\n",
    "\n",
    "All models inherit from `brainstate.nn.Dynamics`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20b842ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "class MyModel(brainstate.nn.Dynamics):\n",
    "    def __init__(self, in_size, **params):\n",
    "        super().__init__()\n",
    "        # Initialize parameters\n",
    "        # Create state variables with HiddenState\n",
    "\n",
    "    def init_state(self, batch_size=None):\n",
    "        # Initialize state variables\n",
    "        pass\n",
    "\n",
    "    def update(self, **inputs):\n",
    "        # Update dynamics by one time step\n",
    "        # Return observable(s)\n",
    "        pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e4ca9fc",
   "metadata": {},
   "source": [
    "## State Management\n",
    "\n",
    "Uses `brainstate.HiddenState` for internal variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9cf7ec82",
   "metadata": {},
   "outputs": [],
   "source": [
    "self.x = brainstate.HiddenState(\n",
    "    brainstate.init.Constant(0.),\n",
    "    sharding=brainstate.ShardingMode.REPLICATED\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c965523",
   "metadata": {},
   "source": [
    "## Coupling Architecture\n",
    "\n",
    "Coupling as separate modules enables:\n",
    "\n",
    "- Reusable across models\n",
    "- Swappable coupling mechanisms\n",
    "- Clear separation of node vs edge dynamics\n",
    "\n",
    "## Forward Models\n",
    "\n",
    "Designed as transformations:\n",
    "\n",
    "```text\n",
    "Neural Activity → Forward Model → Observable Signal\n",
    "(hidden)         (biophysics)    (measured)\n",
    "```\n",
    "\n",
    "## Optimization Support\n",
    "\n",
    "- `ArrayParam` wraps parameters with transforms\n",
    "- Compatible with JAX autodiff\n",
    "- Works with gradient-free optimizers (Nevergrad)\n",
    "\n",
    "## Extension Points\n",
    "\n",
    "Extend `brainmass` by:\n",
    "\n",
    "1. **New models:** Inherit from `Dynamics`\n",
    "2. **New noise:** Inherit from noise base classes\n",
    "3. **New coupling:** Implement coupling interface\n",
    "4. **New forward models:** Follow BOLD/EEG pattern\n",
    "\n",
    "## Code Organization\n",
    "\n",
    "- Private modules: `_module.py` (implementation)\n",
    "- Public API: `__init__.py` (exports)\n",
    "- Tests: `tests/test_module.py`\n",
    "- Examples: `examples/###-name.ipynb`\n",
    "\n",
    "## See Also\n",
    "\n",
    "- {doc}`creating_models` - Build custom models\n",
    "- {doc}`extending_noise` - Custom noise processes\n",
    "- `brainstate` documentation\n",
    "- `brainunit` documentation"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
