{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Ball and stick 1: Basic cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the first part of a several page tutorial that will ultimately build a ring network of mutlicompartment neurons running on a parallel machine.\n", "\n", "Best software engineering practice is to carefully design both the model and code. A well-designed system is easier to debug, maintain, and extend.\n", "\n", "This tutorial will take a functional bottom-up approach, building key components and refactoring as needed for a better software design instead of describing a complex design and filling in the pieces.\n", "\n", "This part of the tutorial builds a two-compartment neuron consisting of a soma and dendrite. This representation is known as a ball-and-stick model. After building the cell, we will attach some instrumentation to it to simulate and monitor its dynamics." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load NEURON" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We of course begin by loading NEURON's main submodule `n`." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:09.591517Z", "iopub.status.busy": "2025-08-18T03:35:09.590573Z", "iopub.status.idle": "2025-08-18T03:35:10.642161Z", "shell.execute_reply": "2025-08-18T03:35:10.641729Z" } }, "outputs": [], "source": [ "from neuron import n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As good practice, we'll load some unit definitions:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:10.645984Z", "iopub.status.busy": "2025-08-18T03:35:10.645767Z", "iopub.status.idle": "2025-08-18T03:35:10.682933Z", "shell.execute_reply": "2025-08-18T03:35:10.682432Z" } }, "outputs": [], "source": [ "from neuron.units import ms, mV, µm" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll load the standard run library to give us high-level simulation control functions (e.g. running a simulation for a given period of time):" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:10.689020Z", "iopub.status.busy": "2025-08-18T03:35:10.688692Z", "iopub.status.idle": "2025-08-18T03:35:10.736611Z", "shell.execute_reply": "2025-08-18T03:35:10.736175Z" } }, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.load_file(\"stdrun.hoc\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we're running in Jupyter, we should allow interactive graphics inline so that we can explore our PlotShapes interactively; skip this line if you're not using Jupyter (it'll cause a syntax error):" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:10.910666Z", "iopub.status.busy": "2025-08-18T03:35:10.906880Z", "iopub.status.idle": "2025-08-18T03:35:40.969840Z", "shell.execute_reply": "2025-08-18T03:35:40.969402Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Matplotlib is building the font cache; this may take a moment.\n" ] } ], "source": [ "%matplotlib notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Defining the cell morphology" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create the sections" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A ball-and-stick cell by definition consists of two parts: the soma (ball) and a dendrite (stick). We could define two Sections at the top level as in the previous tutorial, but that wouldn't give us an easy way to create multiple cells. Instead, let's define a BallAndStick neuron class. The basic boilerplate for defining any class in Python looks like:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:40.976971Z", "iopub.status.busy": "2025-08-18T03:35:40.976731Z", "iopub.status.idle": "2025-08-18T03:35:40.980936Z", "shell.execute_reply": "2025-08-18T03:35:40.980565Z" } }, "outputs": [], "source": [ "class BallAndStick:\n", " def __init__(self):\n", " \"\"\"anything that should be done every time one of these is created goes here\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In our case in particular, every time we say that there is a BallAndStick cell, we should create the soma and the dendrite sections:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:40.987868Z", "iopub.status.busy": "2025-08-18T03:35:40.987714Z", "iopub.status.idle": "2025-08-18T03:35:40.992566Z", "shell.execute_reply": "2025-08-18T03:35:40.991138Z" } }, "outputs": [], "source": [ "class BallAndStick:\n", " def __init__(self):\n", " self.soma = n.Section(\"soma\", self)\n", " self.dend = n.Section(\"dend\", self)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any variables that describe properties of the cell must get stored as attributes of self. This is why we write self.soma instead of soma. Temporary variables, on the other hand, need not be prefixed with self and will simply stop existing when the initialization function ends.\n", "\n", "You will also note that we have introduced a new keyword argument for Section, namely the cell attribute. This will always be set to self (i.e. the current cell) to allow each Section to know what cell it belongs to." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Recall that we can check the topology via:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.000086Z", "iopub.status.busy": "2025-08-18T03:35:40.999717Z", "iopub.status.idle": "2025-08-18T03:35:41.006030Z", "shell.execute_reply": "2025-08-18T03:35:41.005665Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "No sections were displayed. Why?\n", "\n", "The explanation is that we haven't actually created any such cells yet; we've only defined a rule for them. Let's go ahead and create our first cell:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.012874Z", "iopub.status.busy": "2025-08-18T03:35:41.012721Z", "iopub.status.idle": "2025-08-18T03:35:41.017521Z", "shell.execute_reply": "2025-08-18T03:35:41.017144Z" } }, "outputs": [], "source": [ "my_cell = BallAndStick()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We again check the topology and see that the sections have in fact been created:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.019091Z", "iopub.status.busy": "2025-08-18T03:35:41.018936Z", "iopub.status.idle": "2025-08-18T03:35:41.025237Z", "shell.execute_reply": "2025-08-18T03:35:41.024919Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| <__main__.BallAndStick object at 0x7b2441e3dd90>.soma(0-1)\n", "|-| <__main__.BallAndStick object at 0x7b2441e3dd90>.dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Clearly there is a soma and a dendrite, but the cell identifier before each is not very friendly.\n", "\n", "We can specify how the cell displays using the `__repr__` method:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.026881Z", "iopub.status.busy": "2025-08-18T03:35:41.026740Z", "iopub.status.idle": "2025-08-18T03:35:41.033515Z", "shell.execute_reply": "2025-08-18T03:35:41.033136Z" } }, "outputs": [], "source": [ "class BallAndStick:\n", " def __init__(self):\n", " self.soma = n.Section(\"soma\", self)\n", " self.dend = n.Section(\"dend\", self)\n", "\n", " def __repr__(self):\n", " return \"BallAndStick\"" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.035598Z", "iopub.status.busy": "2025-08-18T03:35:41.034910Z", "iopub.status.idle": "2025-08-18T03:35:41.043626Z", "shell.execute_reply": "2025-08-18T03:35:41.043235Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| <__main__.BallAndStick object at 0x7b2441e3dd90>.soma(0-1)\n", "|-| <__main__.BallAndStick object at 0x7b2441e3dd90>.dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our sections display based on the rule they were created with, not the new rule, so we need to recreate the cell:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.045402Z", "iopub.status.busy": "2025-08-18T03:35:41.045113Z", "iopub.status.idle": "2025-08-18T03:35:41.049657Z", "shell.execute_reply": "2025-08-18T03:35:41.049281Z" } }, "outputs": [], "source": [ "my_cell = BallAndStick()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we see something friendlier:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.052877Z", "iopub.status.busy": "2025-08-18T03:35:41.051039Z", "iopub.status.idle": "2025-08-18T03:35:41.058560Z", "shell.execute_reply": "2025-08-18T03:35:41.058179Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| BallAndStick.soma(0-1)\n", "|-| BallAndStick.dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There's a problem though; do you see it?\n", "\n", "Every cell using this rule would print out the same cell identifier. So if we create a second cell:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.062505Z", "iopub.status.busy": "2025-08-18T03:35:41.060097Z", "iopub.status.idle": "2025-08-18T03:35:41.064349Z", "shell.execute_reply": "2025-08-18T03:35:41.063990Z" } }, "outputs": [], "source": [ "my_other_cell = BallAndStick()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and look at the topology:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.066524Z", "iopub.status.busy": "2025-08-18T03:35:41.065939Z", "iopub.status.idle": "2025-08-18T03:35:41.073907Z", "shell.execute_reply": "2025-08-18T03:35:41.073549Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| BallAndStick.soma(0-1)\n", "|-| BallAndStick.dend(0-1)\n", "|-| BallAndStick.soma(0-1)\n", "|-| BallAndStick.dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is no way to tell the two somas apart and see which goes with which cell. To fix this, we'll pass in an identifier gid when we create the cell and have `__repr__` incorporate that into the name:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.075552Z", "iopub.status.busy": "2025-08-18T03:35:41.075191Z", "iopub.status.idle": "2025-08-18T03:35:41.081606Z", "shell.execute_reply": "2025-08-18T03:35:41.079867Z" } }, "outputs": [], "source": [ "class BallAndStick:\n", " def __init__(self, gid):\n", " self._gid = gid\n", " self.soma = n.Section(\"soma\", self)\n", " self.dend = n.Section(\"dend\", self)\n", "\n", " def __repr__(self):\n", " return \"BallAndStick[{}]\".format(self._gid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Important: the cell name (returned by `__repr__`) will be read when the Section is created, so any and all data that function needs -- here the `gid` -- must be stored before creating any Section objects." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's create our two cells:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.085498Z", "iopub.status.busy": "2025-08-18T03:35:41.083274Z", "iopub.status.idle": "2025-08-18T03:35:41.087438Z", "shell.execute_reply": "2025-08-18T03:35:41.087052Z" } }, "outputs": [], "source": [ "my_cell = BallAndStick(0)\n", "my_other_cell = BallAndStick(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now when we look at the topology, we can tell the Sections belonging to the two cells apart:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.090693Z", "iopub.status.busy": "2025-08-18T03:35:41.090543Z", "iopub.status.idle": "2025-08-18T03:35:41.097033Z", "shell.execute_reply": "2025-08-18T03:35:41.096662Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| BallAndStick[0].soma(0-1)\n", "|-| BallAndStick[0].dend(0-1)\n", "|-| BallAndStick[1].soma(0-1)\n", "|-| BallAndStick[1].dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can tell which sections are the soma and which are dendrites. We can see which go with cell 0 and which go with cell 1, but there is nothing indicating that the dendrite is connected to the soma. This is because we have not told NEURON about any such relationships, so let's do so:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Connect the sections" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We attach `self.dend` to the `self.soma` using the `connect` method:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.098701Z", "iopub.status.busy": "2025-08-18T03:35:41.098557Z", "iopub.status.idle": "2025-08-18T03:35:41.104617Z", "shell.execute_reply": "2025-08-18T03:35:41.102691Z" } }, "outputs": [], "source": [ "class BallAndStick:\n", " def __init__(self, gid):\n", " self._gid = gid\n", " self.soma = n.Section(\"soma\", self)\n", " self.dend = n.Section(\"dend\", self)\n", " self.dend.connect(self.soma)\n", "\n", " def __repr__(self):\n", " return \"BallAndStick[{}]\".format(self._gid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As before, we must recreate the cells now that we've changed the rule:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.106723Z", "iopub.status.busy": "2025-08-18T03:35:41.106060Z", "iopub.status.idle": "2025-08-18T03:35:41.111502Z", "shell.execute_reply": "2025-08-18T03:35:41.111137Z" } }, "outputs": [], "source": [ "my_cell = BallAndStick(0)\n", "my_other_cell = BallAndStick(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that this is not equivalent to attaching the `soma` to the `dend`; instead it means that the dendrite begins where the soma ends. We can see that in the topology:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.113278Z", "iopub.status.busy": "2025-08-18T03:35:41.113136Z", "iopub.status.idle": "2025-08-18T03:35:41.118894Z", "shell.execute_reply": "2025-08-18T03:35:41.118533Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| BallAndStick[0].soma(0-1)\n", " `| BallAndStick[0].dend(0-1)\n", "|-| BallAndStick[1].soma(0-1)\n", " `| BallAndStick[1].dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For now, we can get rid of `my_other_cell`:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.122651Z", "iopub.status.busy": "2025-08-18T03:35:41.122502Z", "iopub.status.idle": "2025-08-18T03:35:41.127470Z", "shell.execute_reply": "2025-08-18T03:35:41.127085Z" } }, "outputs": [], "source": [ "del my_other_cell" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.129567Z", "iopub.status.busy": "2025-08-18T03:35:41.128901Z", "iopub.status.idle": "2025-08-18T03:35:41.136841Z", "shell.execute_reply": "2025-08-18T03:35:41.136464Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| BallAndStick[0].soma(0-1)\n", " `| BallAndStick[0].dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A `soma` can have many dendrites attached to it, but any dendrite only begins at one specific location." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What if we didn't want to attach the dendrite to the end of the soma (position 1)? We could explicitly specify the connection location via, e.g. `self.dend.connect(self.soma(0.5))` which would mean the dendrite was attached to the center of the soma. (Recall: segments are described using normalized positions.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The 1 end of the soma is said to be the parent of the `dend` section." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define stylized geometry" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's set the length and the width for both sections. We'll make the soma have length and diameter of 12.6157 microns, the dendrite have length 200 microns and diameter 1 micron." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.138636Z", "iopub.status.busy": "2025-08-18T03:35:41.138490Z", "iopub.status.idle": "2025-08-18T03:35:41.144515Z", "shell.execute_reply": "2025-08-18T03:35:41.144141Z" } }, "outputs": [], "source": [ "class BallAndStick:\n", " def __init__(self, gid):\n", " self._gid = gid\n", " self.soma = n.Section(\"soma\", self)\n", " self.dend = n.Section(\"dend\", self)\n", " self.dend.connect(self.soma)\n", " self.soma.L = self.soma.diam = 12.6157 * µm\n", " self.dend.L = 200 * µm\n", " self.dend.diam = 1 * µm\n", "\n", " def __repr__(self):\n", " return \"BallAndStick[{}]\".format(self._gid)\n", "\n", "\n", "my_cell = BallAndStick(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you're wondering why that number was chosen for the soma length and diameter: it is because it makes the surface area (which doesn't include end faces) approximately 500 μm2:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.145965Z", "iopub.status.busy": "2025-08-18T03:35:41.145822Z", "iopub.status.idle": "2025-08-18T03:35:41.151005Z", "shell.execute_reply": "2025-08-18T03:35:41.150631Z" } }, "outputs": [ { "data": { "text/plain": [ "500.00296377255506" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_cell.soma(0.5).area()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(NEURON only returns areas of segments which is why we asked for the center `soma` segment; since there is only one segment, the area here is the same as the whole Section area.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the surface area of a cylinder with equal length and diameter\n", "$$\n", "\\pi d \\ell = \\pi d^2 = 4 \\pi \\left (\\frac{d}{2} \\right) ^2 = 4 \\pi r^2\n", "$$\n", "is the same as the surface area of a sphere with the same diameter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That is, if we're only interested in electrophysiology modeling, we can substitute a cylindrical soma with equal length and diameter for a spherical soma with the same diameter, as we've done here. (The volume, however, is of course different. So this substitution does not work if we're modeling diffusion or accumulation of ions.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For the rest of this tutorial page, we'll focus solely on one cell." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.154263Z", "iopub.status.busy": "2025-08-18T03:35:41.153692Z", "iopub.status.idle": "2025-08-18T03:35:41.161511Z", "shell.execute_reply": "2025-08-18T03:35:41.159733Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "|-| BallAndStick[0].soma(0-1)\n", " `| BallAndStick[0].dend(0-1)\n", "\n" ] }, { "data": { "text/plain": [ "1.0" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n.topology()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now it is time to see what the cell looks like:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "execution": { "iopub.execute_input": "2025-08-18T03:35:41.164967Z", "iopub.status.busy": "2025-08-18T03:35:41.164819Z", "iopub.status.idle": "2025-08-18T03:35:41.420462Z", "shell.execute_reply": "2025-08-18T03:35:41.420029Z" } }, "outputs": [ { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", "/* global mpl */\n", "window.mpl = {};\n", "\n", "mpl.get_websocket_type = function () {\n", " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", " alert(\n", " 'Your browser does not have WebSocket support. ' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.'\n", " );\n", " }\n", "};\n", "\n", "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", " warnings.textContent =\n", " 'This browser does not support binary websocket messages. ' +\n", " 'Performance may be slow.';\n", " }\n", " }\n", "\n", " this.imageObj = new Image();\n", "\n", " this.context = undefined;\n", " this.message = undefined;\n", " this.canvas = undefined;\n", " this.rubberband_canvas = undefined;\n", " this.rubberband_context = undefined;\n", " this.format_dropdown = undefined;\n", "\n", " this.image_mode = 'full';\n", "\n", " this.root = document.createElement('div');\n", " this.root.setAttribute('style', 'display: inline-block');\n", " this._root_extra_style(this.root);\n", "\n", " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", " this._init_toolbar(this);\n", "\n", " var fig = this;\n", "\n", " this.waiting = false;\n", "\n", " this.ws.onopen = function () {\n", " fig.send_message('supports_binary', { value: fig.supports_binary });\n", " fig.send_message('send_image_mode', {});\n", " if (fig.ratio !== 1) {\n", " fig.send_message('set_device_pixel_ratio', {\n", " device_pixel_ratio: fig.ratio,\n", " });\n", " }\n", " fig.send_message('refresh', {});\n", " };\n", "\n", " this.imageObj.onload = function () {\n", " if (fig.image_mode === 'full') {\n", " // Full images could contain transparency (where diff images\n", " // almost always do), so we need to clear the canvas so that\n", " // there is no ghosting.\n", " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", " }\n", " fig.context.drawImage(fig.imageObj, 0, 0);\n", " };\n", "\n", " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", "};\n", "\n", "mpl.figure.prototype._init_header = function () {\n", " var titlebar = document.createElement('div');\n", " titlebar.classList =\n", " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", " var titletext = document.createElement('div');\n", " titletext.classList = 'ui-dialog-title';\n", " titletext.setAttribute(\n", " 'style',\n", " 'width: 100%; text-align: center; padding: 3px;'\n", " );\n", " titlebar.appendChild(titletext);\n", " this.root.appendChild(titlebar);\n", " this.header = titletext;\n", "};\n", "\n", "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", " var canvas_div = (this.canvas_div = document.createElement('div'));\n", " canvas_div.setAttribute('tabindex', '0');\n", " canvas_div.setAttribute(\n", " 'style',\n", " 'border: 1px solid #ddd;' +\n", " 'box-sizing: content-box;' +\n", " 'clear: both;' +\n", " 'min-height: 1px;' +\n", " 'min-width: 1px;' +\n", " 'outline: 0;' +\n", " 'overflow: hidden;' +\n", " 'position: relative;' +\n", " 'resize: both;' +\n", " 'z-index: 2;'\n", " );\n", "\n", " function on_keyboard_event_closure(name) {\n", " return function (event) {\n", " return fig.key_event(event, name);\n", " };\n", " }\n", "\n", " canvas_div.addEventListener(\n", " 'keydown',\n", " on_keyboard_event_closure('key_press')\n", " );\n", " canvas_div.addEventListener(\n", " 'keyup',\n", " on_keyboard_event_closure('key_release')\n", " );\n", "\n", " this._canvas_extra_style(canvas_div);\n", " this.root.appendChild(canvas_div);\n", "\n", " var canvas = (this.canvas = document.createElement('canvas'));\n", " canvas.classList.add('mpl-canvas');\n", " canvas.setAttribute(\n", " 'style',\n", " 'box-sizing: content-box;' +\n", " 'pointer-events: none;' +\n", " 'position: relative;' +\n", " 'z-index: 0;'\n", " );\n", "\n", " this.context = canvas.getContext('2d');\n", "\n", " var backingStore =\n", " this.context.backingStorePixelRatio ||\n", " this.context.webkitBackingStorePixelRatio ||\n", " this.context.mozBackingStorePixelRatio ||\n", " this.context.msBackingStorePixelRatio ||\n", " this.context.oBackingStorePixelRatio ||\n", " this.context.backingStorePixelRatio ||\n", " 1;\n", "\n", " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", " 'canvas'\n", " ));\n", " rubberband_canvas.setAttribute(\n", " 'style',\n", " 'box-sizing: content-box;' +\n", " 'left: 0;' +\n", " 'pointer-events: none;' +\n", " 'position: absolute;' +\n", " 'top: 0;' +\n", " 'z-index: 1;'\n", " );\n", "\n", " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", " if (this.ResizeObserver === undefined) {\n", " if (window.ResizeObserver !== undefined) {\n", " this.ResizeObserver = window.ResizeObserver;\n", " } else {\n", " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", " this.ResizeObserver = obs.ResizeObserver;\n", " }\n", " }\n", "\n", " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", " // There's no need to resize if the WebSocket is not connected:\n", " // - If it is still connecting, then we will get an initial resize from\n", " // Python once it connects.\n", " // - If it has disconnected, then resizing will clear the canvas and\n", " // never get anything back to refill it, so better to not resize and\n", " // keep something visible.\n", " if (fig.ws.readyState != 1) {\n", " return;\n", " }\n", " var nentries = entries.length;\n", " for (var i = 0; i < nentries; i++) {\n", " var entry = entries[i];\n", " var width, height;\n", " if (entry.contentBoxSize) {\n", " if (entry.contentBoxSize instanceof Array) {\n", " // Chrome 84 implements new version of spec.\n", " width = entry.contentBoxSize[0].inlineSize;\n", " height = entry.contentBoxSize[0].blockSize;\n", " } else {\n", " // Firefox implements old version of spec.\n", " width = entry.contentBoxSize.inlineSize;\n", " height = entry.contentBoxSize.blockSize;\n", " }\n", " } else {\n", " // Chrome <84 implements even older version of spec.\n", " width = entry.contentRect.width;\n", " height = entry.contentRect.height;\n", " }\n", "\n", " // Keep the size of the canvas and rubber band canvas in sync with\n", " // the canvas container.\n", " if (entry.devicePixelContentBoxSize) {\n", " // Chrome 84 implements new version of spec.\n", " canvas.setAttribute(\n", " 'width',\n", " entry.devicePixelContentBoxSize[0].inlineSize\n", " );\n", " canvas.setAttribute(\n", " 'height',\n", " entry.devicePixelContentBoxSize[0].blockSize\n", " );\n", " } else {\n", " canvas.setAttribute('width', width * fig.ratio);\n", " canvas.setAttribute('height', height * fig.ratio);\n", " }\n", " /* This rescales the canvas back to display pixels, so that it\n", " * appears correct on HiDPI screens. */\n", " canvas.style.width = width + 'px';\n", " canvas.style.height = height + 'px';\n", "\n", " rubberband_canvas.setAttribute('width', width);\n", " rubberband_canvas.setAttribute('height', height);\n", "\n", " // And update the size in Python. We ignore the initial 0/0 size\n", " // that occurs as the element is placed into the DOM, which should\n", " // otherwise not happen due to the minimum size styling.\n", " if (width != 0 && height != 0) {\n", " fig.request_resize(width, height);\n", " }\n", " }\n", " });\n", " this.resizeObserverInstance.observe(canvas_div);\n", "\n", " function on_mouse_event_closure(name) {\n", " /* User Agent sniffing is bad, but WebKit is busted:\n", " * https://bugs.webkit.org/show_bug.cgi?id=144526\n", " * https://bugs.webkit.org/show_bug.cgi?id=181818\n", " * The worst that happens here is that they get an extra browser\n", " * selection when dragging, if this check fails to catch them.\n", " */\n", " var UA = navigator.userAgent;\n", " var isWebKit = /AppleWebKit/.test(UA) && !/Chrome/.test(UA);\n", " if(isWebKit) {\n", " return function (event) {\n", " /* This prevents the web browser from automatically changing to\n", " * the text insertion cursor when the button is pressed. We\n", " * want to control all of the cursor setting manually through\n", " * the 'cursor' event from matplotlib */\n", " event.preventDefault()\n", " return fig.mouse_event(event, name);\n", " };\n", " } else {\n", " return function (event) {\n", " return fig.mouse_event(event, name);\n", " };\n", " }\n", " }\n", "\n", " canvas_div.addEventListener(\n", " 'mousedown',\n", " on_mouse_event_closure('button_press')\n", " );\n", " canvas_div.addEventListener(\n", " 'mouseup',\n", " on_mouse_event_closure('button_release')\n", " );\n", " canvas_div.addEventListener(\n", " 'dblclick',\n", " on_mouse_event_closure('dblclick')\n", " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", " canvas_div.addEventListener(\n", " 'mousemove',\n", " on_mouse_event_closure('motion_notify')\n", " );\n", "\n", " canvas_div.addEventListener(\n", " 'mouseenter',\n", " on_mouse_event_closure('figure_enter')\n", " );\n", " canvas_div.addEventListener(\n", " 'mouseleave',\n", " on_mouse_event_closure('figure_leave')\n", " );\n", "\n", " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", " canvas_div.appendChild(canvas);\n", " canvas_div.appendChild(rubberband_canvas);\n", "\n", " this.rubberband_context = rubberband_canvas.getContext('2d');\n", " this.rubberband_context.strokeStyle = '#000000';\n", "\n", " this._resize_canvas = function (width, height, forward) {\n", " if (forward) {\n", " canvas_div.style.width = width + 'px';\n", " canvas_div.style.height = height + 'px';\n", " }\n", " };\n", "\n", " // Disable right mouse context menu.\n", " canvas_div.addEventListener('contextmenu', function (_e) {\n", " event.preventDefault();\n", " return false;\n", " });\n", "\n", " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", "};\n", "\n", "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", " var toolbar = document.createElement('div');\n", " toolbar.classList = 'mpl-toolbar';\n", " this.root.appendChild(toolbar);\n", "\n", " function on_click_closure(name) {\n", " return function (_event) {\n", " return fig.toolbar_button_onclick(name);\n", " };\n", " }\n", "\n", " function on_mouseover_closure(tooltip) {\n", " return function (event) {\n", " if (!event.currentTarget.disabled) {\n", " return fig.toolbar_button_onmouseover(tooltip);\n", " }\n", " };\n", " }\n", "\n", " fig.buttons = {};\n", " var buttonGroup = document.createElement('div');\n", " buttonGroup.classList = 'mpl-button-group';\n", " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", " /* Instead of a spacer, we start a new button group. */\n", " if (buttonGroup.hasChildNodes()) {\n", " toolbar.appendChild(buttonGroup);\n", " }\n", " buttonGroup = document.createElement('div');\n", " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", "\n", " var button = (fig.buttons[name] = document.createElement('button'));\n", " button.classList = 'mpl-widget';\n", " button.setAttribute('role', 'button');\n", " button.setAttribute('aria-disabled', 'false');\n", " button.addEventListener('click', on_click_closure(method_name));\n", " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", "\n", " var icon_img = document.createElement('img');\n", " icon_img.src = '_images/' + image + '.png';\n", " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", " icon_img.alt = tooltip;\n", " button.appendChild(icon_img);\n", "\n", " buttonGroup.appendChild(button);\n", " }\n", "\n", " if (buttonGroup.hasChildNodes()) {\n", " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " var fmt_picker = document.createElement('select');\n", " fmt_picker.classList = 'mpl-widget';\n", " toolbar.appendChild(fmt_picker);\n", " this.format_dropdown = fmt_picker;\n", "\n", " for (var ind in mpl.extensions) {\n", " var fmt = mpl.extensions[ind];\n", " var option = document.createElement('option');\n", " option.selected = fmt === mpl.default_extension;\n", " option.innerHTML = fmt;\n", " fmt_picker.appendChild(option);\n", " }\n", "\n", " var status_bar = document.createElement('span');\n", " status_bar.classList = 'mpl-message';\n", " toolbar.appendChild(status_bar);\n", " this.message = status_bar;\n", "};\n", "\n", "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", " // which will in turn request a refresh of the image.\n", " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", "};\n", "\n", "mpl.figure.prototype.send_message = function (type, properties) {\n", " properties['type'] = type;\n", " properties['figure_id'] = this.id;\n", " this.ws.send(JSON.stringify(properties));\n", "};\n", "\n", "mpl.figure.prototype.send_draw_message = function () {\n", " if (!this.waiting) {\n", " this.waiting = true;\n", " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", " }\n", "};\n", "\n", "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " var format_dropdown = fig.format_dropdown;\n", " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", " fig.ondownload(fig, format);\n", "};\n", "\n", "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", " var size = msg['size'];\n", " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", " fig._resize_canvas(size[0], size[1], msg['forward']);\n", " fig.send_message('refresh', {});\n", " }\n", "};\n", "\n", "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", " var x0 = msg['x0'] / fig.ratio;\n", " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", " var x1 = msg['x1'] / fig.ratio;\n", " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", " x0 = Math.floor(x0) + 0.5;\n", " y0 = Math.floor(y0) + 0.5;\n", " x1 = Math.floor(x1) + 0.5;\n", " y1 = Math.floor(y1) + 0.5;\n", " var min_x = Math.min(x0, x1);\n", " var min_y = Math.min(y0, y1);\n", " var width = Math.abs(x1 - x0);\n", " var height = Math.abs(y1 - y0);\n", "\n", " fig.rubberband_context.clearRect(\n", " 0,\n", " 0,\n", " fig.canvas.width / fig.ratio,\n", " fig.canvas.height / fig.ratio\n", " );\n", "\n", " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", "};\n", "\n", "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", " // Updates the figure title.\n", " fig.header.textContent = msg['label'];\n", "};\n", "\n", "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", " fig.canvas_div.style.cursor = msg['cursor'];\n", "};\n", "\n", "mpl.figure.prototype.handle_message = function (fig, msg) {\n", " fig.message.textContent = msg['message'];\n", "};\n", "\n", "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", " // Request the server to send over a new figure.\n", " fig.send_draw_message();\n", "};\n", "\n", "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", " fig.image_mode = msg['mode'];\n", "};\n", "\n", "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", " for (var key in msg) {\n", " if (!(key in fig.buttons)) {\n", " continue;\n", " }\n", " fig.buttons[key].disabled = !msg[key];\n", " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", " }\n", "};\n", "\n", "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", " if (msg['mode'] === 'PAN') {\n", " fig.buttons['Pan'].classList.add('active');\n", " fig.buttons['Zoom'].classList.remove('active');\n", " } else if (msg['mode'] === 'ZOOM') {\n", " fig.buttons['Pan'].classList.remove('active');\n", " fig.buttons['Zoom'].classList.add('active');\n", " } else {\n", " fig.buttons['Pan'].classList.remove('active');\n", " fig.buttons['Zoom'].classList.remove('active');\n", " }\n", "};\n", "\n", "mpl.figure.prototype.updated_canvas_event = function () {\n", " // Called whenever the canvas gets updated.\n", " this.send_message('ack', {});\n", "};\n", "\n", "// A function to construct a web socket function for onmessage handling.\n", "// Called in the figure constructor.\n", "mpl.figure.prototype._make_on_message_function = function (fig) {\n", " return function socket_on_message(evt) {\n", " if (evt.data instanceof Blob) {\n", " var img = evt.data;\n", " if (img.type !== 'image/png') {\n", " /* FIXME: We get \"Resource interpreted as Image but\n", " * transferred with MIME type text/plain:\" errors on\n", " * Chrome. But how to set the MIME type? It doesn't seem\n", " * to be part of the websocket stream */\n", " img.type = 'image/png';\n", " }\n", "\n", " /* Free the memory for the previous frames */\n", " if (fig.imageObj.src) {\n", " (window.URL || window.webkitURL).revokeObjectURL(\n", " fig.imageObj.src\n", " );\n", " }\n", "\n", " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", " img\n", " );\n", " fig.updated_canvas_event();\n", " fig.waiting = false;\n", " return;\n", " } else if (\n", " typeof evt.data === 'string' &&\n", " evt.data.slice(0, 21) === 'data:image/png;base64'\n", " ) {\n", " fig.imageObj.src = evt.data;\n", " fig.updated_canvas_event();\n", " fig.waiting = false;\n", " return;\n", " }\n", "\n", " var msg = JSON.parse(evt.data);\n", " var msg_type = msg['type'];\n", "\n", " // Call the \"handle_{type}\" callback, which takes\n", " // the figure and JSON message as its only arguments.\n", " try {\n", " var callback = fig['handle_' + msg_type];\n", " } catch (e) {\n", " console.log(\n", " \"No handler for the '\" + msg_type + \"' message type: \",\n", " msg\n", " );\n", " return;\n", " }\n", "\n", " if (callback) {\n", " try {\n", " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", " callback(fig, msg);\n", " } catch (e) {\n", " console.log(\n", " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", " e,\n", " e.stack,\n", " msg\n", " );\n", " }\n", " }\n", " };\n", "};\n", "\n", "function getModifiers(event) {\n", " var mods = [];\n", " if (event.ctrlKey) {\n", " mods.push('ctrl');\n", " }\n", " if (event.altKey) {\n", " mods.push('alt');\n", " }\n", " if (event.shiftKey) {\n", " mods.push('shift');\n", " }\n", " if (event.metaKey) {\n", " mods.push('meta');\n", " }\n", " return mods;\n", "}\n", "\n", "/*\n", " * return a copy of an object with only non-object keys\n", " * we need this to avoid circular references\n", " * https://stackoverflow.com/a/24161582/3208463\n", " */\n", "function simpleKeys(original) {\n", " return Object.keys(original).reduce(function (obj, key) {\n", " if (typeof original[key] !== 'object') {\n", " obj[key] = original[key];\n", " }\n", " return obj;\n", " }, {});\n", "}\n", "\n", "mpl.figure.prototype.mouse_event = function (event, name) {\n", " if (name === 'button_press') {\n", " this.canvas.focus();\n", " this.canvas_div.focus();\n", " }\n", "\n", " // from https://stackoverflow.com/q/1114465\n", " var boundingRect = this.canvas.getBoundingClientRect();\n", " var x = (event.clientX - boundingRect.left) * this.ratio;\n", " var y = (event.clientY - boundingRect.top) * this.ratio;\n", "\n", " this.send_message(name, {\n", " x: x,\n", " y: y,\n", " button: event.button,\n", " step: event.step,\n", " buttons: event.buttons,\n", " modifiers: getModifiers(event),\n", " guiEvent: simpleKeys(event),\n", " });\n", "\n", " return false;\n", "};\n", "\n", "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", " // Handle any extra behaviour associated with a key event\n", "};\n", "\n", "mpl.figure.prototype.key_event = function (event, name) {\n", " // Prevent repeat events\n", " if (name === 'key_press') {\n", " if (event.key === this._key) {\n", " return;\n", " } else {\n", " this._key = event.key;\n", " }\n", " }\n", " if (name === 'key_release') {\n", " this._key = null;\n", " }\n", "\n", " var value = '';\n", " if (event.ctrlKey && event.key !== 'Control') {\n", " value += 'ctrl+';\n", " }\n", " else if (event.altKey && event.key !== 'Alt') {\n", " value += 'alt+';\n", " }\n", " else if (event.shiftKey && event.key !== 'Shift') {\n", " value += 'shift+';\n", " }\n", "\n", " value += 'k' + event.key;\n", "\n", " this._key_event_extra(event, name);\n", "\n", " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", " return false;\n", "};\n", "\n", "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", " if (name === 'download') {\n", " this.handle_save(this, null);\n", " } else {\n", " this.send_message('toolbar_button', { name: name });\n", " }\n", "};\n", "\n", "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", " this.message.textContent = tooltip;\n", "};\n", "\n", "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", "// prettier-ignore\n", "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis\", \"fa fa-square-o\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o\", \"download\"]];\n", "\n", "mpl.extensions = [\"eps\", \"jpeg\", \"pgf\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\", \"webp\"];\n", "\n", "mpl.default_extension = \"png\";/* global mpl */\n", "\n", "var comm_websocket_adapter = function (comm) {\n", " // Create a \"websocket\"-like object which calls the given IPython comm\n", " // object with the appropriate methods. Currently this is a non binary\n", " // socket, so there is still some room for performance tuning.\n", " var ws = {};\n", "\n", " ws.binaryType = comm.kernel.ws.binaryType;\n", " ws.readyState = comm.kernel.ws.readyState;\n", " function updateReadyState(_event) {\n", " if (comm.kernel.ws) {\n", " ws.readyState = comm.kernel.ws.readyState;\n", " } else {\n", " ws.readyState = 3; // Closed state.\n", " }\n", " }\n", " comm.kernel.ws.addEventListener('open', updateReadyState);\n", " comm.kernel.ws.addEventListener('close', updateReadyState);\n", " comm.kernel.ws.addEventListener('error', updateReadyState);\n", "\n", " ws.close = function () {\n", " comm.close();\n", " };\n", " ws.send = function (m) {\n", " //console.log('sending', m);\n", " comm.send(m);\n", " };\n", " // Register the callback with on_msg.\n", " comm.on_msg(function (msg) {\n", " //console.log('receiving', msg['content']['data'], msg);\n", " var data = msg['content']['data'];\n", " if (data['blob'] !== undefined) {\n", " data = {\n", " data: new Blob(msg['buffers'], { type: data['blob'] }),\n", " };\n", " }\n", " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", " ws.onmessage(data);\n", " });\n", " return ws;\n", "};\n", "\n", "mpl.mpl_figure_comm = function (comm, msg) {\n", " // This is the function which gets called when the mpl process\n", " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", "\n", " var id = msg.content.data.id;\n", " // Get hold of the div created by the display call when the Comm\n", " // socket was opened in Python.\n", " var element = document.getElementById(id);\n", " var ws_proxy = comm_websocket_adapter(comm);\n", "\n", " function ondownload(figure, _format) {\n", " window.open(figure.canvas.toDataURL());\n", " }\n", "\n", " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", "\n", " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", " // web socket which is closed, not our websocket->open comm proxy.\n", " ws_proxy.onopen();\n", "\n", " fig.parent_element = element;\n", " fig.cell_info = mpl.find_output_cell(\"
\");\n", " if (!fig.cell_info) {\n", " console.error('Failed to find cell for figure', id, fig);\n", " return;\n", " }\n", " fig.cell_info[0].output_area.element.on(\n", " 'cleared',\n", " { fig: fig },\n", " fig._remove_fig_handler\n", " );\n", "};\n", "\n", "mpl.figure.prototype.handle_close = function (fig, msg) {\n", " var width = fig.canvas.width / fig.ratio;\n", " fig.cell_info[0].output_area.element.off(\n", " 'cleared',\n", " fig._remove_fig_handler\n", " );\n", " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", "\n", " // Update the output cell to use the data from the current canvas.\n", " fig.push_to_output();\n", " var dataURL = fig.canvas.toDataURL();\n", " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", " // the notebook keyboard shortcuts fail.\n", " IPython.keyboard_manager.enable();\n", " fig.parent_element.innerHTML =\n", " 'units()
. Pass in a string with the paramater name, an underscore, and then the mechanism name. e.g."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.537685Z",
"iopub.status.busy": "2025-08-18T03:35:41.537539Z",
"iopub.status.idle": "2025-08-18T03:35:41.540481Z",
"shell.execute_reply": "2025-08-18T03:35:41.540108Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S/cm2\n"
]
}
],
"source": [
"print(n.units(\"gnabar_hh\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use `psection` to see what is present where:"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.541877Z",
"iopub.status.busy": "2025-08-18T03:35:41.541742Z",
"iopub.status.idle": "2025-08-18T03:35:41.550546Z",
"shell.execute_reply": "2025-08-18T03:35:41.550156Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"BallAndStick[0].soma: hh\n",
"BallAndStick[0].dend: pas\n"
]
}
],
"source": [
"for sec in n.allsec():\n",
" print(\"%s: %s\" % (sec, \", \".join(sec.psection()[\"density_mechs\"].keys())))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(A quick aside about `psection`: it's great for quickly getting information when interactively exploring a model because it provides a lot of data in one pass; for the same reason, however, other solutions that only extract specific desired information are more efficient for automatic explorations.)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Instrumentation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have now created our neuron. Let's stimulate it and visualize its dynamics."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Stimulation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll inject a current pulse into the distal (1) end of the dendrite starting 5 ms after the simulation starts, with a duration of 1 ms, and an amplitude of 0.1 nA. First, let's define and position the current clamp object:"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.552447Z",
"iopub.status.busy": "2025-08-18T03:35:41.552240Z",
"iopub.status.idle": "2025-08-18T03:35:41.555303Z",
"shell.execute_reply": "2025-08-18T03:35:41.554942Z"
}
},
"outputs": [],
"source": [
"stim = n.IClamp(my_cell.dend(1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we want, we can check the segment the current clamp is inserted into:"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.557729Z",
"iopub.status.busy": "2025-08-18T03:35:41.557585Z",
"iopub.status.idle": "2025-08-18T03:35:41.563309Z",
"shell.execute_reply": "2025-08-18T03:35:41.562941Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"BallAndStick[0].dend(1)"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stim.get_segment()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Recall that if we forget what the names of the attributes are, we can check the `dir`. Here we do that and ignore Python-created attributes:"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.564950Z",
"iopub.status.busy": "2025-08-18T03:35:41.564812Z",
"iopub.status.idle": "2025-08-18T03:35:41.570537Z",
"shell.execute_reply": "2025-08-18T03:35:41.570150Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"amp, baseattr, delay, dur, get_loc, get_segment, has_loc, hname, hocobjptr, i, loc, same\n"
]
}
],
"source": [
"print(\", \".join(item for item in dir(stim) if not item.startswith(\"__\")))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The parameters we need to set for a current clamp are `delay` (measured in ms), `dur` (measured in ms), and `amp` (in nA):"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.573805Z",
"iopub.status.busy": "2025-08-18T03:35:41.573665Z",
"iopub.status.idle": "2025-08-18T03:35:41.577014Z",
"shell.execute_reply": "2025-08-18T03:35:41.576412Z"
}
},
"outputs": [],
"source": [
"stim.delay = 5\n",
"stim.dur = 1\n",
"stim.amp = 0.1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Recording"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll start out recording the membrane potential at the center of the soma and the time in two NEURON Vectors:"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.580678Z",
"iopub.status.busy": "2025-08-18T03:35:41.580536Z",
"iopub.status.idle": "2025-08-18T03:35:41.583587Z",
"shell.execute_reply": "2025-08-18T03:35:41.583242Z"
}
},
"outputs": [],
"source": [
"soma_v = n.Vector().record(my_cell.soma(0.5)._ref_v)\n",
"t = n.Vector().record(n._ref_t)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Run the simulation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We initialize membrane potential everywhere to -65 mV:"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.587011Z",
"iopub.status.busy": "2025-08-18T03:35:41.586863Z",
"iopub.status.idle": "2025-08-18T03:35:41.593164Z",
"shell.execute_reply": "2025-08-18T03:35:41.592817Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"1.0"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n.finitialize(-65 * mV)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we run until time 25 ms:"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.596206Z",
"iopub.status.busy": "2025-08-18T03:35:41.596065Z",
"iopub.status.idle": "2025-08-18T03:35:41.607899Z",
"shell.execute_reply": "2025-08-18T03:35:41.607490Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"0.0"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n.continuerun(25 * ms)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plot the results"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As in the scripting neuron basics part of the tutorial, we initialize `bokeh` graphics:"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"execution": {
"iopub.execute_input": "2025-08-18T03:35:41.609476Z",
"iopub.status.busy": "2025-08-18T03:35:41.609316Z",
"iopub.status.idle": "2025-08-18T03:35:42.176952Z",
"shell.execute_reply": "2025-08-18T03:35:42.176588Z"
}
},
"outputs": [
{
"data": {
"text/html": [
" \n",
" \n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/javascript": [
"'use strict';\n",
"(function(root) {\n",
" function now() {\n",
" return new Date();\n",
" }\n",
"\n",
" const force = true;\n",
"\n",
" if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n",
" root._bokeh_onload_callbacks = [];\n",
" root._bokeh_is_loading = undefined;\n",
" }\n",
"\n",
"const JS_MIME_TYPE = 'application/javascript';\n",
" const HTML_MIME_TYPE = 'text/html';\n",
" const EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n",
" const CLASS_NAME = 'output_bokeh rendered_html';\n",
"\n",
" /**\n",
" * Render data to the DOM node\n",
" */\n",
" function render(props, node) {\n",
" const script = document.createElement(\"script\");\n",
" node.appendChild(script);\n",
" }\n",
"\n",
" /**\n",
" * Handle when an output is cleared or removed\n",
" */\n",
" function handleClearOutput(event, handle) {\n",
" function drop(id) {\n",
" const view = Bokeh.index.get_by_id(id)\n",
" if (view != null) {\n",
" view.model.document.clear()\n",
" Bokeh.index.delete(view)\n",
" }\n",
" }\n",
"\n",
" const cell = handle.cell;\n",
"\n",
" const id = cell.output_area._bokeh_element_id;\n",
" const server_id = cell.output_area._bokeh_server_id;\n",
"\n",
" // Clean up Bokeh references\n",
" if (id != null) {\n",
" drop(id)\n",
" }\n",
"\n",
" if (server_id !== undefined) {\n",
" // Clean up Bokeh references\n",
" const cmd_clean = \"from bokeh.io.state import curstate; print(curstate().uuid_to_server['\" + server_id + \"'].get_sessions()[0].document.roots[0]._id)\";\n",
" cell.notebook.kernel.execute(cmd_clean, {\n",
" iopub: {\n",
" output: function(msg) {\n",
" const id = msg.content.text.trim()\n",
" drop(id)\n",
" }\n",
" }\n",
" });\n",
" // Destroy server and session\n",
" const cmd_destroy = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n",
" cell.notebook.kernel.execute(cmd_destroy);\n",
" }\n",
" }\n",
"\n",
" /**\n",
" * Handle when a new output is added\n",
" */\n",
" function handleAddOutput(event, handle) {\n",
" const output_area = handle.output_area;\n",
" const output = handle.output;\n",
"\n",
" // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n",
" if ((output.output_type != \"display_data\") || (!Object.prototype.hasOwnProperty.call(output.data, EXEC_MIME_TYPE))) {\n",
" return\n",
" }\n",
"\n",
" const toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n",
"\n",
" if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n",
" toinsert[toinsert.length - 1].firstChild.textContent = output.data[JS_MIME_TYPE];\n",
" // store reference to embed id on output_area\n",
" output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n",
" }\n",
" if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n",
" const bk_div = document.createElement(\"div\");\n",
" bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n",
" const script_attrs = bk_div.children[0].attributes;\n",
" for (let i = 0; i < script_attrs.length; i++) {\n",
" toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n",
" toinsert[toinsert.length - 1].firstChild.textContent = bk_div.children[0].textContent\n",
" }\n",
" // store reference to server id on output_area\n",
" output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n",
" }\n",
" }\n",
"\n",
" function register_renderer(events, OutputArea) {\n",
"\n",
" function append_mime(data, metadata, element) {\n",
" // create a DOM node to render to\n",
" const toinsert = this.create_output_subarea(\n",
" metadata,\n",
" CLASS_NAME,\n",
" EXEC_MIME_TYPE\n",
" );\n",
" this.keyboard_manager.register_events(toinsert);\n",
" // Render to node\n",
" const props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n",
" render(props, toinsert[toinsert.length - 1]);\n",
" element.append(toinsert);\n",
" return toinsert\n",
" }\n",
"\n",
" /* Handle when an output is cleared or removed */\n",
" events.on('clear_output.CodeCell', handleClearOutput);\n",
" events.on('delete.Cell', handleClearOutput);\n",
"\n",
" /* Handle when a new output is added */\n",
" events.on('output_added.OutputArea', handleAddOutput);\n",
"\n",
" /**\n",
" * Register the mime type and append_mime function with output_area\n",
" */\n",
" OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n",
" /* Is output safe? */\n",
" safe: true,\n",
" /* Index of renderer in `output_area.display_order` */\n",
" index: 0\n",
" });\n",
" }\n",
"\n",
" // register the mime type if in Jupyter Notebook environment and previously unregistered\n",
" if (root.Jupyter !== undefined) {\n",
" const events = require('base/js/events');\n",
" const OutputArea = require('notebook/js/outputarea').OutputArea;\n",
"\n",
" if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n",
" register_renderer(events, OutputArea);\n",
" }\n",
" }\n",
" if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n",
" root._bokeh_timeout = Date.now() + 5000;\n",
" root._bokeh_failed_load = false;\n",
" }\n",
"\n",
" const NB_LOAD_WARNING = {'data': {'text/html':\n",
" \"\\n\"+\n", " \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n", " \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n", " \"
\\n\"+\n", " \"\\n\"+\n",
" \"from bokeh.resources import INLINE\\n\"+\n",
" \"output_notebook(resources=INLINE)\\n\"+\n",
" \"
\\n\"+\n",
" \"\\n\"+\n \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n \"
\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"
\\n\"+\n \"