{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "110e226b",
   "metadata": {},
   "source": [
    "# Checkpointing\n",
    "\n",
    "Once you have loaded and possibly edited a morphology, you can persist it to\n",
    "disk and reload it later without re-parsing the original reconstruction. This is\n",
    "useful for caching a cleaned-up morphology or sharing a processed cell.\n",
    "\n",
    "## Saving and loading a morphology"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d802a7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import braincell\n",
    "import braincell.io as io\n",
    "\n",
    "morpho = braincell.Morphology.from_swc(\"neuron.swc\")\n",
    "\n",
    "path = io.save_morpho(morpho, \"neuron.bcm\")   # returns the written Path\n",
    "morpho = io.load_morpho(\"neuron.bcm\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b3a007b",
   "metadata": {},
   "source": [
    "For a single branch there are matching helpers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc0c0171",
   "metadata": {},
   "outputs": [],
   "source": [
    "io.save_branch(branch, \"branch.bcb\")\n",
    "branch = io.load_branch(\"branch.bcb\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74b8c6cf",
   "metadata": {},
   "source": [
    "## Versioning and errors\n",
    "\n",
    "Checkpoints are versioned. If you load a file written by an incompatible\n",
    "version, the loaders raise a clear error:\n",
    "\n",
    "- {class}`~braincell.io.CheckpointError` — a checkpoint could not be read.\n",
    "- {class}`~braincell.io.CheckpointVersionError` — the checkpoint's format\n",
    "  version is not supported by the installed `braincell`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cb531c48",
   "metadata": {},
   "outputs": [],
   "source": [
    "from braincell.io import CheckpointVersionError\n",
    "\n",
    "try:\n",
    "    morpho = io.load_morpho(\"old.bcm\")\n",
    "except CheckpointVersionError as e:\n",
    "    print(\"Re-export from the source file:\", e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81c742ee",
   "metadata": {},
   "source": [
    "## See also\n",
    "\n",
    "- {doc}`overview` — loading from the original formats.\n",
    "- {doc}`../apis/io` — the full checkpoint API."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
